-
Notifications
You must be signed in to change notification settings - Fork 330
Set default log level to None for MCP in Stdio mode. #3420
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: dev/anushakolan/set-log-level
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -2606,13 +2606,38 @@ public static bool TryStartEngineWithOptions(StartOptions options, FileSystemRun | |
| } | ||
| else | ||
| { | ||
| minimumLogLevel = deserializedRuntimeConfig.GetConfiguredLogLevel(); | ||
| HostMode hostModeType = deserializedRuntimeConfig.IsDevelopmentMode() ? HostMode.Development : HostMode.Production; | ||
| // When --mcp-stdio is used without explicit --LogLevel: | ||
| // 1. Check if config has log-level set - use that (Config has priority 2) | ||
| // 2. Otherwise default to None for clean MCP stdio output | ||
| if (options.McpStdio) | ||
| { | ||
| // Check if config explicitly sets a log level | ||
| if (!deserializedRuntimeConfig.IsLogLevelNull()) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. There is a chance that if we have some LogLevel being set for a specific namespace and this would cause this section to be run even if there is no
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Also, might be easier to include the logic to check if we need to use LogLevel none inside the |
||
| { | ||
| minimumLogLevel = deserializedRuntimeConfig.GetConfiguredLogLevel(); | ||
| _logger.LogInformation("MCP stdio mode: Using config log-level: {minimumLogLevel}.", minimumLogLevel); | ||
| // Pass --LogLevel to Service with special marker to indicate it's from config, not CLI. | ||
| // This allows MCP logging/setLevel to be blocked by config override. | ||
| args.Add("--LogLevel"); | ||
|
Comment on lines
+2620
to
+2621
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. We don't want to use the |
||
| args.Add(minimumLogLevel.ToString()); | ||
| args.Add("--LogLevelFromConfig"); | ||
| } | ||
| else | ||
| { | ||
| _logger.LogInformation("MCP stdio mode: Defaulting to LogLevel.None (no config override)."); | ||
| // Don't add --LogLevel to args - let Service handle the default. | ||
| } | ||
| } | ||
| else | ||
| { | ||
| minimumLogLevel = deserializedRuntimeConfig.GetConfiguredLogLevel(); | ||
| HostMode hostModeType = deserializedRuntimeConfig.IsDevelopmentMode() ? HostMode.Development : HostMode.Production; | ||
|
|
||
| _logger.LogInformation($"Setting default minimum LogLevel: {minimumLogLevel} for {hostModeType} mode.", minimumLogLevel, hostModeType); | ||
| _logger.LogInformation($"Setting default minimum LogLevel: {minimumLogLevel} for {hostModeType} mode.", minimumLogLevel, hostModeType); | ||
|
|
||
| // Don't add --LogLevel arg since user didn't explicitly set it. | ||
| // Service will determine default log level based on config or host mode. | ||
| // Don't add --LogLevel arg since user didn't explicitly set it. | ||
| // Service will determine default log level based on config or host mode. | ||
| } | ||
| } | ||
|
|
||
| // This will add args to disable automatic redirects to https if specified by user | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -71,9 +71,16 @@ public class CustomConsoleLogger : ILogger | |
|
|
||
| /// <summary> | ||
| /// Creates Log message by setting console message color based on LogLevel. | ||
| /// Skips logging when in MCP stdio mode to keep stdout clean for JSON-RPC protocol. | ||
| /// </summary> | ||
| public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter) | ||
| { | ||
| // In MCP stdio mode, suppress all CLI logging to keep stdout clean for JSON-RPC. | ||
| if (Cli.Utils.IsMcpStdioMode) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. We also need to check if we are overriding the LogLevel from the CLI or the config file or else it would skip outputting the logs even when it is not expected. |
||
| { | ||
| return; | ||
| } | ||
|
|
||
| if (!IsEnabled(logLevel) || logLevel < _minimumLogLevel) | ||
| { | ||
| return; | ||
|
|
||
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
|
|
@@ -4,6 +4,7 @@ | |||||
| using System; | ||||||
| using System.CommandLine; | ||||||
| using System.CommandLine.Parsing; | ||||||
| using System.IO; | ||||||
| using System.Runtime.InteropServices; | ||||||
| using System.Text; | ||||||
| using System.Text.RegularExpressions; | ||||||
|
|
@@ -63,6 +64,28 @@ public static bool StartEngine(string[] args, bool runMcpStdio, string? mcpRole) | |||||
| { | ||||||
| try | ||||||
| { | ||||||
| // Initialize log level EARLY, before building the host. | ||||||
| // This ensures logging filters are effective during the entire host build process. | ||||||
| LogLevel initialLogLevel = GetLogLevelFromCommandLineArgs(args, runMcpStdio, out bool isCliOverridden, out bool isConfigOverridden); | ||||||
| LogLevelProvider.SetInitialLogLevel(initialLogLevel, isCliOverridden, isConfigOverridden); | ||||||
|
|
||||||
| // For MCP stdio mode, redirect Console.Out to keep stdout clean for JSON-RPC. | ||||||
| // MCP SDK uses Console.OpenStandardOutput() which gets the real stdout, unaffected by this redirect. | ||||||
| if (runMcpStdio) | ||||||
| { | ||||||
| // When LogLevel.None, redirect to null stream for ZERO output. | ||||||
| // Otherwise redirect to stderr so logs don't pollute JSON-RPC. | ||||||
| if (initialLogLevel == LogLevel.None) | ||||||
| { | ||||||
| Console.SetOut(TextWriter.Null); | ||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Would this change if the LogLevel is intoduced in config file as part of a hot-reload? |
||||||
| Console.SetError(TextWriter.Null); | ||||||
| } | ||||||
| else | ||||||
| { | ||||||
| Console.SetOut(Console.Error); | ||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Why would we want to change the Console to only output errors if the LogLevel is overriden by the CLI or the Config file? Wouldn't that defeat the purpose of allowing the LogLevel to be overriden in the first place? |
||||||
| } | ||||||
| } | ||||||
|
|
||||||
| IHost host = CreateHostBuilder(args, runMcpStdio, mcpRole).Build(); | ||||||
|
|
||||||
| if (runMcpStdio) | ||||||
|
|
@@ -115,13 +138,20 @@ public static IHostBuilder CreateHostBuilder(string[] args, bool runMcpStdio, st | |||||
| }) | ||||||
| .ConfigureLogging(logging => | ||||||
| { | ||||||
| logging.AddFilter("Microsoft", logLevel => LogLevelProvider.ShouldLog(logLevel)); | ||||||
| logging.AddFilter("Microsoft.Hosting.Lifetime", logLevel => LogLevelProvider.ShouldLog(logLevel)); | ||||||
| // Set minimum level at the framework level - this affects all loggers. | ||||||
| // For MCP stdio mode, Console.Out is redirected to stderr in Main(), | ||||||
| // so any logging output goes to stderr and doesn't pollute the JSON-RPC channel. | ||||||
| logging.SetMinimumLevel(LogLevelProvider.CurrentLogLevel); | ||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Just curious, does this set the LogLevel for all the possible namespaces? Since the reason we had it the way we did is because the LogLevel was not being applied to some namespaces. |
||||||
|
|
||||||
| // Add filter for dynamic log level changes (e.g., via MCP logging/setLevel) | ||||||
| logging.AddFilter(logLevel => LogLevelProvider.ShouldLog(logLevel)); | ||||||
| }) | ||||||
| .ConfigureWebHostDefaults(webBuilder => | ||||||
| { | ||||||
| Startup.MinimumLogLevel = GetLogLevelFromCommandLineArgs(args, out Startup.IsLogLevelOverriddenByCli); | ||||||
| LogLevelProvider.SetInitialLogLevel(Startup.MinimumLogLevel, Startup.IsLogLevelOverriddenByCli); | ||||||
| // LogLevelProvider was already initialized in StartEngine before CreateHostBuilder. | ||||||
| // Use the already-set values to avoid re-parsing args. | ||||||
| Startup.MinimumLogLevel = LogLevelProvider.CurrentLogLevel; | ||||||
| Startup.IsLogLevelOverriddenByCli = LogLevelProvider.IsCliOverridden; | ||||||
| ILoggerFactory loggerFactory = GetLoggerFactoryForLogLevel(Startup.MinimumLogLevel, stdio: runMcpStdio); | ||||||
| ILogger<Startup> startupLogger = loggerFactory.CreateLogger<Startup>(); | ||||||
| DisableHttpsRedirectionIfNeeded(args); | ||||||
|
|
@@ -133,19 +163,59 @@ public static IHostBuilder CreateHostBuilder(string[] args, bool runMcpStdio, st | |||||
| /// Using System.CommandLine Parser to parse args and return | ||||||
| /// the correct log level. We save if there is a log level in args through | ||||||
| /// the out param. For log level out of range we throw an exception. | ||||||
| /// When in MCP stdio mode without explicit --LogLevel, defaults to None without CLI override. | ||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. nit:
Suggested change
|
||||||
| /// </summary> | ||||||
| /// <param name="args">array that may contain log level information.</param> | ||||||
| /// <param name="isLogLevelOverridenByCli">sets if log level is found in the args.</param> | ||||||
| /// <param name="runMcpStdio">whether running in MCP stdio mode.</param> | ||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. nit: Capitalize the first letter of all the descriptions for the parameters. |
||||||
| /// <param name="isLogLevelOverridenByCli">sets if log level is found in the args from CLI.</param> | ||||||
| /// <param name="isLogLevelOverridenByConfig">sets if log level came from config file.</param> | ||||||
| /// <returns>Appropriate log level.</returns> | ||||||
| private static LogLevel GetLogLevelFromCommandLineArgs(string[] args, out bool isLogLevelOverridenByCli) | ||||||
| private static LogLevel GetLogLevelFromCommandLineArgs(string[] args, bool runMcpStdio, out bool isLogLevelOverridenByCli, out bool isLogLevelOverridenByConfig) | ||||||
| { | ||||||
| Command cmd = new(name: "start"); | ||||||
| Option<LogLevel> logLevelOption = new(name: "--LogLevel"); | ||||||
| Option<bool> logLevelFromConfigOption = new(name: "--LogLevelFromConfig"); | ||||||
| cmd.AddOption(logLevelOption); | ||||||
| cmd.AddOption(logLevelFromConfigOption); | ||||||
| ParseResult result = GetParseResult(cmd, args); | ||||||
| bool matchedToken = result.Tokens.Count - result.UnmatchedTokens.Count - result.UnparsedTokens.Count > 1; | ||||||
| LogLevel logLevel = matchedToken ? result.GetValueForOption(logLevelOption) : LogLevel.Error; | ||||||
| isLogLevelOverridenByCli = matchedToken; | ||||||
|
|
||||||
| // Check if --LogLevelFromConfig flag is present (indicates config override, not CLI) | ||||||
| bool isFromConfig = result.GetValueForOption(logLevelFromConfigOption); | ||||||
|
|
||||||
| LogLevel logLevel; | ||||||
| if (matchedToken) | ||||||
| { | ||||||
| logLevel = result.GetValueForOption(logLevelOption); | ||||||
|
|
||||||
| if (isFromConfig) | ||||||
| { | ||||||
| // Log level came from config file (passed by CLI with --LogLevelFromConfig marker) | ||||||
| isLogLevelOverridenByCli = false; | ||||||
| isLogLevelOverridenByConfig = true; | ||||||
| } | ||||||
| else | ||||||
| { | ||||||
| // User explicitly set --LogLevel via CLI (highest priority) | ||||||
| isLogLevelOverridenByCli = true; | ||||||
| isLogLevelOverridenByConfig = false; | ||||||
| } | ||||||
| } | ||||||
| else if (runMcpStdio) | ||||||
| { | ||||||
| // MCP stdio mode without explicit --LogLevel: default to None to keep stdout clean. | ||||||
| // This is NOT a CLI or config override, so MCP logging/setLevel can still change it. | ||||||
| logLevel = LogLevel.None; | ||||||
| isLogLevelOverridenByCli = false; | ||||||
| isLogLevelOverridenByConfig = false; | ||||||
| } | ||||||
| else | ||||||
| { | ||||||
| // Normal mode without explicit --LogLevel | ||||||
| logLevel = LogLevel.Error; | ||||||
| isLogLevelOverridenByCli = false; | ||||||
| isLogLevelOverridenByConfig = false; | ||||||
| } | ||||||
|
|
||||||
| if (logLevel is > LogLevel.None or < LogLevel.Trace) | ||||||
| { | ||||||
|
|
||||||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Should also add a comment that says that if we are not using --mcp-stdio it will default to Error for Production mode and Debug for Development mode