Skip to content

Commit 96c6b4c

Browse files
committed
Automatically set the logging through stderr for MCP servers
This prevents default logging to console to disrupt the stdio protocol. We do this only and automatically when AddMcpServer was invoked previously.
1 parent 6b48562 commit 96c6b4c

File tree

1 file changed

+33
-1
lines changed

1 file changed

+33
-1
lines changed

src/Smith/App.cs

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
using Microsoft.Extensions.DependencyInjection;
22
using Microsoft.Extensions.Hosting;
3+
using Microsoft.Extensions.Logging;
4+
using Microsoft.Extensions.Options;
5+
using ModelContextProtocol.Server;
36

47
namespace Smith;
58

@@ -8,6 +11,30 @@ namespace Smith;
811
/// </summary>
912
public static class App
1013
{
14+
class AppBuilder(IServiceCollection services)
15+
{
16+
public IServiceCollection Services => services;
17+
}
18+
19+
class AppServiceFactory(HostApplicationBuilder host) : IServiceProviderFactory<AppBuilder>
20+
{
21+
public AppBuilder CreateBuilder(IServiceCollection services) => new(services);
22+
23+
public IServiceProvider CreateServiceProvider(AppBuilder builder)
24+
{
25+
// If MCP server was registered with AddMcpServer, then tune logging to prevent
26+
// stdio noise from breaking the protocol.
27+
if (host.Services.AsEnumerable().Any(x => x.ServiceType == typeof(IConfigureOptions<McpServerOptions>)))
28+
{
29+
host.Logging.AddConsole(consoleLogOptions =>
30+
{
31+
consoleLogOptions.LogToStandardErrorThreshold = LogLevel.Trace;
32+
});
33+
}
34+
return builder.Services.BuildServiceProvider();
35+
}
36+
}
37+
1138
/// <summary>
1239
/// Invokes the <see cref="Host.CreateApplicationBuilder(string[]?)"/> with additional pre-configured defaults.
1340
/// </summary>
@@ -19,7 +46,12 @@ public static class App
1946
/// </remarks>
2047
/// <param name="args">The command line args.</param>
2148
/// <returns>The initialized <see cref="HostApplicationBuilder"/>.</returns>
22-
public static HostApplicationBuilder CreateBuilder(string[]? args) => Host.CreateApplicationBuilder(args);
49+
public static HostApplicationBuilder CreateBuilder(string[]? args)
50+
{
51+
var host = Host.CreateApplicationBuilder(args);
52+
host.ConfigureContainer(new AppServiceFactory(host));
53+
return host;
54+
}
2355

2456
/// <summary>
2557
/// Builds the host app and registers the provided <paramref name="main"/> function as a hosted service to be

0 commit comments

Comments
 (0)