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); } }); } }