Bundle: redb-route / tests/redb.Route.Tests.Llm.Mcp (tests.redb.Route.Tests.Llm.Mcp.txt), 19 files Snapshot: development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Index: https://redbase.app/src/dev-2026-12-06/redb-route/_index.txt ==== Path: redb-route/tests/redb.Route.Tests.Llm.Mcp/ComponentSideTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Llm.Mcp/ComponentSideTests.cs ---- using redb.Route.Core; using redb.Route.Llm.Mcp; namespace redb.Route.Tests.Llm.Mcp; /// The component declares the only side it has ([EndpointRole], Apache Camel's producerOnly / consumerOnly). public sealed class ComponentSideTests { [Fact] public void The_component_declares_its_only_side() { EndpointSides.Declaration(typeof(McpComponent))!.Role.Should().Be(EndpointRole.Producer); } } Path: redb-route/tests/redb.Route.Tests.Llm.Mcp/Framing/StdioJsonRpcFramingTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Llm.Mcp/Framing/StdioJsonRpcFramingTests.cs ---- using System.Text.Json; using System.Text.Json.Nodes; using redb.Route.Llm.Mcp.Protocol; namespace redb.Route.Tests.Llm.Mcp.Framing; /// /// Pure unit coverage of : response demux, monotonic /// id generation, notification dispatch, transport-failure unwind, cancellation /// emitting notifications/cancelled. No process spawning, no transport. /// public sealed class StdioJsonRpcFramingTests { [Fact] public async Task CallTool_ResponseDelivered_OnIdMatch() { var client = new TestableMcpClient("test"); // Drive a tools/call without going through Initialize; capture id from the request frame. var callTask = client.CallToolAsync("get_x", new JsonObject { ["a"] = 1 }, CancellationToken.None); await WaitForFrameAsync(client, 0); var requestFrame = client.SentFrames[0]; var id = JsonNode.Parse(requestFrame)!["id"]!.GetValue(); var response = new JsonObject { ["jsonrpc"] = "2.0", ["id"] = id, ["result"] = new JsonObject { ["content"] = new JsonArray(new JsonObject { ["type"] = "text", ["text"] = "hello" }), ["isError"] = false, }, }; client.InjectFrame(response.ToJsonString()); var result = await callTask; result.IsError.Should().BeFalse(); result.Content!.AsArray()[0]!["text"]!.GetValue().Should().Be("hello"); } [Fact] public async Task CallTool_OutOfOrderResponses_AreCorrectlyDemuxed() { var client = new TestableMcpClient("test"); var task1 = client.CallToolAsync("first", null, CancellationToken.None); var task2 = client.CallToolAsync("second", null, CancellationToken.None); await WaitForFrameAsync(client, 1); var id1 = JsonNode.Parse(client.SentFrames[0])!["id"]!.GetValue(); var id2 = JsonNode.Parse(client.SentFrames[1])!["id"]!.GetValue(); id2.Should().BeGreaterThan(id1); // Reply to #2 before #1 — both must resolve correctly. client.InjectFrame(BuildResultFrame(id2, "second-result")); client.InjectFrame(BuildResultFrame(id1, "first-result")); (await task1).Content!.AsArray()[0]!["text"]!.GetValue().Should().Be("first-result"); (await task2).Content!.AsArray()[0]!["text"]!.GetValue().Should().Be("second-result"); } [Fact] public async Task CallTool_ServerError_RaisesMcpException() { var client = new TestableMcpClient("test"); var task = client.CallToolAsync("broken", null, CancellationToken.None); await WaitForFrameAsync(client, 0); var id = JsonNode.Parse(client.SentFrames[0])!["id"]!.GetValue(); var errorFrame = new JsonObject { ["jsonrpc"] = "2.0", ["id"] = id, ["error"] = new JsonObject { ["code"] = -32601, ["message"] = "method not found" }, }; client.InjectFrame(errorFrame.ToJsonString()); var act = async () => await task; await act.Should().ThrowAsync().WithMessage("*method not found*"); } [Fact] public void NonJsonFrame_IsSkipped_WithoutCrashing() { var client = new TestableMcpClient("test"); // Garbage / log line bleed. Must not throw. client.InjectFrame("INFO: server started"); client.InjectFrame(""); client.InjectFrame(" not-json "); client.InjectFrame("{ this is not valid json"); } [Fact] public async Task ListChangedNotification_RaisesToolsChangedEvent() { var client = new TestableMcpClient("test"); var raised = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); client.ToolsChanged += (_, _) => raised.TrySetResult(true); client.InjectFrame("""{"jsonrpc":"2.0","method":"notifications/tools/list_changed"}"""); var fired = await Task.WhenAny(raised.Task, Task.Delay(1_000)) == raised.Task; fired.Should().BeTrue("tools/list_changed must propagate to subscribers"); } [Fact] public async Task TransportFailure_FailsAllPendingRequests() { var client = new TestableMcpClient("test"); var t1 = client.CallToolAsync("a", null, CancellationToken.None); var t2 = client.CallToolAsync("b", null, CancellationToken.None); await WaitForFrameAsync(client, 1); client.InjectTransportFailure("process exited"); var act1 = async () => await t1; var act2 = async () => await t2; await act1.Should().ThrowAsync().WithMessage("*transport failed*process exited*"); await act2.Should().ThrowAsync().WithMessage("*transport failed*process exited*"); } [Fact] public async Task Cancellation_EmitsCancelNotification_AndCancelsTask() { var client = new TestableMcpClient("test"); using var cts = new CancellationTokenSource(); var task = client.CallToolAsync("slow", null, cts.Token); await WaitForFrameAsync(client, 0); var id = JsonNode.Parse(client.SentFrames[0])!["id"]!.GetValue(); cts.Cancel(); var act = async () => await task; await act.Should().ThrowAsync(); // The cancel notification is emitted asynchronously — give it a moment. for (var i = 0; i < 50 && client.SentFrames.Count < 2; i++) await Task.Delay(20); client.SentFrames.Should().HaveCountGreaterThanOrEqualTo(2, "the client must emit a notifications/cancelled frame after the request is cancelled"); var cancelFrame = client.SentFrames.Skip(1).Select(f => JsonNode.Parse(f)!).First(); cancelFrame["method"]!.GetValue().Should().Be("notifications/cancelled"); cancelFrame["params"]!["requestId"]!.GetValue().Should().Be(id); } [Fact] public async Task Dispose_FailsPendingRequests() { var client = new TestableMcpClient("test"); var task = client.CallToolAsync("never", null, CancellationToken.None); await WaitForFrameAsync(client, 0); await client.DisposeAsync(); var act = async () => await task; await act.Should().ThrowAsync().WithMessage("*disposed*"); } [Fact] public void IdsAreStrictlyMonotonic_AcrossManyRequests() { var client = new TestableMcpClient("test"); const int count = 50; for (var i = 0; i < count; i++) _ = client.CallToolAsync($"tool_{i}", null, CancellationToken.None); client.SentFrames.Should().HaveCount(count); var ids = client.SentFrames .Select(f => JsonNode.Parse(f)!["id"]!.GetValue()) .ToList(); ids.Should().BeInAscendingOrder(); ids.Distinct().Should().HaveCount(count, "every request must get a unique id"); } // ── helpers ───────────────────────────────────────────────────────────── private static async Task WaitForFrameAsync(TestableMcpClient client, int index, int timeoutMs = 1_000) { var deadline = Environment.TickCount + timeoutMs; while (Environment.TickCount < deadline) { lock (client.SentFrames) { if (client.SentFrames.Count > index) return; } await Task.Delay(5); } throw new TimeoutException($"Frame[{index}] not produced within {timeoutMs}ms."); } private static string BuildResultFrame(long id, string text) => new JsonObject { ["jsonrpc"] = "2.0", ["id"] = id, ["result"] = new JsonObject { ["content"] = new JsonArray(new JsonObject { ["type"] = "text", ["text"] = text }), ["isError"] = false, }, }.ToJsonString(); } Path: redb-route/tests/redb.Route.Tests.Llm.Mcp/Framing/TestableMcpClient.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Llm.Mcp/Framing/TestableMcpClient.cs ---- using Microsoft.Extensions.Logging.Abstractions; using redb.Route.Llm.Mcp.Protocol; namespace redb.Route.Tests.Llm.Mcp.Framing; /// /// Test subclass that exposes the protected hooks of /// and captures every outgoing frame so we can assert on what the client sent. /// internal sealed class TestableMcpClient : McpClientBase { public List SentFrames { get; } = new(); public TaskCompletionSource StartTransportTcs { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); public TaskCompletionSource StopTransportTcs { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); public TestableMcpClient(string serverName) : base(serverName, NullLogger.Instance) { } public void InjectFrame(string frameJson) => OnFrameReceived(frameJson); public void InjectTransportFailure(string reason) => OnTransportFailed(reason); protected override Task StartTransportAsync(CancellationToken cancellationToken) { StartTransportTcs.TrySetResult(); return Task.CompletedTask; } protected override Task StopTransportAsync() { StopTransportTcs.TrySetResult(); return Task.CompletedTask; } protected override Task SendFrameAsync(string frameJson, CancellationToken cancellationToken) { lock (SentFrames) SentFrames.Add(frameJson); return Task.CompletedTask; } } Path: redb-route/tests/redb.Route.Tests.Llm.Mcp/GlobalUsings.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Llm.Mcp/GlobalUsings.cs ---- global using System.Text.Json; global using System.Text.Json.Nodes; global using redb.Route.Abstractions; global using redb.Route.Core; global using redb.Route.Llm; global using redb.Route.Llm.Abstractions.Tools; global using redb.Route.Llm.Engine; global using redb.Route.Llm.Extensions; global using redb.Route.Llm.Mcp; global using redb.Route.Llm.Mcp.Protocol; global using redb.Route.Llm.Mcp.Transport; global using redb.Route.Llm.Providers; global using redb.Route.Tests.Llm.Mcp.TestHelpers; Path: redb-route/tests/redb.Route.Tests.Llm.Mcp/Governance/McpSafetyUnitTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Llm.Mcp/Governance/McpSafetyUnitTests.cs ---- using System.Text.RegularExpressions; namespace redb.Route.Tests.Llm.Mcp.Governance; /// /// Unit-level locks for the MCP safety surface. There is no local fake MCP server in this /// repository (only live Serena tests under SerenaFact), so MCP behaviour is pinned where it can /// be pinned without a server: on the descriptor, the override matcher and the configuration defaults. /// [Trait("Category", "Governance")] public sealed class McpSafetyUnitTests { private static McpSafetyOverride Override(string pattern) => new() { ToolNamePattern = pattern, Safety = new LlmToolSafety { RequiresApproval = true, SideEffect = ToolSideEffect.External } }; /// /// A trap: McpSafetyOverride.ToolNamePattern /// is matched against the raw server-side tool name, while the operator and the model see the /// sanitized {server}__{tool} form. Copying the model-facing name into the pattern therefore /// matches nothing — silently, falling back to DefaultSafety. /// [Fact] public void McpSafetyOverride_ModelFacingPattern_DoesNotMatchRawName() { var modelFacing = McpToolDescriptor.BuildModelFacingName("serena", "find_symbol"); modelFacing.Should().Be("serena__find_symbol", "the model-facing form is server__tool"); var overridden = Override("^" + Regex.Escape(modelFacing) + "$"); overridden.Matches("find_symbol").Should().BeFalse( "matching runs against the raw name, so a pattern built from the model-facing name silently misses"); } /// /// The same trap, made loud: discovery reports every override that matched no discovered tool, so an /// operator sees the miss instead of quietly running on DefaultSafety. /// [Fact] public void McpSafetyOverride_ModelFacingPattern_IsReportedAsUnmatched() { var server = new McpServerOptions { Name = "serena", Transport = McpTransport.Stdio("mcp-server"), SafetyOverrides = [Override("^serena__find_symbol$")] }; var tools = new List { new() { Name = "find_symbol" } }; McpDiscoveryService.FindUnmatchedOverrides(server, tools).Should().ContainSingle( "a pattern that matched nothing must be reported, not left for the operator to discover in production"); } /// A pattern that does match the raw name is, of course, not reported. [Fact] public void McpSafetyOverride_RawNamePattern_IsNotReported() { var server = new McpServerOptions { Name = "serena", Transport = McpTransport.Stdio("mcp-server"), SafetyOverrides = [Override("^find_symbol$")] }; var tools = new List { new() { Name = "find_symbol" } }; McpDiscoveryService.FindUnmatchedOverrides(server, tools).Should().BeEmpty(); } /// /// A typo in a pattern used to surface only during discovery, where the exception turned into /// "the server is silently absent from the tool set". Compiling it at build time makes the typo /// fail where it is written. /// [Fact] public void McpSafetyOverride_InvalidRegex_FailsAtConstruction() { var act = () => Override("^find_symbol("); act.Should().Throw() .WithMessage("*not a valid regex*", "the message must say which pattern is broken, not only that something is wrong"); } /// /// Wave 6 deliberately flips the discovered-tool default: a third-party tool is unknown, so it is /// declared external and approval-required. Approval only becomes a control point with a gate /// other than the shipped — this test pins the declaration, and /// ApprovalDefaultsTests.AddRedbRouteLlm_ResolvesAutoApproveGateByDefault pins what that /// declaration currently buys. /// [Fact] public void McpServerOptions_DefaultSafety_RequiresApproval() { var options = new McpServerOptions { Name = "srv", Transport = McpTransport.Stdio("mcp-server") }; options.DefaultSafety.SideEffect.Should().Be(ToolSideEffect.External); options.DefaultSafety.RequiresApproval.Should().BeTrue( "discovery cannot know what a third-party tool does, so the safe default is the declared one"); } /// /// A caching policy on a discovered tool that is not read-only is refused when the server options are /// built — at configuration time, where the operator can still fix it, instead of during discovery, /// where it would read as "this server is silently missing from the tool set". /// [Fact] public void McpServerOptions_CachingOnNonReadOnlySafety_FailsAtConfiguration() { var builder = new McpServerOptionsBuilder { Name = "srv", Transport = McpTransport.Stdio("mcp-server"), DefaultSafety = new LlmToolSafety { SideEffect = ToolSideEffect.External, Caching = ToolCachingPolicy.Persist } }; var act = () => builder.Build(); act.Should().Throw() .Which.Message.Should().Contain("Only read-only tools may be cached"); } } Path: redb-route/tests/redb.Route.Tests.Llm.Mcp/HttpSseTransportTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Llm.Mcp/HttpSseTransportTests.cs ---- using System.Net; using System.Reflection; using Microsoft.Extensions.Logging.Abstractions; namespace redb.Route.Tests.Llm.Mcp; /// /// The MCP HTTP+SSE transport keeps its event stream alive the way the model clients do: its own client asks for /// HTTP/2, so keep-alive pings run while the stream is open and silent between events, and the hand-built SSE /// request carries the client's version (a hand-built request starts at HTTP/1.1, and then no pings are sent). /// public sealed class HttpSseTransportTests { private static McpTransport Sse() => new() { Kind = McpTransportKind.HttpSse, BaseUrl = "https://mcp.example.test/mcp" }; /// Records the first request and answers 404, so the SSE pump ends at once. private sealed class FirstRequestHandler : HttpMessageHandler { public TaskCompletionSource<(HttpMethod Method, Version Version, HttpVersionPolicy Policy)> First { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); protected override Task SendAsync(HttpRequestMessage request, CancellationToken ct) { First.TrySetResult((request.Method, request.Version, request.VersionPolicy)); return Task.FromResult(new HttpResponseMessage(HttpStatusCode.NotFound)); } } [Fact] public async Task OwnClient_AsksForHttp2() { await using var client = new HttpSseMcpClient("probe", Sse(), NullLogger.Instance); client.Http.DefaultRequestVersion.Should().Be(HttpVersion.Version20, "the keep-alive pings ride on HTTP/2 frames; an event stream can be silent for minutes"); client.Http.DefaultVersionPolicy.Should().Be(HttpVersionPolicy.RequestVersionOrLower, "HTTP/1.1 stays the fallback"); } [Fact] public async Task SseRequest_CarriesTheClientsHttpVersion() { var handler = new FirstRequestHandler(); var http = new HttpClient(handler) { DefaultRequestVersion = HttpVersion.Version20, DefaultVersionPolicy = HttpVersionPolicy.RequestVersionOrLower }; await using var client = new HttpSseMcpClient("probe", Sse(), NullLogger.Instance, http); // The SSE channel opens when the transport starts; InitializeAsync would run the MCP handshake on top of it. var start = typeof(HttpSseMcpClient).GetMethod("StartTransportAsync", BindingFlags.Instance | BindingFlags.NonPublic)!; await (Task)start.Invoke(client, [CancellationToken.None])!; var sent = await handler.First.Task.WaitAsync(TimeSpan.FromSeconds(10)); sent.Method.Should().Be(HttpMethod.Get, "the first request of the transport is the SSE channel"); sent.Version.Should().Be(HttpVersion.Version20, "the hand-built SSE request must carry the client's version"); sent.Policy.Should().Be(HttpVersionPolicy.RequestVersionOrLower); } } Path: redb-route/tests/redb.Route.Tests.Llm.Mcp/McpComponentRegistryTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Llm.Mcp/McpComponentRegistryTests.cs ---- using System.Xml.Linq; using Microsoft.Extensions.DependencyInjection; using redb.Route.Extensions; using redb.Route.Xml; using redb.Route.Xml.Packaging; namespace redb.Route.Tests.Llm.Mcp; /// /// without a constructor argument takes the MCP client registry the context holds: the one /// a Tsak module gives it in InitRoute (ctx.AddService(typeof(IMcpRegistry), registry)), or the host's DI /// singleton of AddRedbRouteMcp(). So a package's markup can name the component and the catalog can describe it. /// public sealed class McpComponentRegistryTests : IDisposable { private readonly string _root = Path.Combine(Path.GetTempPath(), "redb-mcp-registry-" + Guid.NewGuid().ToString("N")); public McpComponentRegistryTests() => Directory.CreateDirectory(_root); public void Dispose() => Directory.Delete(_root, recursive: true); /// An MCP client that answers every tools/call with the tool's name, without a server. private sealed class EchoClient(string serverName) : IMcpClient { public string ServerName { get; } = serverName; public McpClientStatus Status => McpClientStatus.Healthy; public InitializeResult? Initialize => null; public event EventHandler? ToolsChanged { add { } remove { } } public Task InitializeAsync(CancellationToken cancellationToken = default) => Task.CompletedTask; public Task> ListToolsAsync(CancellationToken cancellationToken = default) => Task.FromResult>([]); public Task CallToolAsync(string toolName, JsonNode? arguments, CancellationToken cancellationToken = default) => Task.FromResult(new CallToolResult { Content = new JsonArray(JsonValue.Create(toolName)) }); public ValueTask DisposeAsync() => ValueTask.CompletedTask; } private static McpRegistry Registry() { var registry = new McpRegistry(); registry.Register(new EchoClient("srv")); return registry; } private static async Task Send(RouteContext ctx) { var template = new ProducerTemplate(ctx); template.Start(); var exchange = new Exchange(new Message("{}")); await template.SendAsync("direct://in", exchange); return exchange; } [Fact] public async Task Takes_the_registry_a_module_gave_the_context() { await using var ctx = new RouteContext(); ctx.AddService(typeof(IMcpRegistry), Registry()); ctx.AddComponent(new McpComponent()); ctx.AddRoutes(r => r.From("direct://in").To("mcp://srv/echo")); await ctx.Start(); var exchange = await Send(ctx); exchange.Exception.Should().BeNull(); exchange.In.Headers["Mcp-Tool"].Should().Be("echo"); } [Fact] public async Task Takes_the_registry_of_the_host_services() { var services = new ServiceCollection().AddSingleton(Registry()).BuildServiceProvider(); await using var ctx = new RouteContext(services); ctx.AddComponent(new McpComponent()); var act = () => ctx.GetEndpoint("mcp://srv/echo"); act.Should().NotThrow(); } [Fact] public async Task Without_a_registry_creating_the_endpoint_names_both_ways() { await using var ctx = new RouteContext(); ctx.AddComponent(new McpComponent()); var act = () => ctx.GetEndpoint("mcp://srv/echo"); act.Should().Throw().Which.Message.Should() .Contain("AddRedbRouteMcp").And.Contain("AddMcpServer") .And.Contain("InitRoute").And.Contain("ctx.AddService(typeof(IMcpRegistry), registry)"); } [Fact] public async Task The_registry_given_to_the_constructor_still_serves() { await using var ctx = new RouteContext(); ctx.AddComponent(new McpComponent(Registry())); ctx.AddRoutes(r => r.From("direct://in").To("mcp://srv/echo")); await ctx.Start(); (await Send(ctx)).In.Headers["Mcp-Tool"].Should().Be("echo"); } [Fact] public void AddRouteComponent_still_injects_the_registry_through_the_constructor() { var registry = Registry(); var services = new ServiceCollection(); services.AddSingleton(registry); services.AddRouteComponent(); services.BuildServiceProvider().GetRequiredService().Registry.Should().BeSameAs(registry); } [Fact] public async Task A_package_names_the_component_in_markup_once_module_code_provided_the_registry() { await using var ctx = new RouteContext(); ctx.AddService(typeof(IMcpRegistry), Registry()); // what InitRoute.main does in a Tsak module ctx.AddXmlContextFromContent($$""" """); ctx.AddXmlRoutesFromContent(""" """); await ctx.Start(); (await Send(ctx)).In.Headers["Mcp-Tool"].Should().Be("echo"); } private static readonly IReadOnlyList Catalog = ComponentCatalog.Build([new McpComponent()]); [Fact] public void The_catalog_describes_mcp_as_producer_only_with_its_options() { var mcp = Catalog.Should().ContainSingle().Which; mcp.Scheme.Should().Be("mcp"); mcp.Role.Should().Be(EndpointRole.Producer); mcp.Options.Select(o => o.Name).Should().BeEquivalentTo(["ServerName", "ToolName", "CallTimeoutMs"]); } [Fact] public void The_schema_takes_mcp_as_a_target_and_refuses_it_in_from() { IReadOnlyList<(int Line, int Column, string Message)> Validate(string from, string to) => XmlRouteSchema.Validate(XDocument.Parse($""" {from} {to} """, LoadOptions.SetLineInfo), ElementRegistry.CreateDefault(), Catalog); Validate("""""", """""").Should().ContainSingle().Which.Line.Should().Be(3); } [Fact] public void Check_reports_mcp_in_from_at_its_position() { var dir = RouteProjectScaffold.Create(_root, "Mcp"); File.WriteAllText(Path.Combine(dir, "routes", "main.route.xml"), """ """); var errors = RoutePackage.Check(dir, "p", "1.0.0", catalog: Catalog).Errors.ToList(); errors.Should().ContainSingle(e => e.Message.Contains("mcp")).Which.Should().Match(e => e.File.StartsWith("routes/main.route.xml(3,") && e.Message.StartsWith(": mcp has no consumer side: a route cannot start from it (mcp is producer-only).")); } } Path: redb-route/tests/redb.Route.Tests.Llm.Mcp/McpTraceTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Llm.Mcp/McpTraceTests.cs ---- using System.Diagnostics; using redb.Route.Configuration; using redb.Route.Tests.Telemetry; namespace redb.Route.Tests.Llm.Mcp; /// /// The tools/call span is a transport span of its endpoint: it carries redb.route.endpoint, honours /// EnableTelemetry, and a failed call — an unknown or dead server, a tool error thrown by the client, a timeout — /// marks it red; our own cancellation does not. Stub clients only: no MCP server is started. /// public sealed class McpTraceTests { private readonly string _server = $"trace{Guid.NewGuid():N}"; private string Uri => $"mcp://{_server}/echo"; private RouteTelemetryProbe Spans() => new(a => a.Kind == ActivityKind.Client && RouteTelemetryProbe.Tag(a, RouteTelemetryProbe.EndpointTag)?.Contains(_server, StringComparison.Ordinal) == true); private async Task Start(IMcpClient? client, bool telemetry = true) { var registry = new McpRegistry(); if (client is not null) registry.Register(client); var ctx = new RouteContext(options: new RouteEngineOptions { EnableTelemetry = telemetry }); ctx.AddComponent(new McpComponent(registry)); await ctx.Start(); return ctx; } private IMcpClient Client(Func> call, McpClientStatus status = McpClientStatus.Healthy) { var client = Substitute.For(); client.ServerName.Returns(_server); client.Status.Returns(status); client.CallToolAsync("echo", Arg.Any(), Arg.Any()) .Returns(ci => call(ci.ArgAt(2))); return client; } private static Task Call(RouteContext ctx, string uri, CancellationToken ct = default) => ctx.GetEndpoint(uri).CreateProducer().Process(new Exchange(new Message("{}")), ct); [Fact] public async Task The_call_is_a_span_of_its_endpoint() { using var probe = Spans(); await using (var ctx = await Start(Client(_ => Task.FromResult(new CallToolResult { Content = new JsonArray() })))) await Call(ctx, Uri); var span = probe.Activities.Should().ContainSingle().Subject; span.Status.Should().NotBe(ActivityStatusCode.Error); RouteTelemetryProbe.Tag(span, "rpc.system").Should().Be("mcp"); RouteTelemetryProbe.Tag(span, "rpc.method").Should().Be("echo"); } [Fact] public async Task A_failed_call_marks_the_span_red() { using var probe = Spans(); await using (var ctx = await Start(Client(_ => throw new McpException("tool failed")))) { var call = () => Call(ctx, Uri); await call.Should().ThrowAsync(); } probe.Activities.Should().ContainSingle().Which.Status.Should().Be(ActivityStatusCode.Error); } [Fact] public async Task An_unknown_server_marks_the_span_red() { using var probe = Spans(); await using (var ctx = await Start(client: null)) { var call = () => Call(ctx, Uri); await call.Should().ThrowAsync(); } probe.Activities.Should().ContainSingle().Which.Status.Should().Be(ActivityStatusCode.Error); } [Fact] public async Task A_timeout_marks_the_span_red() { using var probe = Spans(); await using (var ctx = await Start(Client(async ct => { await Task.Delay(Timeout.Infinite, ct); return new CallToolResult(); }))) { var call = () => Call(ctx, $"{Uri}?callTimeoutMs=100"); await call.Should().ThrowAsync(); } probe.Activities.Should().ContainSingle().Which.Status.Should().Be(ActivityStatusCode.Error); } [Fact] public async Task Our_own_cancellation_does_not_mark_the_span() { using var probe = Spans(); using var cts = new CancellationTokenSource(); await using (var ctx = await Start(Client(async ct => { await cts.CancelAsync(); await Task.Delay(Timeout.Infinite, ct); return new CallToolResult(); }))) { var call = () => Call(ctx, Uri, cts.Token); await call.Should().ThrowAsync(); } probe.Activities.Should().ContainSingle().Which.Status.Should().NotBe(ActivityStatusCode.Error); } [Fact] public async Task Tracing_off_opens_no_span() { using var probe = new RouteTelemetryProbe(a => RouteTelemetryProbe.Tag(a, "rpc.service") == _server); await using (var ctx = await Start(Client(_ => Task.FromResult(new CallToolResult { Content = new JsonArray() })), telemetry: false)) await Call(ctx, Uri); probe.Activities.Should().BeEmpty(); } } Path: redb-route/tests/redb.Route.Tests.Llm.Mcp/RestartTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Llm.Mcp/RestartTests.cs ---- using System.Diagnostics; using Microsoft.Extensions.Logging.Abstractions; namespace redb.Route.Tests.Llm.Mcp; /// /// Verifies the observable recovery contract for stdio MCP clients: /// /// Status transitions from to /// after the underlying process is killed. /// Pending / subsequent tools/call requests fail with /// instead of hanging. /// A fresh client built with the same launch configuration brings the /// server back up cleanly — proving the manual-restart path works. /// /// /// Each test spawns its own Serena process so they don't perturb the shared /// . They still join the SerenaSerial collection /// to avoid running multiple Serena LSPs simultaneously. /// /// [Trait("Category", "LiveMcp")] [Collection("SerenaSerial")] public sealed class RestartTests { [SerenaFact] public async Task ProcessKill_TransitionsClientToDead_AndFailsNextCall() { var launch = SerenaConfig.Launch!; var transport = McpTransport.Stdio(launch.Command, launch.Arguments); var client = new StdioMcpClient("serena-restart-1", transport, NullLogger.Instance); try { using var initCts = new CancellationTokenSource(TimeSpan.FromMinutes(2)); await client.InitializeAsync(initCts.Token); client.Status.Should().Be(McpClientStatus.Healthy); var pid = ResolvePid(client); pid.Should().BeGreaterThan(0, "the stdio transport must have spawned a process"); // Kill the process tree out from under the client and give the // OnExited / pumps a moment to react. KillProcessTree(pid); // Next call must fail rather than hang. The exact exception type can // vary (transport-failed McpException vs. broken-pipe IOException) // depending on whether the read pump or the write pump notices first. using var callCts = new CancellationTokenSource(TimeSpan.FromSeconds(10)); var act = async () => await client.ListToolsAsync(callCts.Token); await act.Should().ThrowAsync( "calling a dead stdio client must surface as an error, not hang"); // Give OnProcessExited a moment to mark the client dead. await WaitUntil(() => client.Status is McpClientStatus.Dead, TimeSpan.FromSeconds(5)); client.Status.Should().Be(McpClientStatus.Dead, "OnProcessExited must transition the client to Dead"); } finally { await client.DisposeAsync(); } } [SerenaFact] public async Task FreshClient_AfterKill_DiscoversToolsAgain() { var launch = SerenaConfig.Launch!; var transport = McpTransport.Stdio(launch.Command, launch.Arguments); // Bring up + tear down a first client so we know one is "dead". var firstClient = new StdioMcpClient("serena-restart-2a", transport, NullLogger.Instance); try { using var cts1 = new CancellationTokenSource(TimeSpan.FromMinutes(2)); await firstClient.InitializeAsync(cts1.Token); firstClient.Status.Should().Be(McpClientStatus.Healthy); } finally { await firstClient.DisposeAsync(); } firstClient.Status.Should().Be(McpClientStatus.Dead); // Now build a fresh client and prove the recovery path is clean. var secondClient = new StdioMcpClient("serena-restart-2b", transport, NullLogger.Instance); try { using var cts2 = new CancellationTokenSource(TimeSpan.FromMinutes(2)); await secondClient.InitializeAsync(cts2.Token); secondClient.Status.Should().Be(McpClientStatus.Healthy); var tools = await secondClient.ListToolsAsync(cts2.Token); tools.Should().NotBeEmpty("fresh Serena instance must re-publish its tool catalogue"); tools.Should().Contain(t => t.Name.Contains("get_symbols_overview", StringComparison.OrdinalIgnoreCase)); } finally { await secondClient.DisposeAsync(); } } /// /// Reads the private _process field of /// via reflection. This is the only reliable way to identify *this client's* /// process — naming-based heuristics would risk killing the /// 's long-running instance instead. /// private static int ResolvePid(StdioMcpClient client) { var field = typeof(StdioMcpClient).GetField( "_process", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic); var proc = field?.GetValue(client) as Process; return proc?.Id ?? 0; } private static void KillProcessTree(int pid) { try { using var p = Process.GetProcessById(pid); p.Kill(entireProcessTree: true); p.WaitForExit(5_000); } catch { // Already gone or insufficient privilege — both acceptable for a kill. } } private static async Task WaitUntil(Func condition, TimeSpan timeout) { var deadline = DateTime.UtcNow + timeout; while (DateTime.UtcNow < deadline) { if (condition()) return; await Task.Delay(100); } } } Path: redb-route/tests/redb.Route.Tests.Llm.Mcp/SerenaAgentTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Llm.Mcp/SerenaAgentTests.cs ---- using LlmDsl = redb.Route.Llm.Fluent.Llm; namespace redb.Route.Tests.Llm.Mcp; /// /// End-to-end agent tests against the live Serena MCP server. Each test: /// /// Reuses the shared (one Serena process per collection). /// Builds an that projects Serena's tools/list /// catalogue into as s. /// Sends a question whose answer requires reading the source file via the /// serena__get_symbols_overview tool. /// Asserts the model actually invoked the MCP tool through the /// . /// /// /// Groq llama-3.3-70b-versatile is used because its free-tier tool-use is /// the most reliable mix we have. Claude claude-haiku-4-5 provides a second /// vendor cross-check. /// /// [Trait("Category", "LiveLlmMcp")] [Collection("SerenaSerial")] public sealed class SerenaAgentTests { private readonly SerenaFixture _fixture; public SerenaAgentTests(SerenaFixture fixture) => _fixture = fixture; [SerenaEnvFact("REDB_LLM_GROQ_KEY")] public async Task Groq_AgentInvokesGetSymbolsOverview_OnRedbRouteFile() { var spy = new ToolInvocationSpy(); await using var host = McpAgentHost.Build("serena", _fixture.Client!, _fixture.Tools, spy) .AddFactory("groq", new LlmConnectionFactory { Provider = "groq", ModelId = "llama-3.3-70b-versatile", ApiKey = Environment.GetEnvironmentVariable("REDB_LLM_GROQ_KEY"), Temperature = 0.0, MaxTokens = 512, }); await host.StartAsync(r => { r.From("direct:agent") .Process(e => e.In.Headers[LlmHeaders.SystemPrompt] = "You are a code-archaeology assistant. When the user asks about a C# source file, " + "you MUST call the serena__get_symbols_overview tool with that file's relative path " + "to inspect its top-level symbols. Reply with a single short sentence summarising " + "what the file declares.") .To(LlmDsl.Factory("groq") .Tools("serena__get_symbols_overview") .MaxIterations(4) .AsUri()); }); var question = "What top-level types are declared in 'redb.Route/src/redb.Route.Llm.Mcp/Protocol/McpProtocol.cs'? " + "Use the serena__get_symbols_overview tool with relative_path set to that path, then summarise."; var ex = await host.SendAsync("direct:agent", question); spy.ForTool("serena__get_symbols_overview") .Should().NotBeEmpty("the model must call serena's get_symbols_overview tool"); // The spy already proves the agent dispatched through mcp://. The exact // response payload depends on which path Groq passed to Serena, so we // only check the tool was invoked and the run produced a final reply. ex.In.Body.Should().NotBeNull(); } [SerenaEnvFact("REDB_LLM_ANT_API03_KEY")] public async Task Claude_AgentInvokesGetSymbolsOverview_OnRedbRouteFile() { var spy = new ToolInvocationSpy(); await using var host = McpAgentHost.Build("serena", _fixture.Client!, _fixture.Tools, spy) .AddFactory("claude", new LlmConnectionFactory { Provider = "anthropic", ModelId = "claude-haiku-4-5", ApiKey = Environment.GetEnvironmentVariable("REDB_LLM_ANT_API03_KEY"), Temperature = 0.0, MaxTokens = 512, }); await host.StartAsync(r => { r.From("direct:agent") .Process(e => e.In.Headers[LlmHeaders.SystemPrompt] = "You inspect C# code via Serena's MCP tools. To answer questions about a source file, " + "call serena__get_symbols_overview with the file's relative_path, then summarise " + "the result in one short sentence.") .To(LlmDsl.Factory("claude") .Tools("serena__get_symbols_overview") .MaxIterations(4) .AsUri()); }); var question = "Look at 'redb.Route/src/redb.Route.Llm.Mcp/McpProducer.cs' using the " + "serena__get_symbols_overview tool and tell me what top-level type it declares."; var ex = await host.SendAsync("direct:agent", question); spy.ForTool("serena__get_symbols_overview") .Should().NotBeEmpty("Claude must call serena's get_symbols_overview tool"); // The spy already proves Claude reached the MCP producer. The exact // response payload is LLM-dependent (the model can call the tool with // different relative_path values across runs), so assert only that the // round-trip completed and the run produced a final assistant reply. ex.In.Body.Should().NotBeNull(); } } Path: redb-route/tests/redb.Route.Tests.Llm.Mcp/SerenaConfig.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Llm.Mcp/SerenaConfig.cs ---- using System.IO; using System.Text.Json.Nodes; using Xunit.Sdk; namespace redb.Route.Tests.Llm.Mcp; /// /// Resolves Serena's launch configuration from .mcp.json at the repo root. /// Tests use to gate on its availability. /// internal static class SerenaConfig { private static readonly Lazy _launch = new(Resolve); public static SerenaLaunch? Launch => _launch.Value; public static bool IsAvailable => Launch is not null; public static string SkipReason => "Serena MCP launch not found — expected '.mcp.json' with a 'Serena' entry at the repo root, or env var SERENA_MCP_LAUNCH."; private static SerenaLaunch? Resolve() { // Env override: SERENA_MCP_LAUNCH=command|arg1|arg2|... var envValue = Environment.GetEnvironmentVariable("SERENA_MCP_LAUNCH"); if (!string.IsNullOrWhiteSpace(envValue)) { var parts = envValue.Split('|', StringSplitOptions.RemoveEmptyEntries); if (parts.Length > 0) return new SerenaLaunch(parts[0], parts.Skip(1).ToArray()); } // Climb up from BaseDirectory until we find .mcp.json. var dir = AppContext.BaseDirectory; while (!string.IsNullOrEmpty(dir)) { var candidate = Path.Combine(dir, ".mcp.json"); if (File.Exists(candidate)) return ParseFile(candidate); dir = Directory.GetParent(dir)?.FullName; } return null; } private static SerenaLaunch? ParseFile(string path) { try { var json = File.ReadAllText(path); var root = JsonNode.Parse(json); var servers = root?["servers"]; if (servers is null) return null; // Match case-insensitively — `.mcp.json` typically uses "Serena". JsonNode? entry = null; foreach (var kv in servers.AsObject()) { if (string.Equals(kv.Key, "serena", StringComparison.OrdinalIgnoreCase)) { entry = kv.Value; break; } } if (entry is null) return null; var command = entry["command"]?.GetValue(); if (string.IsNullOrWhiteSpace(command)) return null; var args = entry["args"]?.AsArray() .Select(n => n?.GetValue() ?? "") .Where(s => s.Length > 0) .ToArray() ?? []; return new SerenaLaunch(command, args); } catch { return null; } } } /// Materialised Serena launch description. internal sealed record SerenaLaunch(string Command, IReadOnlyList Arguments); /// /// xUnit fact gated on Serena's availability via . /// [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] [XunitTestCaseDiscoverer("Xunit.Sdk.FactDiscoverer", "xunit.execution.{Platform}")] public sealed class SerenaFactAttribute : FactAttribute { /// Creates a Serena-gated fact. public SerenaFactAttribute() { if (!SerenaConfig.IsAvailable) Skip = SerenaConfig.SkipReason; } } /// /// xUnit fact gated on BOTH Serena availability and the named environment variable(s). /// Skips with a clear reason when either side is missing. /// [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] [XunitTestCaseDiscoverer("Xunit.Sdk.FactDiscoverer", "xunit.execution.{Platform}")] public sealed class SerenaEnvFactAttribute : FactAttribute { /// Creates a Serena+env-gated fact. /// Required environment variable. /// Additional variables that must also be present. public SerenaEnvFactAttribute(string envVar, params string[] extraEnvVars) { if (!SerenaConfig.IsAvailable) { Skip = SerenaConfig.SkipReason; return; } var missing = new List(); if (string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable(envVar))) missing.Add(envVar); foreach (var v in extraEnvVars) if (string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable(v))) missing.Add(v); if (missing.Count > 0) Skip = $"Live LLM+MCP test skipped — set env vars: {string.Join(", ", missing)}."; } } Path: redb-route/tests/redb.Route.Tests.Llm.Mcp/SerenaFixture.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Llm.Mcp/SerenaFixture.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging.Abstractions; using redb.Route.Llm.Mcp.Protocol; namespace redb.Route.Tests.Llm.Mcp; /// /// Spawns a single Serena MCP server once per xUnit collection and exposes the /// connected client + tool catalogue. Tests that don't need their own private /// process reuse this fixture to keep startup cost (uvx download / venv) at one /// hit per run. /// public sealed class SerenaFixture : IAsyncLifetime { /// Live MCP client connected to Serena. Null when fixture skipped initialization. public IMcpClient? Client { get; private set; } /// Tool catalogue returned by the initial tools/list. public IReadOnlyList Tools { get; private set; } = []; /// Resolved launch command (for diagnostic display + RestartTests). internal SerenaLaunch? Launch { get; private set; } /// public async Task InitializeAsync() { var launch = SerenaConfig.Launch; if (launch is null) return; Launch = launch; var transport = McpTransport.Stdio(launch.Command, launch.Arguments); var client = new redb.Route.Llm.Mcp.Transport.StdioMcpClient("serena", transport, NullLogger.Instance); using var cts = new CancellationTokenSource(TimeSpan.FromMinutes(2)); try { await client.InitializeAsync(cts.Token).ConfigureAwait(false); Tools = await client.ListToolsAsync(cts.Token).ConfigureAwait(false); Client = client; } catch { await client.DisposeAsync().ConfigureAwait(false); throw; } } /// public async Task DisposeAsync() { if (Client is not null) await Client.DisposeAsync().ConfigureAwait(false); } } /// Collection definition that shares a single across tests. [CollectionDefinition("SerenaSerial", DisableParallelization = true)] public sealed class SerenaCollection : ICollectionFixture { } Path: redb-route/tests/redb.Route.Tests.Llm.Mcp/SerenaProducerTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Llm.Mcp/SerenaProducerTests.cs ---- using System.Text.Json; using System.Text.Json.Nodes; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging.Abstractions; using redb.Route.Llm.Mcp.Protocol; namespace redb.Route.Tests.Llm.Mcp; /// /// End-to-end tests against a real Serena MCP server through the /// . No LLM involvement — we drive /// mcp://serena/<tool> directly via the producer (and once via /// to exercise the new CT-aware overload). /// [Trait("Category", "LiveMcp")] [Collection("SerenaSerial")] public sealed class SerenaProducerTests { private readonly SerenaFixture _fixture; public SerenaProducerTests(SerenaFixture fixture) => _fixture = fixture; [SerenaFact] public async Task ListsTools_AndExposesGetSymbolsOverview() { _fixture.Client.Should().NotBeNull("fixture must have initialized Serena"); _fixture.Tools.Should().NotBeEmpty("Serena reports a non-empty tool catalogue"); var names = _fixture.Tools.Select(t => t.Name).ToList(); names.Should().Contain(n => n.Contains("get_symbols_overview", StringComparison.OrdinalIgnoreCase)); names.Should().Contain(n => n.Contains("find_symbol", StringComparison.OrdinalIgnoreCase)); } [SerenaFact] public async Task DirectProducer_CallsTool_ReturnsContentAndHeaders() { var registry = new McpRegistry(); registry.Register(_fixture.Client!); var component = new McpComponent(registry); var endpoint = (McpEndpoint)component.CreateEndpoint( EndpointUriParser.Parse("mcp://serena/get_symbols_overview")); var producer = (McpProducer)endpoint.CreateProducer(); var args = new JsonObject { ["relative_path"] = "redb.Route/src/redb.Route.Llm.Mcp/Protocol/McpProtocol.cs", }; var msg = new Message(args.ToJsonString()); var exchange = new Exchange(msg); await producer.Process(exchange, CancellationToken.None); var body = (string)exchange.In.Body!; body.Should().NotBeNullOrWhiteSpace(); // Every Serena response is a JSON array of content blocks. var arr = JsonNode.Parse(body) as JsonArray; arr.Should().NotBeNull("MCP tools/call returns a content[] array"); arr!.Count.Should().BeGreaterThan(0); exchange.In.Headers.TryGetValue("Mcp-Server", out var server); server.Should().Be("serena"); exchange.In.Headers.TryGetValue("Mcp-Tool", out var tool); tool.Should().Be("get_symbols_overview"); } [SerenaFact] public async Task ViaProducerTemplate_CallsTool_AndReturnsString() { var registry = new McpRegistry(); registry.Register(_fixture.Client!); var services = new ServiceCollection(); var sp = services.BuildServiceProvider(); var ctx = new RouteContext(sp, contextId: "mcp-producer-test"); ctx.AddComponent(new McpComponent(registry)); await using var ctxScope = ctx; await ctx.Start(); using var pt = new ProducerTemplate(ctx); pt.Start(); var args = new JsonObject { ["relative_path"] = "redb.Route/src/redb.Route.Llm.Mcp/McpProducer.cs", }; var result = await pt.RequestBody( "mcp://serena/get_symbols_overview", args.ToJsonString(), CancellationToken.None); result.Should().NotBeNull(); var json = result!.ToString(); json.Should().NotBeNullOrWhiteSpace(); JsonNode.Parse(json!).Should().NotBeNull("response must be valid JSON"); } [SerenaFact] public async Task DirectProducer_RespectsCancellationToken() { var registry = new McpRegistry(); registry.Register(_fixture.Client!); var component = new McpComponent(registry); var endpoint = (McpEndpoint)component.CreateEndpoint( EndpointUriParser.Parse("mcp://serena/find_symbol")); var producer = (McpProducer)endpoint.CreateProducer(); // A find_symbol with broad query → should run long enough that we can cancel it. var args = new JsonObject { ["name_path"] = "Mcp", ["substring_matching"] = true, ["relative_path"] = "", }; var exchange = new Exchange(new Message(args.ToJsonString())); using var cts = new CancellationTokenSource(); var task = producer.Process(exchange, cts.Token); // Cancel immediately — the producer/client must propagate. cts.Cancel(); var act = async () => await task; var thrown = await act.Should().ThrowAsync(); thrown.Which.CancellationToken.IsCancellationRequested.Should().BeTrue(); } [SerenaFact] public async Task DirectProducer_DeadClient_ThrowsMcpException() { // Build a registry whose client we mark "Dead" by disposing it. var deadClient = new redb.Route.Llm.Mcp.Transport.StdioMcpClient( "deadhorse", McpTransport.Stdio("uvx", new[] { "--version" }), NullLogger.Instance); await deadClient.DisposeAsync(); var registry = new McpRegistry(); registry.Register(deadClient); var component = new McpComponent(registry); var endpoint = (McpEndpoint)component.CreateEndpoint( EndpointUriParser.Parse("mcp://deadhorse/anything")); var producer = (McpProducer)endpoint.CreateProducer(); var exchange = new Exchange(new Message("{}")); var act = async () => await producer.Process(exchange); await act.Should().ThrowAsync().WithMessage("*deadhorse*dead*"); } } Path: redb-route/tests/redb.Route.Tests.Llm.Mcp/TestHelpers/EnvFactAttribute.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Llm.Mcp/TestHelpers/EnvFactAttribute.cs ---- using Xunit.Sdk; namespace redb.Route.Tests.Llm.Mcp.TestHelpers; /// /// xUnit fact attribute that skips the test when the named environment variable is /// missing or empty. Same shape as redb.Route.Tests.Llm.TestHelpers.EnvFactAttribute — /// duplicated here to keep the MCP test project self-contained. /// [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] [XunitTestCaseDiscoverer("Xunit.Sdk.FactDiscoverer", "xunit.execution.{Platform}")] public sealed class EnvFactAttribute : FactAttribute { /// Creates an env-gated fact. /// Required environment variable. If unset/empty the test is skipped. /// Additional variables that must also be present. public EnvFactAttribute(string envVar, params string[] extraEnvVars) { var missing = new List(); if (string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable(envVar))) missing.Add(envVar); foreach (var v in extraEnvVars) if (string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable(v))) missing.Add(v); if (missing.Count > 0) Skip = $"Live LLM test skipped — set env vars: {string.Join(", ", missing)}."; } } Path: redb-route/tests/redb.Route.Tests.Llm.Mcp/TestHelpers/EnvLoader.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Llm.Mcp/TestHelpers/EnvLoader.cs ---- using System.IO; using System.Runtime.CompilerServices; namespace redb.Route.Tests.Llm.Mcp.TestHelpers; /// /// Loads .env.local from redb.Tsak/publish/keys/.env.local into the /// process environment before any test runs. Mirrors the loader used by /// redb.Route.Tests.Llm — duplicated here because /// is per-assembly. Existing environment variables are never overwritten. /// internal static class EnvLoader { [ModuleInitializer] internal static void Load() { var dir = AppContext.BaseDirectory; while (!string.IsNullOrEmpty(dir)) { var candidate = Path.Combine(dir, "redb.Tsak", "publish", "keys", ".env.local"); if (File.Exists(candidate)) { Apply(candidate); return; } dir = Directory.GetParent(dir)?.FullName; } } private static void Apply(string path) { foreach (var rawLine in File.ReadAllLines(path)) { var line = rawLine.Trim(); if (line.Length == 0 || line.StartsWith('#')) continue; var eq = line.IndexOf('='); if (eq <= 0) continue; var key = line[..eq].Trim(); var value = line[(eq + 1)..].Trim().Trim('"'); if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable(key))) continue; Environment.SetEnvironmentVariable(key, value); } } } Path: redb-route/tests/redb.Route.Tests.Llm.Mcp/TestHelpers/McpAgentHost.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Llm.Mcp/TestHelpers/McpAgentHost.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Route.Llm.Engine.Governance; using redb.Route.Llm.Engine.Observability; using redb.Route.Llm.Mcp.Protocol; namespace redb.Route.Tests.Llm.Mcp.TestHelpers; /// /// Minimal LLM-host wiring for MCP integration tests. Mirrors the /// LiveLlmHost pattern from redb.Route.Tests.Llm but adds the /// + so the agent can /// dispatch mcp:// URIs. /// /// Tests inject pre-discovered instances (typically /// from ) and supply the matching /// list — descriptors are projected into /// the same way would. /// /// public sealed class McpAgentHost : IAsyncDisposable { /// The shared route context. public RouteContext Context { get; } /// The producer template — used to invoke direct: entrypoints. public IProducerTemplate ProducerTemplate { get; } /// The agent engine wired with the producer template + observer. public IAgentEngine Engine { get; } /// The tool registry into which MCP descriptors were projected. public IToolDescriptorRegistry ToolRegistry { get; } /// The MCP client registry the producer dispatches against. public IMcpRegistry McpRegistry { get; } private McpAgentHost( RouteContext ctx, IProducerTemplate pt, IAgentEngine engine, IToolDescriptorRegistry toolRegistry, IMcpRegistry mcpRegistry) { Context = ctx; ProducerTemplate = pt; Engine = engine; ToolRegistry = toolRegistry; McpRegistry = mcpRegistry; } /// Builds a host with the LLM + MCP components wired and the supplied client(s) registered. /// Logical MCP server name (matches the mcp://<serverName>/... URI). /// Pre-initialized MCP client (e.g. from ). /// Tool catalogue to project as instances. /// Optional agent observer — defaults to . public static McpAgentHost Build( string serverName, IMcpClient client, IReadOnlyList tools, IAgentObserver? observer = null) { RouteContext ctx = null!; var services = new ServiceCollection(); services.AddSingleton(_ => ctx); var sp = services.BuildServiceProvider(); ctx = new RouteContext(sp, contextId: $"mcp-test-{serverName}"); ctx.AddComponent(new LlmComponent()); var mcpRegistry = new McpRegistry(); mcpRegistry.Register(client); ctx.AddComponent(new McpComponent(mcpRegistry)); var toolRegistry = new ToolDescriptorRegistry(); foreach (var tool in tools) { if (string.IsNullOrWhiteSpace(tool.Name)) continue; var modelName = McpToolDescriptor.BuildModelFacingName(serverName, tool.Name); var capability = new LlmToolCapability { Name = modelName, Description = tool.Description ?? $"MCP tool '{tool.Name}' from server '{serverName}'.", InputSchema = McpToolDescriptor.BuildInputSchema(tool), Safety = new LlmToolSafety(), }; toolRegistry.Register(new McpToolDescriptor(serverName, tool.Name, capability)); } ctx.AddService(typeof(IToolDescriptorRegistry), toolRegistry); var pt = new ProducerTemplate(ctx); ctx.AddService(typeof(IProducerTemplate), pt); var engine = new AgentEngine( logger: null, producerTemplate: pt, observer: observer ?? new NoopAgentObserver(), budget: new NoopBudgetEnforcer(), approval: new AutoApproveGate(), redaction: new NoopRedactionFilter(), shadow: new NoopShadowRunner(), conversation: null, idempotency: null, approvalStore: null); ctx.AddService(typeof(IAgentEngine), engine); return new McpAgentHost(ctx, pt, engine, toolRegistry, mcpRegistry); } /// Registers a connection factory for use in routes. public McpAgentHost AddFactory(string name, LlmConnectionFactory factory) { factory.Name = name; Context.AddToRegistry(name, factory); return this; } /// Declares routes inline and starts the context + producer template. public async Task StartAsync(Action configure) { Context.AddRoutes(configure); await Context.Start().ConfigureAwait(false); ((ProducerTemplate)ProducerTemplate).Start(); return this; } /// Sends one message into and returns the resulting exchange. public async Task SendAsync(string endpointUri, string body, CancellationToken ct = default) { var endpoint = Context.GetEndpoint(endpointUri); var producer = endpoint.CreateProducer(); await producer.Start(ct).ConfigureAwait(false); var msg = new Message(body); var ex = Exchange.Create(msg, endpoint.ScopeFactory); await producer.Process(ex, ct).ConfigureAwait(false); return ex; } /// public async ValueTask DisposeAsync() { await Context.DisposeAsync().ConfigureAwait(false); if (ProducerTemplate is IDisposable d) d.Dispose(); } } Path: redb-route/tests/redb.Route.Tests.Llm.Mcp/TestHelpers/ToolInvocationSpy.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Llm.Mcp/TestHelpers/ToolInvocationSpy.cs ---- using System.Collections.Concurrent; using redb.Route.Llm.Engine.Observability; namespace redb.Route.Tests.Llm.Mcp.TestHelpers; /// /// Captures every call so a live test /// can assert which MCP tools the model actually invoked. /// public sealed class ToolInvocationSpy : IAgentObserver { private readonly ConcurrentBag _invocations = new(); /// Snapshot of every captured invocation. public IReadOnlyCollection Invocations => _invocations.ToArray(); /// Convenience filter — returns invocations whose tool name matches. public IReadOnlyCollection ForTool(string name) => _invocations.Where(i => i.Tool.Name == name).ToArray(); /// public Task OnRunStartedAsync(AgentRunContext context, CancellationToken ct = default) => Task.CompletedTask; /// public Task OnIterationCompletedAsync(AgentIterationContext context, CancellationToken ct = default) => Task.CompletedTask; /// public Task OnToolInvokedAsync(AgentToolInvocationContext context, CancellationToken ct = default) { _invocations.Add(context); return Task.CompletedTask; } /// public Task OnRunCompletedAsync(AgentRunCompletedContext context, CancellationToken ct = default) => Task.CompletedTask; } Path: redb-route/tests/redb.Route.Tests.Llm.Mcp/redb.Route.Tests.Llm.Mcp.csproj Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Llm.Mcp/redb.Route.Tests.Llm.Mcp.csproj ---- PreserveNewest Path: redb-route/tests/redb.Route.Tests.Llm.Mcp/xunit.runner.json Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Llm.Mcp/xunit.runner.json ---- { "$schema": "https://xunit.net/schema/current/xunit.runner.schema.json", "parallelizeTestCollections": false }