Bundle: redb-route / redb.Route.Llm.Mcp (redb.Route.Llm.Mcp.txt), 18 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/redb.Route.Llm.Mcp/Extensions/McpServiceCollectionExtensions.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/redb.Route.Llm.Mcp/Extensions/McpServiceCollectionExtensions.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using redb.Route.Extensions; using redb.Route.Llm.Abstractions.Tools; using redb.Route.Llm.Mcp.Transport; namespace redb.Route.Llm.Mcp; /// /// DI registration helpers for redb.Route.Llm.Mcp. /// public static class McpServiceCollectionExtensions { /// /// Registers the MCP component (mcp:// scheme), the client registry, /// and the discovery hosted service. Call for each /// MCP server you want spawned at host startup. /// /// /// /// services.AddRedbRoute(...); /// services.AddRedbRouteLlm(...); /// services.AddRedbRouteMcp(); /// services.AddMcpServer("serena", McpTransport.Stdio("uvx", /// ["--from", "git+https://github.com/oraios/serena", "serena", "start-mcp-server", /// "--context", "ide", "--project", "C:/path/to/project"])); /// /// public static IServiceCollection AddRedbRouteMcp(this IServiceCollection services) { ArgumentNullException.ThrowIfNull(services); services.TryAddSingleton(); // IRouteContextConfigurator is applied by RouteHostedService at startup -- // the correct registration hook (a lazy marker singleton never fires). services.AddRouteComponent(); // Tool descriptor registry is owned by redb.Route.Llm; don't add a duplicate here. // If the consumer hasn't called AddRedbRouteLlm() the discovery service will // fail-fast at construction time which is the right diagnostic. services.AddHostedService(); return services; } /// /// Registers a single MCP server entry. The discovery hosted service spawns /// the server at host startup, runs initialize + tools/list, and /// projects the discovered tools into . /// /// DI container. /// Logical server name — must be unique and matches the registry key. /// Transport configuration (use or ). /// Optional callback to set DiscoveryTimeout, RestartPolicy, or SafetyOverrides. public static IServiceCollection AddMcpServer( this IServiceCollection services, string name, McpTransport transport, Action? configure = null) { ArgumentNullException.ThrowIfNull(services); ArgumentException.ThrowIfNullOrWhiteSpace(name); ArgumentNullException.ThrowIfNull(transport); var builder = new McpServerOptionsBuilder { Name = name, Transport = transport }; configure?.Invoke(builder); var options = builder.Build(); services.AddSingleton(options); return services; } } /// Mutable builder for . public sealed class McpServerOptionsBuilder { /// Logical server name. public required string Name { get; set; } /// Transport configuration. public required McpTransport Transport { get; set; } /// Discovery timeout (default 30s). public TimeSpan DiscoveryTimeout { get; set; } = TimeSpan.FromSeconds(30); /// Restart policy (default 3 attempts at 1/3/10s). public McpRestartPolicy RestartPolicy { get; set; } = McpRestartPolicy.Default; /// Per-tool safety overrides. public List SafetyOverrides { get; set; } = []; /// /// Default safety attached when no override matches: external side effects and an approval /// requirement, because discovery cannot know what a third-party tool does. /// /// With the shipped this flag produces an audit row /// (ApprovalId = "auto"), not a blocked call — replace the gate to make approval a control /// point. /// /// public LlmToolSafety DefaultSafety { get; set; } = new() { SideEffect = ToolSideEffect.External, Cost = ToolCostClass.Cheap, RequiresApproval = true, }; internal McpServerOptions Build() { // A caching policy on a tool that is not read-only is refused here, at configuration time. The // tool registry refuses it as well, but that happens during discovery — where the failure reads // as "the server is silently missing from the tool set" instead of "this override is wrong". ValidateSafety("DefaultSafety", DefaultSafety); foreach (var ovr in SafetyOverrides) ValidateSafety($"safety override '{ovr.ToolNamePattern}'", ovr.Safety); return new McpServerOptions { Name = Name, Transport = Transport, DiscoveryTimeout = DiscoveryTimeout, RestartPolicy = RestartPolicy, SafetyOverrides = SafetyOverrides, DefaultSafety = DefaultSafety, }; } private static void ValidateSafety(string what, LlmToolSafety safety) { if (safety.Caching != ToolCachingPolicy.None && safety.SideEffect != ToolSideEffect.ReadOnly) throw new InvalidOperationException( $"MCP {what} declares Caching={safety.Caching} with SideEffect={safety.SideEffect}. " + "Only read-only tools may be cached — a cache hit would suppress the side effect."); } } Path: redb-route/redb.Route.Llm.Mcp/IMcpRegistry.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/redb.Route.Llm.Mcp/IMcpRegistry.cs ---- using System.Collections.Concurrent; namespace redb.Route.Llm.Mcp; /// /// Registry of singletons keyed by server name. /// Populated by on host startup; queried by /// at tools/call time. /// public interface IMcpRegistry { /// Adds a client to the registry. Replaces any existing entry with the same name. void Register(IMcpClient client); /// Returns the client for the given server name, or null when none is registered. IMcpClient? GetClient(string serverName); /// Snapshot of all clients currently in the registry. IReadOnlyCollection All(); /// Removes a client from the registry by name. Returns the removed client, or null. IMcpClient? Remove(string serverName); } /// Default in-memory thread-safe . public sealed class McpRegistry : IMcpRegistry { private readonly ConcurrentDictionary _clients = new(StringComparer.OrdinalIgnoreCase); /// public void Register(IMcpClient client) { ArgumentNullException.ThrowIfNull(client); _clients[client.ServerName] = client; } /// public IMcpClient? GetClient(string serverName) { ArgumentException.ThrowIfNullOrWhiteSpace(serverName); return _clients.TryGetValue(serverName, out var client) ? client : null; } /// public IReadOnlyCollection All() => [.. _clients.Values]; /// public IMcpClient? Remove(string serverName) { ArgumentException.ThrowIfNullOrWhiteSpace(serverName); return _clients.TryRemove(serverName, out var client) ? client : null; } } Path: redb-route/redb.Route.Llm.Mcp/McpComponent.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/redb.Route.Llm.Mcp/McpComponent.cs ---- using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Llm.Mcp; /// /// MCP component. Scheme: mcp. Endpoint URI: mcp://serverName/toolName. /// Producer-only — invokes tools/call on the named MCP server. /// [EndpointRole(EndpointRole.Producer, Hint = "MCP servers are invoked through tools/call from the agent loop.")] public sealed class McpComponent : ComponentBase { private IMcpRegistry? _registry; /// /// Creates the component over the MCP client registry its context holds, looked up when the first endpoint is /// created: the one module code gave the context (ctx.AddService(typeof(IMcpRegistry), registry), as a Tsak /// module does in InitRoute), else the host's AddRedbRouteMcp() singleton. This is the constructor a /// package's <component type="…McpComponent"/> and the catalog use. /// public McpComponent() { } /// Creates the component over the given MCP client registry. /// Registry of MCP clients keyed by server name. public McpComponent(IMcpRegistry registry) { ArgumentNullException.ThrowIfNull(registry); _registry = registry; } /// public override string Scheme => "mcp"; /// Resolved registry — exposed to . internal IMcpRegistry Registry => _registry ??= ResolveRegistry(); /// public override IEndpoint CreateEndpoint(EndpointUri uri) { ArgumentNullException.ThrowIfNull(uri); _ = Registry; // a context without a registry fails here, when the route is built, not on the first call var (server, tool) = SplitPath(uri.Path); var options = new McpEndpointOptions { ServerName = server, ToolName = tool }; options.BindFromUri(uri.RawParameters); // Path values win over query params for the canonical fields. options.ServerName = server; options.ToolName = tool; options.Validate(); return new McpEndpoint(uri, this, options); } /// The registry the context holds: the one module code added, else the host's DI singleton. private IMcpRegistry ResolveRegistry() => Context?.GetService() ?? Context?.GetServiceProvider()?.GetService(typeof(IMcpRegistry)) as IMcpRegistry ?? throw new InvalidOperationException( "mcp:// needs the registry of the MCP servers it calls (IMcpRegistry). In a hosted app call " + "services.AddRedbRouteMcp() and services.AddMcpServer(name, transport). In a Tsak module build an " + "McpRegistry in InitRoute from the module's configuration, initialize and register its clients, and " + "give it to the context with ctx.AddService(typeof(IMcpRegistry), registry)."); private static (string Server, string Tool) SplitPath(string path) { if (string.IsNullOrEmpty(path)) throw new ArgumentException("mcp:// URI requires a path of the form 'serverName/toolName'.", nameof(path)); var slash = path.IndexOf('/'); if (slash <= 0 || slash == path.Length - 1) throw new ArgumentException( $"Invalid mcp:// URI path '{path}'. Expected 'serverName/toolName'.", nameof(path)); return (path[..slash], path[(slash + 1)..]); } } Path: redb-route/redb.Route.Llm.Mcp/McpDiscoveryService.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/redb.Route.Llm.Mcp/McpDiscoveryService.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using redb.Route.Llm.Abstractions.Tools; using redb.Route.Llm.Mcp.Protocol; using redb.Route.Llm.Mcp.Transport; namespace redb.Route.Llm.Mcp; /// /// Hosted service that brings up registered MCP servers, runs the /// initialize + tools/list handshake, and projects the discovered /// tools into . Listens for /// notifications/tools/list_changed and rebuilds descriptors when tools /// mutate. For stdio transports, supervises the child process and restarts it /// per . /// public sealed class McpDiscoveryService : IHostedService, IAsyncDisposable { private readonly IReadOnlyList _servers; private readonly IMcpRegistry _registry; private readonly IToolDescriptorRegistry _toolRegistry; private readonly IServiceProvider _serviceProvider; private readonly ILoggerFactory _loggerFactory; private readonly ILogger _logger; private readonly Dictionary> _registeredToolNames = new(StringComparer.OrdinalIgnoreCase); private readonly Dictionary _restartAttempts = new(StringComparer.OrdinalIgnoreCase); private readonly object _gate = new(); /// DI-friendly ctor. /// All registered via . /// MCP client registry. /// LLM tool descriptor registry. /// DI container — used to resolve a shared for HTTP transports if registered. /// Factory for per-server loggers. /// Logger for the discovery service itself. public McpDiscoveryService( IEnumerable servers, IMcpRegistry registry, IToolDescriptorRegistry toolRegistry, IServiceProvider serviceProvider, ILoggerFactory loggerFactory, ILogger logger) { _servers = [.. servers]; _registry = registry; _toolRegistry = toolRegistry; _serviceProvider = serviceProvider; _loggerFactory = loggerFactory; _logger = logger; } /// public async Task StartAsync(CancellationToken cancellationToken) { if (_servers.Count == 0) { _logger.LogInformation("MCP discovery: no servers configured."); return; } _logger.LogInformation("MCP discovery: bringing up {Count} server(s).", _servers.Count); foreach (var server in _servers) { try { await BringUpAsync(server, cancellationToken).ConfigureAwait(false); } catch (Exception ex) { _logger.LogError(ex, "MCP discovery for '{Server}' failed. Other servers continue. Restart will be attempted on next failure.", server.Name); } } } /// public async Task StopAsync(CancellationToken cancellationToken) { _logger.LogInformation("MCP discovery: shutting down {Count} client(s).", _registry.All().Count); foreach (var client in _registry.All()) { try { await client.DisposeAsync().ConfigureAwait(false); } catch (Exception ex) { _logger.LogDebug(ex, "MCP {Server} dispose threw.", client.ServerName); } } } /// public async ValueTask DisposeAsync() => await StopAsync(CancellationToken.None).ConfigureAwait(false); // ── internals ─────────────────────────────────────────────────────────── private async Task BringUpAsync(McpServerOptions server, CancellationToken cancellationToken) { var client = CreateClient(server); client.ToolsChanged += (_, _) => OnToolsChanged(server, client); using var timeoutCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); timeoutCts.CancelAfter(server.DiscoveryTimeout); try { await client.InitializeAsync(timeoutCts.Token).ConfigureAwait(false); var tools = await client.ListToolsAsync(timeoutCts.Token).ConfigureAwait(false); _registry.Register(client); RegisterDescriptors(server, tools); _logger.LogInformation( "MCP server '{Server}' is healthy with {Count} tool(s).", server.Name, tools.Count); } catch { await client.DisposeAsync().ConfigureAwait(false); throw; } } private IMcpClient CreateClient(McpServerOptions server) { var logger = _loggerFactory.CreateLogger($"redb.Route.Llm.Mcp.{server.Name}"); return server.Transport.Kind switch { McpTransportKind.Stdio => new StdioMcpClient(server.Name, server.Transport, logger), McpTransportKind.HttpSse => new HttpSseMcpClient( server.Name, server.Transport, logger, _serviceProvider.GetService()), _ => throw new InvalidOperationException($"Unknown MCP transport kind: {server.Transport.Kind}"), }; } private void RegisterDescriptors(McpServerOptions server, IReadOnlyList tools) { var seen = new HashSet(StringComparer.OrdinalIgnoreCase); var registeredNames = new List(); foreach (var tool in tools) { if (string.IsNullOrWhiteSpace(tool.Name)) continue; var modelName = McpToolDescriptor.BuildModelFacingName(server.Name, tool.Name); if (!seen.Add(modelName)) { _logger.LogWarning( "MCP {Server} tool '{Tool}' produces duplicate model-facing name '{Model}'. Skipping.", server.Name, tool.Name, modelName); continue; } var safety = ResolveSafety(server, tool.Name); var capability = new LlmToolCapability { Name = modelName, Description = tool.Description ?? $"MCP tool '{tool.Name}' from server '{server.Name}'.", InputSchema = McpToolDescriptor.BuildInputSchema(tool), Safety = safety, }; var descriptor = new McpToolDescriptor(server.Name, tool.Name, capability); _toolRegistry.Register(descriptor); registeredNames.Add(modelName); } // Patterns are matched against the RAW server-side tool name, while the model sees the // sanitized "{server}__{tool}" form. An operator who copied the model-facing name gets a silent // no-match, so say it out loud instead — with a real example from this server. var unmatched = FindUnmatchedOverrides(server, tools); if (unmatched.Count > 0) { var example = tools.Count > 0 ? McpToolDescriptor.BuildModelFacingName(server.Name, tools[0].Name) : "(no tools discovered)"; foreach (var ovr in unmatched) { _logger.LogWarning( "MCP {Server}: safety override '{Pattern}' matched no discovered tool. Patterns match the raw " + "server-side name, not the model-facing form; names seen by the model here look like '{Example}'.", server.Name, ovr.ToolNamePattern, example); } } lock (_gate) { _registeredToolNames[server.Name] = registeredNames; } } /// /// Overrides of that match none of . A pure /// function so the diagnostic below is testable without an MCP server. /// internal static IReadOnlyList FindUnmatchedOverrides( McpServerOptions server, IReadOnlyList tools) { if (server.SafetyOverrides.Count == 0) return []; return server.SafetyOverrides .Where(ovr => !tools.Any(tool => !string.IsNullOrWhiteSpace(tool.Name) && ovr.Matches(tool.Name))) .ToArray(); } private static LlmToolSafety ResolveSafety(McpServerOptions server, string rawToolName) { foreach (var ovr in server.SafetyOverrides) { if (ovr.Matches(rawToolName)) return ovr.Safety; } return server.DefaultSafety; } private void OnToolsChanged(McpServerOptions server, IMcpClient client) { _ = Task.Run(async () => { try { var tools = await client.ListToolsAsync().ConfigureAwait(false); RegisterDescriptors(server, tools); _logger.LogInformation( "MCP {Server} tools refreshed ({Count} tool(s)).", server.Name, tools.Count); } catch (Exception ex) { _logger.LogWarning(ex, "MCP {Server} tools refresh failed.", server.Name); } }); } } Path: redb-route/redb.Route.Llm.Mcp/McpEndpoint.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/redb.Route.Llm.Mcp/McpEndpoint.cs ---- using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Llm.Mcp; /// /// MCP endpoint — a single (server, tool) coordinate. Producer-only. /// public sealed class McpEndpoint : EndpointBase { /// Creates a new MCP endpoint. /// Parsed URI. /// Owning component. /// Endpoint options. public McpEndpoint(EndpointUri uri, McpComponent component, McpEndpointOptions options) : base(uri, component, options) { } /// The MCP server registry, resolved from the parent component. internal IMcpRegistry Registry => ((McpComponent)Component).Registry; /// Logical server name from the URI path. public string ServerName => Options.ServerName; /// Server-side tool name from the URI path. public string ToolName => Options.ToolName; /// public override IProducer CreateProducer() => new McpProducer(this, Options); /// public override IConsumer CreateConsumer(IProcessor processor) => throw new NotSupportedException( "mcp:// is producer-only. MCP servers are invoked via tools/call from the agent loop."); } Path: redb-route/redb.Route.Llm.Mcp/McpEndpointOptions.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/redb.Route.Llm.Mcp/McpEndpointOptions.cs ---- using redb.Route.Core; namespace redb.Route.Llm.Mcp; /// /// Endpoint options for the mcp:// scheme. The URI parser maps /// mcp://serverName/toolName to + . /// Optional ?callTimeoutMs=30000 (milliseconds) overrides the per-call timeout. /// public sealed class McpEndpointOptions : EndpointOptions { /// Logical MCP server name (registry key set by AddMcpServer). public string ServerName { get; set; } = ""; /// Server-side tool name (raw name as returned by tools/list). public string ToolName { get; set; } = ""; /// Per-call timeout in milliseconds. Default 60s. 0 = no client-side timeout. public int CallTimeoutMs { get; set; } = 60_000; /// public override void Validate() { if (string.IsNullOrWhiteSpace(ServerName)) throw new InvalidOperationException("mcp:// URI requires a server name (mcp://serverName/toolName)."); if (string.IsNullOrWhiteSpace(ToolName)) throw new InvalidOperationException("mcp:// URI requires a tool name (mcp://serverName/toolName)."); if (CallTimeoutMs < 0) throw new ArgumentOutOfRangeException(nameof(CallTimeoutMs), "CallTimeoutMs must be non-negative."); } } Path: redb-route/redb.Route.Llm.Mcp/McpException.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/redb.Route.Llm.Mcp/McpException.cs ---- namespace redb.Route.Llm.Mcp; /// /// Thrown when an MCP server returns a JSON-RPC error, the transport fails, /// or the protocol is violated. Catch at the MCP boundary; do not surface raw /// JSON-RPC errors to the agent. /// public class McpException : Exception { /// Creates a new with a message. public McpException(string message) : base(message) { } /// Creates a new with a message and inner exception. public McpException(string message, Exception inner) : base(message, inner) { } } Path: redb-route/redb.Route.Llm.Mcp/McpProducer.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/redb.Route.Llm.Mcp/McpProducer.cs ---- using System.Diagnostics; using System.Text.Json; using System.Text.Json.Nodes; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Telemetry; namespace redb.Route.Llm.Mcp; /// /// MCP producer — translates an exchange into an MCP tools/call RPC. /// The exchange body is interpreted as JSON arguments; the result's /// content[] array is serialized back to a JSON string in /// . /// public sealed class McpProducer : IProducer { private readonly McpEndpoint _endpoint; private readonly McpEndpointOptions _options; /// Creates a new MCP producer. /// Owning endpoint. /// Endpoint options. public McpProducer(McpEndpoint endpoint, McpEndpointOptions options) { _endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint)); _options = options ?? throw new ArgumentNullException(nameof(options)); } /// public Task Start(CancellationToken ct = default) => Task.CompletedTask; /// public Task Stop(CancellationToken ct = default) => Task.CompletedTask; /// public async Task Process(IExchange exchange, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(exchange); // A transport span of this endpoint: redb.route.endpoint, and nothing when the context has tracing off. using var activity = RouteTelemetryExtensions.StartTransportSpan( (_endpoint.Component as ComponentBase)?.Context, $"mcp.tools/call {_endpoint.ServerName}/{_endpoint.ToolName}", ActivityKind.Client, "rpc.system", "mcp", _endpoint.Uri.NormalizedKey); if (activity is { IsAllDataRequested: true }) { activity.SetTag("rpc.service", _endpoint.ServerName); activity.SetTag("rpc.method", _endpoint.ToolName); } try { await CallAsync(exchange, ct).ConfigureAwait(false); } catch (Exception ex) when (ex is not OperationCanceledException || !ct.IsCancellationRequested) { // Only our own token cancelling the call is a stop; any other failure, the call timeout included, marks the span. activity.RecordFailure(ex); throw; } } private async Task CallAsync(IExchange exchange, CancellationToken ct) { var client = _endpoint.Registry.GetClient(_endpoint.ServerName) ?? throw new McpException($"MCP server '{_endpoint.ServerName}' is not registered or has been disposed."); if (client.Status is McpClientStatus.Dead) throw new McpException($"MCP server '{_endpoint.ServerName}' is dead. Toolset will refresh on restart."); var arguments = ParseArguments(exchange.In.Body); using var linkedCts = CreateLinkedCts(ct, _options.CallTimeoutMs); try { var result = await client.CallToolAsync(_endpoint.ToolName, arguments, linkedCts.Token).ConfigureAwait(false); // Replace the body with the serialized content array. The agent engine's // SerializeReply path handles strings as raw JSON. var json = result.Content?.ToJsonString() ?? "[]"; exchange.In.Body = json; exchange.In.ContentType = "application/json"; exchange.In.Headers["Mcp-Server"] = _endpoint.ServerName; exchange.In.Headers["Mcp-Tool"] = _endpoint.ToolName; if (result.IsError) exchange.In.Headers["Mcp-IsError"] = "true"; } catch (OperationCanceledException) when (!ct.IsCancellationRequested) { throw new TimeoutException( $"MCP tools/call to '{_endpoint.ServerName}/{_endpoint.ToolName}' timed out after {_options.CallTimeoutMs}ms."); } } private static JsonNode? ParseArguments(object? body) { return body switch { null => null, JsonNode node => node, string s when string.IsNullOrWhiteSpace(s) => null, string s => SafeParse(s), _ => SafeParse(JsonSerializer.Serialize(body)), }; } private static JsonNode? SafeParse(string json) { try { return JsonNode.Parse(json); } catch (JsonException) { return null; } } private static CancellationTokenSource CreateLinkedCts(CancellationToken ct, int timeoutMs) { if (timeoutMs <= 0) return CancellationTokenSource.CreateLinkedTokenSource(ct); var linked = CancellationTokenSource.CreateLinkedTokenSource(ct); linked.CancelAfter(timeoutMs); return linked; } } Path: redb-route/redb.Route.Llm.Mcp/McpServerOptions.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/redb.Route.Llm.Mcp/McpServerOptions.cs ---- using System.Text.RegularExpressions; using redb.Route.Llm.Abstractions.Tools; using redb.Route.Llm.Mcp.Transport; namespace redb.Route.Llm.Mcp; /// /// Restart policy for an MCP stdio server. /// public sealed class McpRestartPolicy { /// How many auto-restart attempts before giving up. Default 3. public int MaxAttempts { get; init; } = 3; /// Backoff schedule applied between restarts. Default: 1s, 3s, 10s. public IReadOnlyList Backoff { get; init; } = [ TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(3), TimeSpan.FromSeconds(10), ]; /// Default policy: 3 attempts at 1s, 3s, 10s. public static McpRestartPolicy Default { get; } = new(); /// Disable auto-restart entirely. public static McpRestartPolicy None { get; } = new() { MaxAttempts = 0, Backoff = [] }; } /// /// Per-tool safety override. The first matching wins. /// public sealed class McpSafetyOverride { private string _toolNamePattern = string.Empty; private Regex? _compiled; /// /// Regex matched against the raw server-side tool name — the name the MCP server reports, /// not the model-facing {server}__{tool} form the descriptor exposes /// ( sanitises the server name to 24 chars and /// the tool name to 36, replacing invalid characters with _). A pattern copied from the /// model-facing name therefore matches nothing; the discovery service warns about overrides that /// matched no discovered tool. /// Example: for server serena and tool find_symbol the pattern is /// ^find_symbol$, not ^serena__find_symbol$. /// The pattern is compiled when the override is built, so a typo fails at configuration time /// instead of surfacing later as "the server is silently missing from the tool set". /// public required string ToolNamePattern { get => _toolNamePattern; init { ArgumentException.ThrowIfNullOrWhiteSpace(value); try { _compiled = new Regex(value, RegexOptions.Compiled); } catch (ArgumentException ex) { throw new ArgumentException( $"MCP safety override pattern '{value}' is not a valid regex: {ex.Message}", nameof(ToolNamePattern), ex); } _toolNamePattern = value; } } /// Replacement to attach to the descriptor. public required LlmToolSafety Safety { get; init; } /// Whether this override accepts (a raw server-side name). internal bool Matches(string toolName) => (_compiled ??= new Regex(ToolNamePattern, RegexOptions.Compiled)).IsMatch(toolName); } /// /// Configuration for a single MCP server entry. Built via /// . /// public sealed class McpServerOptions { /// Logical server name — used as the registry key and embedded into descriptor names. public required string Name { get; init; } /// Transport configuration (stdio or HTTP+SSE). public required McpTransport Transport { get; init; } /// Maximum time to wait for initialize + tools/list. Default 30s. public TimeSpan DiscoveryTimeout { get; init; } = TimeSpan.FromSeconds(30); /// Auto-restart policy for stdio transports. public McpRestartPolicy RestartPolicy { get; init; } = McpRestartPolicy.Default; /// Per-tool safety overrides (first match wins). public IReadOnlyList SafetyOverrides { get; init; } = []; /// /// Default safety attached when no override matches. Discovery cannot know what a third-party tool /// does, so it assumes the worst: external side effects and an approval requirement. /// /// Note what approval means with the shipped gate: approves /// automatically, so this flag buys an audit row (ApprovalId = "auto" in /// ApprovalProps), not a control point. A deployment that wants the call blocked until a /// human answers must replace the gate — services.Replace(ServiceDescriptor.Singleton<IApprovalGate, DenyAllGate>()) /// or a custom . /// /// public LlmToolSafety DefaultSafety { get; init; } = new() { SideEffect = ToolSideEffect.External, Cost = ToolCostClass.Cheap, RequiresApproval = true, }; } Path: redb-route/redb.Route.Llm.Mcp/McpToolDescriptor.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/redb.Route.Llm.Mcp/McpToolDescriptor.cs ---- using System.Text.RegularExpressions; using redb.Route.Abstractions; using redb.Route.Llm.Abstractions.Tools; using redb.Route.Llm.Mcp.Protocol; namespace redb.Route.Llm.Mcp; /// /// backed by a remote MCP tool. Capability built once /// from tools/list metadata; returns the /// precomputed mcp://server/tool URI so dispatch is constant-time. /// public sealed class McpToolDescriptor : ILlmToolDescriptor { /// Maximum length of an LLM-facing tool name (Anthropic / OpenAI cap). public const int MaxToolNameLength = 64; /// Maximum length of the server-prefix segment. public const int MaxServerPrefixLength = 24; /// Maximum length of the tool-name segment. public const int MaxToolPartLength = 36; /// Separator between sanitized server prefix and tool name. public const string Separator = "__"; private static readonly Regex InvalidChars = new("[^a-zA-Z0-9_]", RegexOptions.Compiled); private static readonly Regex StartsWithDigit = new("^[0-9]", RegexOptions.Compiled); /// public LlmToolCapability Capability { get; } /// The raw server-side tool name (as returned by tools/list). public string RawToolName { get; } /// Logical MCP server name. public string ServerName { get; } /// Precomputed mcp://server/tool dispatch URI. public string EndpointUri { get; } /// Creates a new descriptor — usually built by . /// Logical server name. /// Raw server-side tool name. /// Capability projected to the model. public McpToolDescriptor(string serverName, string rawToolName, LlmToolCapability capability) { ArgumentException.ThrowIfNullOrWhiteSpace(serverName); ArgumentException.ThrowIfNullOrWhiteSpace(rawToolName); ArgumentNullException.ThrowIfNull(capability); ServerName = serverName; RawToolName = rawToolName; Capability = capability; EndpointUri = $"mcp://{serverName}/{rawToolName}"; } /// public string BuildEndpointUri(string inputJson, IExchange parentExchange) => EndpointUri; /// /// Builds an LLM-facing tool name {server}{Separator}{tool} truncated to fit /// the 64-char model limit, with non-alphanumerics replaced by _. /// /// Logical server name. /// Raw tool name. /// Sanitized model-facing name (≤ ). public static string BuildModelFacingName(string serverName, string toolName) { var server = Sanitize(serverName, MaxServerPrefixLength); var tool = Sanitize(toolName, MaxToolPartLength); var combined = $"{server}{Separator}{tool}"; if (combined.Length > MaxToolNameLength) combined = combined[..MaxToolNameLength]; if (StartsWithDigit.IsMatch(combined)) combined = "_" + combined[..(MaxToolNameLength - 1)]; return combined; } /// Builds the JSON-Schema string for a descriptor — falls back to a permissive object when missing. /// Tool definition received from tools/list. public static string BuildInputSchema(ToolDefinition definition) { ArgumentNullException.ThrowIfNull(definition); return definition.InputSchema?.ToJsonString() ?? """{"type":"object","additionalProperties":true}"""; } private static string Sanitize(string value, int maxLength) { var cleaned = InvalidChars.Replace(value, "_"); if (cleaned.Length > maxLength) cleaned = cleaned[..maxLength]; return cleaned; } } Path: redb-route/redb.Route.Llm.Mcp/Protocol/IMcpClient.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/redb.Route.Llm.Mcp/Protocol/IMcpClient.cs ---- using System.Text.Json.Nodes; using redb.Route.Llm.Mcp.Protocol; namespace redb.Route.Llm.Mcp; /// /// Health state of an . Surfaced by /// so observers can drop dead servers from the agent toolset. /// public enum McpClientStatus { /// Not yet started. Idle, /// Currently performing the initialize + tools/list handshake. Connecting, /// Connected and ready to handle tools/call. Healthy, /// Lost connection — auto-restart in flight. Restarting, /// Restart budget exhausted — stays dead until a manual restart. Dead } /// /// Transport-agnostic MCP client. Implementations spawn / hold the connection, /// perform the protocol handshake, and dispatch tools/call requests /// against a single MCP server. Lifetime is owned by the host (singleton in DI). /// public interface IMcpClient : IAsyncDisposable { /// Logical server name as registered with . string ServerName { get; } /// Current health state of the client. McpClientStatus Status { get; } /// Server identification reported during initialize; null until handshake completes. InitializeResult? Initialize { get; } /// /// Raised after a notifications/tools/list_changed from the server, /// or after the client reconnects (so the registry refreshes the descriptor set). /// event EventHandler? ToolsChanged; /// Performs the initialize handshake. Must be called before any other method. Task InitializeAsync(CancellationToken cancellationToken = default); /// Returns the current tool catalogue via tools/list. Task> ListToolsAsync(CancellationToken cancellationToken = default); /// /// Invokes a tool via tools/call. On trip the client /// sends a notifications/cancelled for the in-flight id and removes the pending TCS. /// /// Server-side tool name. /// Arguments matching the tool's inputSchema; null = empty object. /// Cancellation token. Task CallToolAsync(string toolName, JsonNode? arguments, CancellationToken cancellationToken = default); } Path: redb-route/redb.Route.Llm.Mcp/Protocol/McpClientBase.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/redb.Route.Llm.Mcp/Protocol/McpClientBase.cs ---- using System.Collections.Concurrent; using System.Text.Json; using System.Text.Json.Nodes; using Microsoft.Extensions.Logging; using redb.Route.Llm.Mcp.Protocol; namespace redb.Route.Llm.Mcp.Protocol; /// /// Shared client logic: per-id registry, /// monotonic id generator, response demux, notifications/cancelled emission on /// CT trip. Subclasses provide the byte-level transport ( + /// the read pump that calls ). /// public abstract class McpClientBase : IMcpClient { private readonly ConcurrentDictionary> _pending = new(); private long _nextId; /// Logger used by the client and its read pump. protected ILogger Logger { get; } /// public string ServerName { get; } /// public McpClientStatus Status { get; protected set; } = McpClientStatus.Idle; /// public InitializeResult? Initialize { get; private set; } /// public event EventHandler? ToolsChanged; /// Initializes the base client with the given server name and logger. /// Logical server identifier (registry key). /// Logger. protected McpClientBase(string serverName, ILogger logger) { ArgumentException.ThrowIfNullOrWhiteSpace(serverName); ArgumentNullException.ThrowIfNull(logger); ServerName = serverName; Logger = logger; } /// public async Task InitializeAsync(CancellationToken cancellationToken = default) { Status = McpClientStatus.Connecting; try { await StartTransportAsync(cancellationToken).ConfigureAwait(false); var initParams = new JsonObject { ["protocolVersion"] = McpProtocol.ProtocolVersion, ["capabilities"] = new JsonObject(), ["clientInfo"] = new JsonObject { ["name"] = "redb.Route.Llm.Mcp", ["version"] = "3.1.1", }, }; var resultNode = await SendRequestAsync("initialize", initParams, cancellationToken).ConfigureAwait(false); Initialize = resultNode?.Deserialize(McpProtocol.JsonOptions); if (Initialize is null) throw new McpException($"Server '{ServerName}' returned an empty initialize result."); if (!string.IsNullOrEmpty(Initialize.ProtocolVersion) && Initialize.ProtocolVersion != McpProtocol.ProtocolVersion) { Logger.LogWarning( "MCP server {Server} negotiated protocol version {Negotiated} (we sent {Sent}). Continuing.", ServerName, Initialize.ProtocolVersion, McpProtocol.ProtocolVersion); } // Notify the server that we've finished the handshake. await SendNotificationAsync("notifications/initialized", null, cancellationToken).ConfigureAwait(false); Status = McpClientStatus.Healthy; Logger.LogInformation( "MCP client '{Server}' connected. ServerInfo={ServerInfo}", ServerName, Initialize.ServerInfo?.Name); } catch { Status = McpClientStatus.Dead; throw; } } /// public async Task> ListToolsAsync(CancellationToken cancellationToken = default) { var resultNode = await SendRequestAsync("tools/list", null, cancellationToken).ConfigureAwait(false); var listed = resultNode?.Deserialize(McpProtocol.JsonOptions); return listed?.Tools ?? []; } /// public async Task CallToolAsync(string toolName, JsonNode? arguments, CancellationToken cancellationToken = default) { ArgumentException.ThrowIfNullOrWhiteSpace(toolName); var callParams = new JsonObject { ["name"] = toolName, ["arguments"] = arguments ?? new JsonObject(), }; var resultNode = await SendRequestAsync("tools/call", callParams, cancellationToken).ConfigureAwait(false); return resultNode?.Deserialize(McpProtocol.JsonOptions) ?? new CallToolResult { Content = new JsonArray(), IsError = false }; } /// public virtual async ValueTask DisposeAsync() { // Fail any pending requests so callers don't hang. foreach (var (_, tcs) in _pending) tcs.TrySetException(new McpException($"MCP client '{ServerName}' was disposed.")); _pending.Clear(); try { await StopTransportAsync().ConfigureAwait(false); } catch (Exception ex) { Logger.LogDebug(ex, "MCP {Server} transport stop threw.", ServerName); } Status = McpClientStatus.Dead; GC.SuppressFinalize(this); } // ── Transport hooks (subclass) ────────────────────────────────────────── /// Brings up the byte-level transport (e.g. spawn process, open HTTP/SSE channels). protected abstract Task StartTransportAsync(CancellationToken cancellationToken); /// Tears the transport down. Should not throw on already-stopped state. protected abstract Task StopTransportAsync(); /// Writes a single JSON frame to the server. Implementations must serialize concurrent writes. /// Already-serialized JSON-RPC frame (no trailing newline — the transport adds it if needed). /// Cancellation token. protected abstract Task SendFrameAsync(string frameJson, CancellationToken cancellationToken); /// Called by the transport's read pump for every received frame (response or notification). /// Raw JSON text — newline already stripped, single message. protected void OnFrameReceived(string frameJson) { if (string.IsNullOrWhiteSpace(frameJson)) return; JsonNode? root; try { root = JsonNode.Parse(frameJson); } catch (JsonException ex) { Logger.LogTrace(ex, "MCP {Server} skipping non-JSON frame: {Frame}", ServerName, frameJson); return; } if (root is not JsonObject obj) return; // Response carries an "id"; notification carries a "method" but no "id". if (obj.TryGetPropertyValue("id", out var idNode) && idNode is not null) { var resp = obj.Deserialize(McpProtocol.JsonOptions); if (resp?.Id is { } id && _pending.TryRemove(id, out var tcs)) tcs.TrySetResult(resp); return; } if (obj.TryGetPropertyValue("method", out var methodNode) && methodNode is not null) { var method = methodNode.GetValue(); HandleNotification(method); } } /// Convenience: invoked by transports when the connection drops outside our control. /// Optional human-readable reason for logging. protected void OnTransportFailed(string? reason) { Logger.LogWarning("MCP {Server} transport failed: {Reason}. Failing {Pending} pending request(s).", ServerName, reason ?? "unknown", _pending.Count); // Mark dead so producers / registry consumers can short-circuit subsequent // calls instead of blocking on a transport that no longer exists. The // McpDiscoveryService can spin up a fresh client on its own schedule. Status = McpClientStatus.Dead; foreach (var (_, tcs) in _pending) tcs.TrySetException(new McpException($"MCP client '{ServerName}' transport failed: {reason}")); _pending.Clear(); } // ── Internals ─────────────────────────────────────────────────────────── private async Task SendRequestAsync(string method, JsonNode? @params, CancellationToken cancellationToken) { var id = Interlocked.Increment(ref _nextId); var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); _pending[id] = tcs; var request = new JsonRpcRequest { Id = id, Method = method, Params = @params }; var json = JsonSerializer.Serialize(request, McpProtocol.JsonOptions); await using var ctReg = cancellationToken.Register(() => { if (_pending.TryRemove(id, out var t)) { t.TrySetCanceled(cancellationToken); _ = SendCancelNotificationAsync(id); } }); try { await SendFrameAsync(json, cancellationToken).ConfigureAwait(false); } catch { _pending.TryRemove(id, out _); throw; } var response = await tcs.Task.ConfigureAwait(false); if (response.Error is not null) throw new McpException( $"MCP server '{ServerName}' returned error for {method}: {response.Error.Code} {response.Error.Message}"); return response.Result; } private async Task SendNotificationAsync(string method, JsonNode? @params, CancellationToken cancellationToken) { var note = new JsonRpcNotification { Method = method, Params = @params }; var json = JsonSerializer.Serialize(note, McpProtocol.JsonOptions); await SendFrameAsync(json, cancellationToken).ConfigureAwait(false); } private async Task SendCancelNotificationAsync(long requestId) { try { var @params = new JsonObject { ["requestId"] = requestId, ["reason"] = "client cancelled" }; await SendNotificationAsync("notifications/cancelled", @params, CancellationToken.None).ConfigureAwait(false); } catch (Exception ex) { Logger.LogTrace(ex, "MCP {Server} failed to send cancel notification for id {Id}.", ServerName, requestId); } } private void HandleNotification(string method) { switch (method) { case "notifications/tools/list_changed": Logger.LogInformation("MCP {Server} reported tools/list_changed.", ServerName); ToolsChanged?.Invoke(this, EventArgs.Empty); break; case "notifications/initialized": // Client→server only; ignore if we ever see it bouncing back. break; default: Logger.LogTrace("MCP {Server} received notification {Method}.", ServerName, method); break; } } } Path: redb-route/redb.Route.Llm.Mcp/Protocol/McpProtocol.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/redb.Route.Llm.Mcp/Protocol/McpProtocol.cs ---- using System.Text.Json; using System.Text.Json.Nodes; using System.Text.Json.Serialization; namespace redb.Route.Llm.Mcp.Protocol; /// /// MCP protocol DTOs and JSON-RPC envelope types. Pinned to MCP protocol version /// 2024-11-05 — the dialect Serena, Claude Desktop, and the official Anthropic /// servers all speak. /// public static class McpProtocol { /// The MCP protocol version this client advertises during initialize. public const string ProtocolVersion = "2024-11-05"; /// JSON-RPC 2.0 protocol identifier. public const string JsonRpcVersion = "2.0"; /// Shared JSON serialization options. matches MCP-server expectations (no nulls on the wire). public static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web) { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, WriteIndented = false, // UTF-8 on the wire, not \uXXXX — non-ASCII tool args / results stay readable. Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping, }; } /// JSON-RPC 2.0 request envelope. public sealed class JsonRpcRequest { /// Always "2.0". [JsonPropertyName("jsonrpc")] public string JsonRpc { get; set; } = McpProtocol.JsonRpcVersion; /// Correlation id matching the eventual . [JsonPropertyName("id")] public long Id { get; set; } /// RPC method name (e.g. "tools/call"). [JsonPropertyName("method")] public string Method { get; set; } = ""; /// Method-specific parameters as a JSON object. [JsonPropertyName("params")] public JsonNode? Params { get; set; } } /// JSON-RPC 2.0 response envelope. public sealed class JsonRpcResponse { /// Always "2.0". [JsonPropertyName("jsonrpc")] public string JsonRpc { get; set; } = McpProtocol.JsonRpcVersion; /// Correlation id matching the originating . [JsonPropertyName("id")] public long? Id { get; set; } /// Successful method result. Mutually exclusive with . [JsonPropertyName("result")] public JsonNode? Result { get; set; } /// Error envelope when the call failed. [JsonPropertyName("error")] public JsonRpcError? Error { get; set; } } /// JSON-RPC error object. public sealed class JsonRpcError { /// Numeric error code per JSON-RPC convention. [JsonPropertyName("code")] public int Code { get; set; } /// Human-readable error message. [JsonPropertyName("message")] public string Message { get; set; } = ""; /// Optional structured error data. [JsonPropertyName("data")] public JsonNode? Data { get; set; } } /// JSON-RPC 2.0 server-initiated notification (no response expected). public sealed class JsonRpcNotification { /// Always "2.0". [JsonPropertyName("jsonrpc")] public string JsonRpc { get; set; } = McpProtocol.JsonRpcVersion; /// Notification method name (e.g. "notifications/tools/list_changed"). [JsonPropertyName("method")] public string Method { get; set; } = ""; /// Notification payload. [JsonPropertyName("params")] public JsonNode? Params { get; set; } } /// Result of the initialize handshake. public sealed class InitializeResult { /// Protocol version the server has agreed to speak. [JsonPropertyName("protocolVersion")] public string ProtocolVersion { get; set; } = ""; /// Server identification (name/version). [JsonPropertyName("serverInfo")] public ServerInfo? ServerInfo { get; set; } /// Server capability flags (verbatim — we don't interpret beyond logging). [JsonPropertyName("capabilities")] public JsonNode? Capabilities { get; set; } } /// Server identification block returned during initialize. public sealed class ServerInfo { /// Server name (free-form, e.g. "serena"). [JsonPropertyName("name")] public string Name { get; set; } = ""; /// Server version string. [JsonPropertyName("version")] public string Version { get; set; } = ""; } /// One tool entry as returned by tools/list. public sealed class ToolDefinition { /// Server-side tool name (raw, before redb sanitisation). [JsonPropertyName("name")] public string Name { get; set; } = ""; /// Human-readable description shown to the model. [JsonPropertyName("description")] public string? Description { get; set; } /// JSON Schema for the tool's input arguments. [JsonPropertyName("inputSchema")] public JsonNode? InputSchema { get; set; } } /// Result of tools/list. public sealed class ListToolsResult { /// The list of tools the server exposes. [JsonPropertyName("tools")] public List Tools { get; set; } = []; } /// Result of tools/call. public sealed class CallToolResult { /// Content blocks produced by the tool (text, images, embedded resources). [JsonPropertyName("content")] public JsonNode? Content { get; set; } /// True when the tool reported an error condition. [JsonPropertyName("isError")] public bool IsError { get; set; } } Path: redb-route/redb.Route.Llm.Mcp/README.md 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/redb.Route.Llm.Mcp/README.md ---- # redb.Route.Llm.Mcp > Documentation and articles: MCP (Model Context Protocol) client connector for **redb.Route.Llm**. Spawns external MCP servers (stdio + HTTP+SSE), discovers their tool catalogue via `tools/list`, and projects every remote tool into the existing `IToolDescriptorRegistry` so the agent picks them up like any native redb tool. ## Wave 1 (current) - `mcp://` scheme — `mcp://serverName/toolName` invokes `tools/call`. - Stdio transport (spawn external process; newline-delimited JSON-RPC). - HTTP + SSE transport (POST request, SSE for server-initiated frames). - `IHostedService` discovery on host startup — `initialize` + `tools/list`. - Listens for `notifications/tools/list_changed` and refreshes descriptors. - Cancellation flows through `IProducerTemplate.RequestBody(uri, msg, ct)` → `IProducer.Process(exchange, ct)` → `IMcpClient.CallToolAsync(..., ct)` → `notifications/cancelled`. - Tool-name sanitisation: `{server}__{tool}`, server ≤ 24 chars, tool ≤ 36, total ≤ 64. - Safety defaults to `External` + `Cheap` + no approval; per-tool override via regex in `McpServerOptions.SafetyOverrides`. ## Quickstart ```csharp services.AddRedbRoute(...); services.AddRedbRouteLlm(...); services.AddRedbRouteMcp(); services.AddMcpServer("serena", McpTransport.Stdio( "uvx", [ "--from", "git+https://github.com/oraios/serena", "serena", "start-mcp-server", "--context", "ide", "--project", "C:/path/to/project", ])); ``` The agent now sees Serena's full tool catalogue (`serena__find_symbol`, `serena__get_symbols_overview`, …) alongside any native redb tools. ## In a Tsak module A module gets the context in `InitRoute.main` and builds the registry itself, from settings it reads from its configuration; the connector does not read configuration. Give the registry to the context, then call `mcp://` from C# routes or from the package's XML routes: ```csharp public static class InitRoute { public static async Task main(IRouteContext ctx) { // command, arguments and logger: the module's own, from its configuration and logging var registry = new McpRegistry(); var client = new StdioMcpClient("serena", McpTransport.Stdio(command, arguments), logger); await client.InitializeAsync(); registry.Register(client); ctx.AddService(typeof(IMcpRegistry), registry); // McpComponent() finds it here return ctx; } } ``` ```xml ``` `new McpComponent()` takes the registry the context holds: the one module code added with `ctx.AddService`, else the `IMcpRegistry` singleton of `AddRedbRouteMcp()` in a hosted app. Without either, creating an `mcp://` endpoint fails and the message names both ways. `new McpComponent(registry)` and `AddRedbRouteMcp()` work as before. ## Tracing On the `redb.Route` activity source (`AddSource("redb.Route")`): one `Client` span per `tools/call`, `mcp.tools/call {server}/{tool}`, with `rpc.system` = `mcp`, `rpc.service`, `rpc.method` and `redb.route.endpoint`. An error when the call fails (an unknown or dead server, a tool error, the call timeout), unless our own token cancelled it. `RouteEngineOptions.EnableTelemetry = false` opens none. ## Out of scope (Wave 2+) - MCP `resources` and `prompts`. - MCP `sampling` (server asking the host to do an LLM call). - Allow-list / sandboxing of MCP servers. Path: redb-route/redb.Route.Llm.Mcp/Transport/HttpSseMcpClient.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/redb.Route.Llm.Mcp/Transport/HttpSseMcpClient.cs ---- using System.Net; using System.Net.Http.Headers; using System.Text; using Microsoft.Extensions.Logging; using redb.Route.Llm.Mcp.Protocol; namespace redb.Route.Llm.Mcp.Transport; /// /// HTTP + SSE transport. POSTs JSON-RPC requests to the base URL, opens a parallel /// SSE channel (GET) for server-initiated frames (notifications, tools/list_changed). /// Bearer auth via . /// public sealed class HttpSseMcpClient : McpClientBase { private readonly McpTransport _transport; private readonly HttpClient _http; private readonly bool _ownsHttpClient; private CancellationTokenSource? _sseCts; private Task? _ssePump; /// The client this transport sends through (tests read its transport defaults). internal HttpClient Http => _http; /// /// Transport of the client this class creates itself: HTTP/2 keep-alive pings every 15 seconds while a request /// is in flight. The SSE stream stays open and can be silent between events for minutes, and VPN tunnels, NAT /// and proxies drop a connection that is silent for about 50 seconds. A copy of /// redb.Route.Llm.Providers.LlmHttpTransport.BuildHandler (this package does not reference /// redb.Route.Llm): change both together. A client the host passes in is used as it is. /// private static SocketsHttpHandler BuildKeepAliveHandler() => new() { PooledConnectionLifetime = TimeSpan.FromMinutes(5), KeepAlivePingDelay = TimeSpan.FromSeconds(15), KeepAlivePingTimeout = TimeSpan.FromSeconds(20), KeepAlivePingPolicy = HttpKeepAlivePingPolicy.WithActiveRequests, }; /// Creates a new HTTP+SSE MCP client. /// Logical server name. /// HTTP+SSE transport configuration. /// Logger. /// Optional HTTP client (DI-managed); a private one is created if null. public HttpSseMcpClient(string serverName, McpTransport transport, ILogger logger, HttpClient? httpClient = null) : base(serverName, logger) { ArgumentNullException.ThrowIfNull(transport); if (transport.Kind != McpTransportKind.HttpSse) throw new ArgumentException("HttpSseMcpClient requires an HTTP+SSE transport.", nameof(transport)); if (string.IsNullOrWhiteSpace(transport.BaseUrl)) throw new ArgumentException("HTTP+SSE transport requires a BaseUrl.", nameof(transport)); _transport = transport; if (httpClient is not null) { _http = httpClient; _ownsHttpClient = false; } else { _http = new HttpClient(BuildKeepAliveHandler()) { BaseAddress = new Uri(transport.BaseUrl, UriKind.Absolute), // HTTP/2 when the server offers it, so the keep-alive pings have a frame to ride on. DefaultRequestVersion = HttpVersion.Version20, DefaultVersionPolicy = HttpVersionPolicy.RequestVersionOrLower, }; _ownsHttpClient = true; } if (!string.IsNullOrEmpty(transport.BearerToken)) _http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", transport.BearerToken); } /// protected override Task StartTransportAsync(CancellationToken cancellationToken) { _sseCts = new CancellationTokenSource(); _ssePump = Task.Run(() => SsePumpAsync(_sseCts.Token)); return Task.CompletedTask; } /// protected override async Task StopTransportAsync() { try { _sseCts?.Cancel(); } catch { /* ignored */ } try { if (_ssePump is not null) await _ssePump.ConfigureAwait(false); } catch { /* pump exceptions surface via OnTransportFailed */ } _ssePump = null; _sseCts?.Dispose(); _sseCts = null; if (_ownsHttpClient) _http.Dispose(); } /// protected override async Task SendFrameAsync(string frameJson, CancellationToken cancellationToken) { using var content = new StringContent(frameJson, Encoding.UTF8, "application/json"); using var response = await _http.PostAsync(_transport.BaseUrl, content, cancellationToken).ConfigureAwait(false); response.EnsureSuccessStatusCode(); // Some MCP servers return the JSON-RPC response inline; others stream via SSE. // Fold inline replies through the same demux path. var body = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); if (!string.IsNullOrWhiteSpace(body) && body.AsSpan().TrimStart().Length > 0 && body.AsSpan().TrimStart()[0] == '{') OnFrameReceived(body); } private async Task SsePumpAsync(CancellationToken ct) { try { // A hand-built request starts at HTTP/1.1 whatever the client asks for; carry the client's version over, // or the keep-alive pings never run on the stream. using var req = new HttpRequestMessage(HttpMethod.Get, _transport.BaseUrl) { Version = _http.DefaultRequestVersion, VersionPolicy = _http.DefaultVersionPolicy, }; req.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/event-stream")); using var response = await _http.SendAsync(req, HttpCompletionOption.ResponseHeadersRead, ct).ConfigureAwait(false); if (!response.IsSuccessStatusCode) { Logger.LogTrace("MCP {Server} SSE channel returned {Status}; skipping pump.", ServerName, response.StatusCode); return; } using var stream = await response.Content.ReadAsStreamAsync(ct).ConfigureAwait(false); using var reader = new StreamReader(stream, Encoding.UTF8); var dataBuffer = new StringBuilder(); while (!ct.IsCancellationRequested) { var line = await reader.ReadLineAsync(ct).ConfigureAwait(false); if (line is null) break; if (line.Length == 0) { if (dataBuffer.Length > 0) { var frame = dataBuffer.ToString(); dataBuffer.Clear(); OnFrameReceived(frame); } continue; } if (line.StartsWith("data:", StringComparison.Ordinal)) { if (dataBuffer.Length > 0) dataBuffer.Append('\n'); dataBuffer.Append(line.AsSpan(5).TrimStart()); } // Other SSE fields (event:, id:, retry:) are ignored — MCP only uses data:. } } catch (OperationCanceledException) { /* normal shutdown */ } catch (Exception ex) { Logger.LogWarning(ex, "MCP {Server} SSE pump terminated.", ServerName); OnTransportFailed($"SSE pump error: {ex.Message}"); } } } Path: redb-route/redb.Route.Llm.Mcp/Transport/McpTransport.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/redb.Route.Llm.Mcp/Transport/McpTransport.cs ---- namespace redb.Route.Llm.Mcp.Transport; /// Transport flavor for an MCP server. public enum McpTransportKind { /// Spawn an external process and exchange newline-delimited JSON over stdin/stdout. Stdio, /// POST JSON-RPC requests to a base URL; receive notifications via SSE. HttpSse } /// /// Configuration for an MCP server transport. Built via /// or and passed to . /// public sealed class McpTransport { /// Selected transport kind. public McpTransportKind Kind { get; init; } // ── stdio ── /// Executable to spawn (stdio transport). Resolved against PATH if not absolute. public string? Command { get; init; } /// Command-line arguments (stdio transport). public IReadOnlyList Arguments { get; init; } = []; /// Additional environment variables for the spawned process (stdio transport). public IReadOnlyDictionary Environment { get; init; } = new Dictionary(StringComparer.Ordinal); /// Working directory for the spawned process (stdio transport). Null = caller's CWD. public string? WorkingDirectory { get; init; } // ── http+sse ── /// Base URL for HTTP+SSE transport (e.g. https://mcp.example.com/). public string? BaseUrl { get; init; } /// Optional bearer token for HTTP+SSE transport. public string? BearerToken { get; init; } /// Builds an stdio transport configuration. /// Executable to spawn. /// Optional command-line arguments. /// Optional additional environment variables. /// Optional working directory. public static McpTransport Stdio( string command, IReadOnlyList? arguments = null, IReadOnlyDictionary? environment = null, string? workingDirectory = null) { ArgumentException.ThrowIfNullOrWhiteSpace(command); return new McpTransport { Kind = McpTransportKind.Stdio, Command = command, Arguments = arguments ?? [], Environment = environment ?? new Dictionary(StringComparer.Ordinal), WorkingDirectory = workingDirectory, }; } /// Builds an HTTP+SSE transport configuration. /// Base URL of the MCP server. /// Optional bearer token for the Authorization header. public static McpTransport Http(string baseUrl, string? bearerToken = null) { ArgumentException.ThrowIfNullOrWhiteSpace(baseUrl); return new McpTransport { Kind = McpTransportKind.HttpSse, BaseUrl = baseUrl, BearerToken = bearerToken, }; } } Path: redb-route/redb.Route.Llm.Mcp/Transport/StdioMcpClient.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/redb.Route.Llm.Mcp/Transport/StdioMcpClient.cs ---- using System.Diagnostics; using System.Text; using Microsoft.Extensions.Logging; using redb.Route.Llm.Mcp.Protocol; namespace redb.Route.Llm.Mcp.Transport; /// /// Stdio transport — spawns an external process, exchanges newline-delimited /// UTF-8 JSON-RPC frames over stdin/stdout, drains stderr to the logger. /// All stdin writes are serialised through a . /// public sealed class StdioMcpClient : McpClientBase { private readonly McpTransport _transport; private readonly SemaphoreSlim _writeLock = new(1, 1); // BOM-less UTF-8: many MCP servers (Serena, Anthropic reference) reject a // BOM-prefixed first frame as invalid JSON. The static Encoding.UTF8 emits // a BOM on WriteLine of the first chunk, so we use UTF8Encoding(false). private static readonly Encoding Utf8NoBom = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false); private Process? _process; private CancellationTokenSource? _readCts; private Task? _stdoutPump; private Task? _stderrPump; /// Creates a new stdio MCP client. /// Logical server name. /// Stdio transport configuration. /// Logger for trace/info/warning/error messages. public StdioMcpClient(string serverName, McpTransport transport, ILogger logger) : base(serverName, logger) { ArgumentNullException.ThrowIfNull(transport); if (transport.Kind != McpTransportKind.Stdio) throw new ArgumentException("StdioMcpClient requires a stdio transport.", nameof(transport)); if (string.IsNullOrWhiteSpace(transport.Command)) throw new ArgumentException("Stdio transport requires a Command.", nameof(transport)); _transport = transport; } /// protected override Task StartTransportAsync(CancellationToken cancellationToken) { var psi = new ProcessStartInfo { FileName = _transport.Command!, UseShellExecute = false, RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true, CreateNoWindow = true, StandardInputEncoding = Utf8NoBom, StandardOutputEncoding = Utf8NoBom, StandardErrorEncoding = Utf8NoBom, }; foreach (var arg in _transport.Arguments) psi.ArgumentList.Add(arg); if (!string.IsNullOrEmpty(_transport.WorkingDirectory)) psi.WorkingDirectory = _transport.WorkingDirectory; // Start from caller's environment, then overlay extras. foreach (var (k, v) in _transport.Environment) psi.EnvironmentVariables[k] = v; var proc = new Process { StartInfo = psi, EnableRaisingEvents = true }; proc.Exited += OnProcessExited; try { if (!proc.Start()) throw new McpException($"MCP stdio server '{ServerName}' failed to start (Process.Start returned false)."); } catch (Exception ex) when (ex is not McpException) { throw new McpException( $"MCP stdio server '{ServerName}' failed to start: {_transport.Command} ({ex.Message})", ex); } Logger.LogInformation( "MCP stdio server '{Server}' spawned (pid {Pid}): {Command} {Args}", ServerName, proc.Id, _transport.Command, string.Join(' ', _transport.Arguments)); _process = proc; _readCts = new CancellationTokenSource(); _stdoutPump = Task.Run(() => StdoutPumpAsync(proc, _readCts.Token)); _stderrPump = Task.Run(() => StderrPumpAsync(proc, _readCts.Token)); return Task.CompletedTask; } /// protected override async Task StopTransportAsync() { try { _readCts?.Cancel(); } catch { /* ignored */ } var proc = _process; if (proc is not null) { try { if (!proc.HasExited) { proc.Kill(entireProcessTree: true); proc.WaitForExit(2_000); } } catch (Exception ex) { Logger.LogDebug(ex, "MCP {Server} process kill threw.", ServerName); } finally { proc.Exited -= OnProcessExited; proc.Dispose(); _process = null; } } try { if (_stdoutPump is not null) await _stdoutPump.ConfigureAwait(false); if (_stderrPump is not null) await _stderrPump.ConfigureAwait(false); } catch { /* pumps own exceptions go through OnTransportFailed */ } _stdoutPump = null; _stderrPump = null; _readCts?.Dispose(); _readCts = null; } /// protected override async Task SendFrameAsync(string frameJson, CancellationToken cancellationToken) { var proc = _process; if (proc is null || proc.HasExited) throw new McpException($"MCP stdio server '{ServerName}' is not running."); await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false); try { var writer = proc.StandardInput; await writer.WriteAsync(frameJson.AsMemory(), cancellationToken).ConfigureAwait(false); await writer.WriteAsync('\n').ConfigureAwait(false); await writer.FlushAsync(cancellationToken).ConfigureAwait(false); } finally { _writeLock.Release(); } } private async Task StdoutPumpAsync(Process proc, CancellationToken ct) { try { var reader = proc.StandardOutput; while (!ct.IsCancellationRequested) { var line = await reader.ReadLineAsync(ct).ConfigureAwait(false); if (line is null) break; if (line.Length == 0) continue; // Skip non-JSON log lines that might bleed into stdout. var trimmed = line.AsSpan().TrimStart(); if (trimmed.Length == 0 || trimmed[0] != '{') { Logger.LogTrace("MCP {Server} stdout (non-frame): {Line}", ServerName, line); continue; } OnFrameReceived(line); } } catch (OperationCanceledException) { /* normal shutdown */ } catch (Exception ex) { Logger.LogWarning(ex, "MCP {Server} stdout pump terminated.", ServerName); OnTransportFailed($"stdout pump error: {ex.Message}"); } } private async Task StderrPumpAsync(Process proc, CancellationToken ct) { try { var reader = proc.StandardError; while (!ct.IsCancellationRequested) { var line = await reader.ReadLineAsync(ct).ConfigureAwait(false); if (line is null) break; if (line.Length == 0) continue; Logger.LogTrace("MCP {Server} stderr: {Line}", ServerName, line); } } catch (OperationCanceledException) { /* normal shutdown */ } catch (Exception ex) { Logger.LogTrace(ex, "MCP {Server} stderr pump terminated.", ServerName); } } private void OnProcessExited(object? sender, EventArgs e) { if (Status is McpClientStatus.Dead) return; var code = (sender as Process)?.ExitCode ?? -1; Logger.LogWarning("MCP {Server} process exited unexpectedly (code {Code}).", ServerName, code); OnTransportFailed($"process exited with code {code}"); } } Path: redb-route/redb.Route.Llm.Mcp/redb.Route.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/redb.Route.Llm.Mcp/redb.Route.Llm.Mcp.csproj ---- redb.Route.Llm.Mcp MCP (Model Context Protocol) client connector for redb.Route.Llm. Spawns external MCP servers (stdio + HTTP+SSE), discovers their tools via tools/list, and registers them as ILlmToolDescriptor entries so the agent picks them up like any native tool. Inherits redb.Route audit/governance/observability for free. llm;mcp;model-context-protocol;ai;agents;tools;redb README.md