Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 30 additions & 5 deletions src/Cli/ConfigGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Copy link
Copy Markdown
Contributor

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

if (options.McpStdio)
{
// Check if config explicitly sets a log level
if (!deserializedRuntimeConfig.IsLogLevelNull())
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The 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 default value being used. You would need to check specifically if we are using the default value inside the config file.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The 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 GetConfiguredLogLevel function, since the way it works is that it first checks if we use the config file, and then defaults to the other LogLevels depending on the mode dab is started in.

{
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
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We don't want to use the --LogLevel flag here, it is causing a bug that I have a PR for #3426

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
Expand Down
7 changes: 7 additions & 0 deletions src/Cli/CustomLoggerProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The 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;
Expand Down
3 changes: 3 additions & 0 deletions src/Cli/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ public static int Main(string[] args)
// Load environment variables from .env file if present.
DotNetEnv.Env.Load();

// Check if MCP stdio mode is requested - suppress CLI logging to keep stdout clean for JSON-RPC.
Utils.IsMcpStdioMode = args.Any(a => string.Equals(a, "--mcp-stdio", StringComparison.OrdinalIgnoreCase));

// Logger setup and configuration
ILoggerFactory loggerFactory = Utils.LoggerFactoryForCli;
ILogger<Program> cliLogger = loggerFactory.CreateLogger<Program>();
Expand Down
5 changes: 5 additions & 0 deletions src/Cli/Utils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,11 @@ public class Utils
public const string WILDCARD = "*";
public static readonly string SEPARATOR = ":";

/// <summary>
/// When true, CLI logging to stdout is suppressed to keep the MCP stdio channel clean.
/// </summary>
public static bool IsMcpStdioMode { get; set; }

#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
private static ILogger<Utils> _logger;
#pragma warning restore CS8618
Expand Down
86 changes: 78 additions & 8 deletions src/Service/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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);
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The 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);
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The 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)
Expand Down Expand Up @@ -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);
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The 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);
Expand All @@ -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.
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit:

Suggested change
/// When in MCP stdio mode without explicit --LogLevel, defaults to None without CLI override.
/// When in MCP stdio mode without explicit --LogLevel, defaults to None without CLI or Config override.

/// </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>
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The 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)
{
Expand Down