diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 26e885b2..fbcf4b54 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -67,7 +67,8 @@ - Be careful with state transitions in the shell. Some states share the same `CosmosClient`, so disposing the old state during navigation can break the new state. - Be careful with iterator lifetimes when returning `IAsyncEnumerable`; do not dispose iterators before enumeration completes. -- MCP in this repo is HTTP-only. The `--mcp` option optionally accepts a port and defaults to `6128`. +- MCP supports two transports. `--mcp [port]` starts the HTTP server (default port `6128`). `--mcp-stdio` runs a headless server where stdin/stdout carry only MCP JSON-RPC and diagnostics go to stderr; it cannot be combined with `--mcp`, `--lsp`, `--stdio`, `-c`, `-k`, or `--clear-history`. +- In MCP stdio mode, nothing may write to the protocol stdout. Route user-facing output through `ShellOutput` (enforced by analyzer rule CZ0003), and never read console input. ## Preferred Change Pattern diff --git a/CosmosDBShell.Analyzer/DirectConsoleOutputAnalyzer.cs b/CosmosDBShell.Analyzer/DirectConsoleOutputAnalyzer.cs index c7729c93..a8b92b59 100644 --- a/CosmosDBShell.Analyzer/DirectConsoleOutputAnalyzer.cs +++ b/CosmosDBShell.Analyzer/DirectConsoleOutputAnalyzer.cs @@ -12,8 +12,8 @@ namespace CosmosShell.Analyzer { /// /// Requires user-facing console output to go through ShellOutput, which applies the - /// quiet and machine-mode presentation policies. Direct writes bypass those - /// policies and can corrupt structured stdout. + /// quiet, machine-mode, and MCP stdio presentation policies. Direct writes bypass those + /// policies and can corrupt structured stdout or the MCP protocol stream. /// [DiagnosticAnalyzer(LanguageNames.CSharp)] public class DirectConsoleOutputAnalyzer : DiagnosticAnalyzer @@ -30,7 +30,7 @@ public class DirectConsoleOutputAnalyzer : DiagnosticAnalyzer Category, DiagnosticSeverity.Error, isEnabledByDefault: true, - description: "User-facing output must go through ShellOutput so --quiet and machine mode are honored."); + description: "User-facing output must go through ShellOutput so --quiet, machine mode, and MCP stdio are honored."); public override ImmutableArray SupportedDiagnostics { get { return ImmutableArray.Create(Rule); } } diff --git a/CosmosDBShell.Tests/CommandTests/BucketCommandTests.cs b/CosmosDBShell.Tests/CommandTests/BucketCommandTests.cs index aa1d7c02..8fdfd00c 100644 --- a/CosmosDBShell.Tests/CommandTests/BucketCommandTests.cs +++ b/CosmosDBShell.Tests/CommandTests/BucketCommandTests.cs @@ -20,6 +20,35 @@ namespace CosmosShell.Tests.CommandTests; [Collection(ConsoleOutputTestCollection.Name)] public class BucketCommandTests { + [Theory] + [InlineData(null, 4)] + [InlineData("3", 3)] + [InlineData("0", null)] + public async Task ClientSelection_ReturnsStructuredResultInEveryMode(string? action, int? expected) + { + foreach (var options in new[] + { + new Program.CosmosShellOptions(), + new Program.CosmosShellOptions { Quiet = true }, + new Program.CosmosShellOptions { Output = "json" }, + new Program.CosmosShellOptions { McpStdio = true }, + }) + { + var client = CreateTestClient(); + client.ClientOptions.ThroughputBucket = 4; + using var shell = ShellInterpreter.CreateInstance(); + shell.Options = options; + shell.State = new DatabaseState("TestDatabase", client); + var command = new BucketCommand { Action = action }; + + var state = await command.ExecuteAsync(shell, new CommandState(), "bucket", TestContext.Current.CancellationToken); + + var result = Assert.IsType(state.Result).Value.GetProperty("clientBucket"); + Assert.Equal(expected, result.ValueKind == System.Text.Json.JsonValueKind.Null ? (int?)null : result.GetInt32()); + Assert.NotNull(state.RenderUser); + } + } + [Theory] [InlineData(null, false)] [InlineData("3", false)] @@ -173,9 +202,10 @@ public async Task ExecuteAsync_InDatabase_InvalidValue_ThrowsCommandException() shell.State = new DatabaseState("TestDatabase", client); var command = new BucketCommand { Action = "99" }; - await Assert.ThrowsAsync( + var error = await Assert.ThrowsAsync( () => command.ExecuteAsync(shell, new CommandState(), "bucket 99", CancellationToken.None)); + Assert.Equal(ShellExitCode.UsageError, ShellExitCode.FromException(error)); Assert.Null(client.ClientOptions.ThroughputBucket); } diff --git a/CosmosDBShell.Tests/CommandTests/ConnectCommandTests.cs b/CosmosDBShell.Tests/CommandTests/ConnectCommandTests.cs index f12ccddf..7aa5158b 100644 --- a/CosmosDBShell.Tests/CommandTests/ConnectCommandTests.cs +++ b/CosmosDBShell.Tests/CommandTests/ConnectCommandTests.cs @@ -36,6 +36,83 @@ public void CreateClientOptions_Emulator_UsesShortRequestTimeout() Assert.Equal(TimeSpan.FromSeconds(5), options.RequestTimeout); } + [Theory] + [InlineData(false, true)] + [InlineData(true, false)] + public void AllowsInteractiveBrowser_IsDisabledOnlyForMcpStdio(bool mcpStdio, bool expected) + { + Assert.Equal(expected, ShellInterpreter.AllowsInteractiveBrowser(mcpStdio)); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void CreateDefaultCredentialOptions_ExcludesBrowserWhenNotAllowed(bool allowInteractiveBrowser) + { + var authority = new Uri("https://login.example.test/"); + + var options = ShellInterpreter.CreateDefaultCredentialOptions(authority, allowInteractiveBrowser); + + Assert.Equal(!allowInteractiveBrowser, options.ExcludeInteractiveBrowserCredential); + Assert.Equal(!allowInteractiveBrowser, options.ExcludeBrokerCredential); + Assert.Equal(authority, options.AuthorityHost); + Assert.False(options.ExcludeAzureCliCredential); + Assert.False(options.ExcludeManagedIdentityCredential); + } + + [Fact] + public void IsMcpStdio_FollowsOptions() + { + using var shell = ShellInterpreter.CreateInstance(); + Assert.False(shell.IsMcpStdio); + + shell.Options = new Program.CosmosShellOptions { McpStdio = true }; + Assert.True(shell.IsMcpStdio); + } + + [Fact] + public async Task ConnectAsync_McpStdioWithTenant_UsesDeviceCodeWithoutBrowser() + { + var shell = ShellInterpreter.Instance; + var originalAccountKey = Environment.GetEnvironmentVariable("COSMOSDB_SHELL_ACCOUNT_KEY"); + var originalToken = Environment.GetEnvironmentVariable("COSMOSDB_SHELL_TOKEN"); + var originalOptions = shell.Options; + var originalError = Console.Error; + var originalOut = Console.Out; + using var error = new StringWriter(); + using var output = new StringWriter(); + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken); + try + { + Environment.SetEnvironmentVariable("COSMOSDB_SHELL_ACCOUNT_KEY", null); + Environment.SetEnvironmentVariable("COSMOSDB_SHELL_TOKEN", null); + shell.Options = new Program.CosmosShellOptions { McpStdio = true }; + Console.SetError(error); + Console.SetOut(output); + timeout.CancelAfter(TimeSpan.FromSeconds(2)); + + // Device code polling cannot complete here: the attempt ends by cancellation or, + // without network access, by an authentication failure. Neither may open a browser. + await Assert.ThrowsAnyAsync(() => shell.ConnectAsync( + "https://stdio-auth-test.documents.azure.com:443/", + tenantId: "00000000-0000-0000-0000-000000000000", + token: timeout.Token)); + } + finally + { + Environment.SetEnvironmentVariable("COSMOSDB_SHELL_ACCOUNT_KEY", originalAccountKey); + Environment.SetEnvironmentVariable("COSMOSDB_SHELL_TOKEN", originalToken); + Console.SetError(originalError); + Console.SetOut(originalOut); + shell.Options = originalOptions; + } + + var stderr = error.ToString(); + Assert.Contains(MessageService.GetString("shell-connect-devicecode-stdio"), stderr, StringComparison.Ordinal); + Assert.DoesNotContain(MessageService.GetString("shell-connect-browser-auth"), stderr + output, StringComparison.Ordinal); + Assert.IsNotType(shell.State); + } + [Fact] public void LocalEmulatorInactivityTimeout_IsInitializedOnSharedAndNewInstances() { diff --git a/CosmosDBShell.Tests/CommandTests/QueryCommandTests.cs b/CosmosDBShell.Tests/CommandTests/QueryCommandTests.cs index 0be198bd..16634d99 100644 --- a/CosmosDBShell.Tests/CommandTests/QueryCommandTests.cs +++ b/CosmosDBShell.Tests/CommandTests/QueryCommandTests.cs @@ -17,6 +17,20 @@ namespace CosmosShell.Tests.CommandTests; [Collection(CosmosShell.Tests.Shell.ThemeStateTestCollection.Name)] public class QueryCommandTests { + [Theory] + [InlineData(-1)] + [InlineData(6)] + public async Task ExecuteAsync_InvalidBucket_ReportsUsageBeforeConnecting(int bucket) + { + using var shell = ShellInterpreter.CreateInstance(); + var command = new QueryCommand { Bucket = bucket }; + + var error = await Assert.ThrowsAsync(() => + command.ExecuteAsync(shell, new CommandState(), "query", TestContext.Current.CancellationToken)); + + Assert.Equal(ShellExitCode.UsageError, ShellExitCode.FromException(error)); + } + private class TestServerSideMetrics : ServerSideMetrics { public override long RetrievedDocumentCount { get; } = 0; diff --git a/CosmosDBShell.Tests/Integration/McpStdioProcessTests.cs b/CosmosDBShell.Tests/Integration/McpStdioProcessTests.cs new file mode 100644 index 00000000..145e3f3a --- /dev/null +++ b/CosmosDBShell.Tests/Integration/McpStdioProcessTests.cs @@ -0,0 +1,630 @@ +// ------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +// ------------------------------------------------------------ + +namespace CosmosShell.Tests.Integration; + +using System.Diagnostics; +using System.Net; +using System.Net.Sockets; +using System.Text; +using System.Text.Json; +using System.Text.Json.Nodes; +using System.Threading.Channels; +using ModelContextProtocol.Protocol; + +public class McpStdioProcessTests +{ + [Fact] + public async Task StdioQuiet_PreservesWarningsAndProtocolResults() + { + await using var server = new ServerProcess(["--quiet", "--theme", "STDIO_WARNING_THEME"]); + await server.InitializeAsync("2025-11-25"); + var echo = await server.CallToolAsync(2, "echo", new { messages = new[] { "QUIET_STDIO_RESULT" } }); + Assert.Equal("QUIET_STDIO_RESULT", echo.GetProperty("result").GetProperty("structuredContent").GetProperty("result").GetString()); + var error = await server.CallToolAsync(3, "help", new { command = "QUIET_MISSING_COMMAND" }); + Assert.True(error.GetProperty("result").GetProperty("isError").GetBoolean()); + await server.CompleteAsync(); + Assert.Equal(0, server.ExitCode); + Assert.Contains("STDIO_WARNING_THEME", server.StdErr); + Assert.DoesNotContain("QUIET_STDIO_RESULT", server.StdErr); + Assert.DoesNotContain("\u001b", server.StdErr, StringComparison.Ordinal); + } + + [Theory] + [InlineData("--help", "USAGE:")] + [InlineData("--version", "CosmosDBShell")] + public async Task Stdio_ExplicitHelpAndVersion_UseStderr(string argument, string expected) + { + await using var server = new ServerProcess([argument]); + await server.CompleteAsync(); + Assert.Equal(0, server.ExitCode); + Assert.Equal(0, server.MessageCount); + Assert.Contains(expected, server.StdErr); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task Stdio_DoesNotCreateOrModifyHistory(bool seedHistory) + { + await using var server = new ServerProcess(seedHistory: seedHistory); + var historyFile = Path.Join(server.ConfigDirectory, "cmd_history"); + var original = seedHistory ? Encoding.UTF8.GetBytes(ServerProcess.HistorySeed) : null; + await server.InitializeAsync("2025-11-25"); + await server.CallToolAsync(2, "echo", new { messages = new[] { "NO_HISTORY_MARKER" } }); + await server.CompleteAsync(); + Assert.Equal(0, server.ExitCode); + Assert.False(File.Exists(historyFile + ".lock")); + if (original is not null) + { + Assert.Equal(original, await File.ReadAllBytesAsync(historyFile, TestContext.Current.CancellationToken)); + } + else + { + Assert.False(File.Exists(historyFile)); + } + } + + [Theory] + [InlineData("2025-11-25")] + [InlineData("2026-07-28")] + public async Task Stdio_ToolsResourcesAndDiagnostics_KeepStdoutProtocolOnly(string version) + { + await using var server = new ServerProcess(); + await server.InitializeAsync(version); + + var tools = await server.RequestAsync(2, "tools/list", new { }); + var toolNames = tools.GetProperty("result").GetProperty("tools").EnumerateArray() + .Select(tool => tool.GetProperty("name").GetString()) + .ToList(); + Assert.Contains("echo", toolNames); + Assert.Contains("help", toolNames); + Assert.DoesNotContain("jq", toolNames); + Assert.DoesNotContain("theme", toolNames); + + var echo = await server.CallToolAsync(3, "echo", new { messages = new[] { "STDIO_RESULT" } }); + Assert.Equal("STDIO_RESULT", echo.GetProperty("result").GetProperty("structuredContent").GetProperty("result").GetString()); + + var helpList = await server.CallToolAsync(4, "help", new { }); + var helpCommands = helpList.GetProperty("result").GetProperty("structuredContent").GetProperty("result") + .GetProperty("commands").EnumerateArray() + .Select(command => command.GetProperty("command").GetString()) + .ToList(); + Assert.Contains("echo", helpCommands); + Assert.DoesNotContain("jq", helpCommands); + Assert.DoesNotContain("theme", helpCommands); + foreach (var name in new[] { "exit", "edit", "watch", "welcome", "sproc", "udf", "trigger" }) + { + Assert.DoesNotContain(name, toolNames); + Assert.DoesNotContain(name, helpCommands); + } + + foreach (var name in new[] { "delete", "rm", "rmdb", "rmcon" }) + { + Assert.Contains(name, toolNames); + Assert.Contains(name, helpCommands); + } + + Assert.Equal(toolNames.Order(), helpCommands.Order()); + + var help = await server.CallToolAsync(5, "help", new { command = "STDIO_MISSING_COMMAND" }); + Assert.True(help.GetProperty("result").GetProperty("isError").GetBoolean()); + + var unknown = await server.CallToolAsync(6, "STDIO_UNKNOWN_TOOL", new { }); + Assert.True(unknown.GetProperty("result").GetProperty("isError").GetBoolean()); + + var resource = await server.RequestAsync(7, "resources/read", new { uri = "cosmos://shell/current-location" }); + var content = resource.GetProperty("result").GetProperty("contents")[0].GetProperty("text").GetString()!; + using var location = JsonDocument.Parse(content); + Assert.Equal(JsonValueKind.Null, location.RootElement.GetProperty("currentLocation").ValueKind); + + var status = await server.CallToolAsync(8, "version", new { }); + var statusResult = status.GetProperty("result").GetProperty("structuredContent").GetProperty("result"); + Assert.True(statusResult.GetProperty("mcpEnabled").GetBoolean()); + Assert.Equal(JsonValueKind.Null, statusResult.GetProperty("mcpPort").ValueKind); + + await server.CompleteAsync(); + Assert.Equal(0, server.ExitCode); + Assert.Contains("STDIO_MISSING_COMMAND", server.StdErr); + Assert.DoesNotContain("STDIO_RESULT", server.StdErr); + } + + [Theory] + [InlineData("2025-06-18")] + [InlineData("2025-11-25")] + public async Task Stdio_LocationSubscription_RoundTripsAndEndsOnEof(string version) + { + await using var server = new ServerProcess(); + await server.InitializeAsync(version); + var subscription = await server.RequestAsync(2, "resources/subscribe", new { uri = "cosmos://shell/current-location" }); + Assert.True(subscription.TryGetProperty("result", out _), subscription.ToString()); + var invalid = await server.RequestAsync(3, "resources/subscribe", new { uri = "cosmos://docs/scripting" }); + Assert.Equal(-32602, invalid.GetProperty("error").GetProperty("code").GetInt32()); + var unsubscribe = await server.RequestAsync(4, "resources/unsubscribe", new { uri = "cosmos://shell/current-location" }); + Assert.True(unsubscribe.TryGetProperty("result", out _), unsubscribe.ToString()); + var resubscribe = await server.RequestAsync(5, "resources/subscribe", new { uri = "cosmos://shell/current-location" }); + Assert.True(resubscribe.TryGetProperty("result", out _), resubscribe.ToString()); + await server.CompleteAsync(); + Assert.Equal(0, server.ExitCode); + } + + [Fact] + public async Task Stdio_LatestSubscriptionListen_AcknowledgesAndEndsOnEof() + { + await using var server = new ServerProcess(); + await server.InitializeAsync("2026-07-28"); + await server.WriteRequestAsync(2, "subscriptions/listen", new + { + notifications = new { resourceSubscriptions = new[] { "cosmos://shell/current-location" } }, + }); + var acknowledgement = await server.ReadMessageAsync(); + Assert.Equal(NotificationMethods.SubscriptionsAcknowledgedNotification, acknowledgement.GetProperty("method").GetString()); + Assert.Equal("cosmos://shell/current-location", + acknowledgement.GetProperty("params").GetProperty("notifications").GetProperty("resourceSubscriptions")[0].GetString()); + await server.CompleteAsync(); + Assert.Equal(0, server.ExitCode); + } + + [Theory] + [InlineData("decline")] + [InlineData("cancel")] + [InlineData("accept")] + public async Task Stdio_DestructiveConfirmation_UsesProtocolEvenWithForce(string action) + { + await using var server = new ServerProcess(); + await server.InitializeAsync("2025-11-25", new { elicitation = new { form = new { } } }); + await server.WriteAsync(new + { + jsonrpc = "2.0", + id = 2, + method = "tools/call", + @params = new { name = "rmdb", arguments = new { name = "StdioConfirmationDb", force = true } }, + }); + var prompt = await server.ReadMessageAsync(); + Assert.Equal("elicitation/create", prompt.GetProperty("method").GetString()); + Assert.Contains("StdioConfirmationDb", prompt.GetProperty("params").GetProperty("message").GetString()); + await server.WriteAsync(new + { + jsonrpc = "2.0", + id = prompt.GetProperty("id"), + result = new { action, content = new { } }, + }); + var response = await server.ReadResponseAsync(2); + Assert.True(response.GetProperty("result").GetProperty("isError").GetBoolean()); + var error = response.GetProperty("result").GetProperty("structuredContent").GetProperty("error").GetString(); + if (action == "accept") + { + Assert.DoesNotContain("was not approved", error); + Assert.DoesNotContain("does not support", error); + } + else + { + Assert.Contains("was not approved", error); + } + + await server.CompleteAsync(); + Assert.Equal(0, server.ExitCode); + } + + [Fact] + public async Task Stdio_ClientWithoutElicitation_RefusesDestructiveTool() + { + await using var server = new ServerProcess(); + await server.InitializeAsync("2025-11-25"); + var response = await server.CallToolAsync(2, "rmdb", new { name = "StdioConfirmationDb", force = true }); + Assert.True(response.GetProperty("result").GetProperty("isError").GetBoolean()); + Assert.Contains("does not support confirmation", response.GetProperty("result").GetProperty("structuredContent").GetProperty("error").GetString()); + await server.CompleteAsync(); + Assert.Equal(0, server.ExitCode); + } + + [Fact] + public async Task Stdio_EofWhileAwaitingConfirmation_ExitsCleanly() + { + await using var server = new ServerProcess(); + await server.InitializeAsync("2025-11-25", new { elicitation = new { form = new { } } }); + await server.WriteRequestAsync(2, "tools/call", new + { + name = "rmdb", + arguments = new { name = "StdioConfirmationDb" }, + }); + var prompt = await server.ReadMessageAsync(); + Assert.Equal("elicitation/create", prompt.GetProperty("method").GetString()); + await server.CompleteAsync(); + Assert.Equal(0, server.ExitCode); + } + + [Fact] + public async Task Stdio_CancelPendingConfirmation_RemainsResponsive() + { + await using var server = new ServerProcess(); + await server.InitializeAsync("2025-11-25", new { elicitation = new { form = new { } } }); + await server.WriteRequestAsync(2, "tools/call", new + { + name = "rmdb", + arguments = new { name = "CancelledStdioDb" }, + }); + var prompt = await server.ReadMessageAsync(); + Assert.Equal("elicitation/create", prompt.GetProperty("method").GetString()); + await server.WriteAsync(new + { + jsonrpc = "2.0", + method = "notifications/cancelled", + @params = new { requestId = 2, reason = "stdio cancellation test" }, + }); + await server.WriteRequestAsync(3, "tools/call", new + { + name = "echo", + arguments = new { messages = new[] { "AFTER_STDIO_CANCELLATION" } }, + }); + var response = await server.ReadResponseAsync(3, cancelledIds: [2]); + Assert.Equal("AFTER_STDIO_CANCELLATION", + response.GetProperty("result").GetProperty("structuredContent").GetProperty("result").GetString()); + await server.CompleteAsync(); + Assert.Equal(0, server.ExitCode); + Assert.DoesNotContain("An exception occurred", server.StdErr); + } + + [Fact] + public async Task Stdio_EofDuringStartupConnection_ExitsWithoutWaitingForNetwork() + { + using var listener = new TcpListener(IPAddress.Loopback, 0); + listener.Start(); + var endpoint = (IPEndPoint)listener.LocalEndpoint; + await using var server = new ServerProcess([ + "--connect", + $"AccountEndpoint=https://127.0.0.1:{endpoint.Port}/;AccountKey=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=;", + ]); + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken); + timeout.CancelAfter(TimeSpan.FromSeconds(10)); + using var connection = await listener.AcceptTcpClientAsync(timeout.Token); + await server.CompleteAsync().WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + Assert.Equal(0, server.ExitCode); + Assert.Equal(0, server.MessageCount); + Assert.DoesNotContain("timed out", server.StdErr, StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public async Task Stdio_StartupFailure_ExitsWithStdinStillOpen() + { + await using var server = new ServerProcess(["--connect", "not-an-endpoint"]); + await server.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + Assert.Equal(2, server.ExitCode); + Assert.Equal(0, server.MessageCount); + Assert.NotEmpty(server.StdErr); + } + + [Fact] + public async Task Stdio_CancelRunningAndQueuedTools_ReleasesShell() + { + using var listener = new TcpListener(IPAddress.Loopback, 0); + listener.Start(); + var endpoint = (IPEndPoint)listener.LocalEndpoint; + await using var server = new ServerProcess(); + await server.InitializeAsync("2025-11-25"); + await server.WriteRequestAsync(2, "tools/call", new + { + name = "connect", + arguments = new + { + connectionString = $"AccountEndpoint=https://127.0.0.1:{endpoint.Port}/;AccountKey=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=;", + }, + }); + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken); + timeout.CancelAfter(TimeSpan.FromSeconds(10)); + using var connection = await listener.AcceptTcpClientAsync(timeout.Token); + await server.WriteRequestAsync(3, "tools/call", new + { + name = "echo", + arguments = new { messages = new[] { "CANCELLED_QUEUED_RESULT" } }, + }); + foreach (var requestId in new[] { 3, 2 }) + { + await server.WriteAsync(new + { + jsonrpc = "2.0", + method = "notifications/cancelled", + @params = new { requestId, reason = "stdio cancellation test" }, + }); + } + + await server.WriteRequestAsync(4, "tools/call", new + { + name = "echo", + arguments = new { messages = new[] { "AFTER_QUEUED_CANCELLATION" } }, + }); + var response = await server.ReadResponseAsync(4, cancelledIds: [2, 3]); + Assert.Equal("AFTER_QUEUED_CANCELLATION", + response.GetProperty("result").GetProperty("structuredContent").GetProperty("result").GetString()); + await server.CompleteAsync(); + Assert.Equal(0, server.ExitCode); + Assert.DoesNotContain("An exception occurred", server.StdErr); + } + + [Theory] + [InlineData("theme", "show")] + [InlineData("theme", "edit")] + [InlineData("jq", null)] + [InlineData("exit", null)] + [InlineData("edit", null)] + [InlineData("watch", null)] + [InlineData("welcome", null)] + [InlineData("sproc", null)] + [InlineData("udf", null)] + [InlineData("trigger", null)] + public async Task Stdio_RemovedCommands_AreUnknownToolsAndHelp(string tool, string? action) + { + await using var server = new ServerProcess(); + await server.InitializeAsync("2025-11-25"); + var arguments = action is null ? new Dictionary() : new Dictionary { ["action"] = action }; + var response = await server.CallToolAsync(2, tool, arguments); + Assert.True(response.GetProperty("result").GetProperty("isError").GetBoolean()); + Assert.Contains("Could not find command", response.GetProperty("result").GetProperty("structuredContent").GetProperty("error").GetString()); + var help = await server.CallToolAsync(3, "help", new { command = tool }); + Assert.True(help.GetProperty("result").GetProperty("isError").GetBoolean()); + await server.CompleteAsync(); + Assert.Equal(0, server.ExitCode); + } + + [Theory] + [InlineData("--mcp")] + [InlineData("--lsp")] + [InlineData("--stdio")] + [InlineData("--clear-history")] + [InlineData("-c")] + [InlineData("-k")] + public async Task Stdio_ConflictingModes_FailOnStderrWithEmptyStdout(string option) + { + await using var server = new ServerProcess(option is "-c" or "-k" ? [option, "echo SHOULD_NOT_RUN"] : [option]); + await server.CompleteAsync(); + Assert.Equal(2, server.ExitCode); + Assert.Equal(0, server.MessageCount); + Assert.Contains("cannot be combined", server.StdErr); + Assert.DoesNotContain("SHOULD_NOT_RUN", server.StdErr); + } + + [Theory] + [InlineData("--help", null, 0)] + [InlineData("--version", null, 0)] + [InlineData("--unknown-option", null, 2)] + [InlineData("--container", "orphan", 2)] + [InlineData("--connect", "not-an-endpoint", 2)] + [InlineData("--mcp-stdio=false", null, 2)] + [InlineData("--mcp-stdio=invalid", null, 2)] + [InlineData("--quiet=invalid", null, 2)] + [InlineData("--lsp=true", null, 2)] + [InlineData("--stdio=true", null, 2)] + public async Task Stdio_StartupOutput_IsStderrOnly(string option, string? value, int expectedExitCode) + { + await using var server = new ServerProcess(value is null ? [option] : [option, value]); + await server.CompleteAsync(); + Assert.Equal(expectedExitCode, server.ExitCode); + Assert.Equal(0, server.MessageCount); + Assert.NotEmpty(server.StdErr); + } + + [Fact] + public async Task Stdio_EofWithoutInitialization_ExitsCleanly() + { + await using var server = new ServerProcess(); + await server.CompleteAsync(); + Assert.Equal(0, server.ExitCode); + Assert.Equal(0, server.MessageCount); + } + + private sealed class ServerProcess : IAsyncDisposable + { + internal const string HistorySeed = "echo EXISTING_HISTORY\nconnect 'AccountEndpoint=https://example.test/;AccountKey=example-history-key;'\n"; + + private readonly string configDirectory = Path.Join(Path.GetTempPath(), $"cosmosshell-stdio-{Guid.NewGuid():N}"); + private readonly CancellationTokenSource timeout = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken); + private readonly Channel messages = Channel.CreateUnbounded(); + private readonly Process process; + private readonly Task outputTask; + private readonly Task errorTask; + + private JsonObject? requestMeta; + + public ServerProcess(string[]? extraArguments = null, bool seedHistory = false) + { + if (seedHistory) + { + Directory.CreateDirectory(this.configDirectory); + File.WriteAllText(Path.Join(this.configDirectory, "cmd_history"), HistorySeed); + } + + this.timeout.CancelAfter(TimeSpan.FromSeconds(30)); + var shellDll = Path.Join(AppContext.BaseDirectory, "CosmosDBShell.dll"); + Assert.True(File.Exists(shellDll), $"Missing shell executable: {shellDll}"); + var startInfo = new ProcessStartInfo + { + FileName = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? "dotnet", + WorkingDirectory = AppContext.BaseDirectory, + UseShellExecute = false, + RedirectStandardInput = true, + RedirectStandardOutput = true, + RedirectStandardError = true, + StandardInputEncoding = new UTF8Encoding(false), + StandardOutputEncoding = Encoding.UTF8, + StandardErrorEncoding = Encoding.UTF8, + CreateNoWindow = true, + }; + startInfo.ArgumentList.Add(shellDll); + startInfo.ArgumentList.Add("--mcp-stdio"); + foreach (var argument in extraArguments ?? []) + { + startInfo.ArgumentList.Add(argument); + } + + startInfo.Environment["COSMOSDB_SHELL_CONFIG_DIR"] = this.configDirectory; + startInfo.Environment.Remove("COSMOSDB_SHELL_ACCOUNT_KEY"); + startInfo.Environment.Remove("COSMOSDB_SHELL_TOKEN"); + startInfo.Environment.Remove("COSMOSDB_SHELL_FORMAT"); + this.process = Process.Start(startInfo) ?? throw new InvalidOperationException("Could not start stdio server."); + this.outputTask = this.CaptureOutputAsync(); + this.errorTask = this.process.StandardError.ReadToEndAsync(); + } + + public List Notifications { get; } = []; + + public string ConfigDirectory => this.configDirectory; + + public int MessageCount { get; private set; } + + public int ExitCode => this.process.ExitCode; + + public string StdErr { get; private set; } = string.Empty; + + public async Task InitializeAsync(string version, object? capabilities = null) + { + if (version == "2026-07-28") + { + this.requestMeta = new JsonObject + { + ["io.modelcontextprotocol/protocolVersion"] = version, + ["io.modelcontextprotocol/clientCapabilities"] = JsonSerializer.SerializeToNode(capabilities ?? new { }), + ["io.modelcontextprotocol/clientInfo"] = new JsonObject { ["name"] = "stdio-process-test", ["version"] = "1.0" }, + }; + var discover = await this.RequestAsync(1, "server/discover", new { }); + Assert.Contains(discover.GetProperty("result").GetProperty("supportedVersions").EnumerateArray(), + supported => supported.GetString() == version); + return; + } + + var response = await this.RequestAsync(1, "initialize", new + { + protocolVersion = version, + capabilities = capabilities ?? new { }, + clientInfo = new { name = "stdio-process-test", version = "1.0" }, + }); + Assert.Equal(version, response.GetProperty("result").GetProperty("protocolVersion").GetString()); + await this.WriteAsync(new { jsonrpc = "2.0", method = "notifications/initialized" }); + } + + public Task CallToolAsync(int id, string name, object arguments) + => this.RequestAsync(id, "tools/call", new { name, arguments }); + + public async Task RequestAsync(int id, string method, object parameters) + { + await this.WriteRequestAsync(id, method, parameters); + return await this.ReadResponseAsync(id); + } + + public async Task WriteRequestAsync(int id, string method, object parameters) + { + var requestParameters = JsonSerializer.SerializeToNode(parameters)!.AsObject(); + if (this.requestMeta is not null) + { + requestParameters["_meta"] = this.requestMeta.DeepClone(); + } + + await this.WriteAsync(new { jsonrpc = "2.0", id, method, @params = requestParameters }); + } + + public async Task WriteAsync(object message) + { + await this.process.StandardInput.WriteLineAsync(JsonSerializer.Serialize(message).AsMemory(), this.timeout.Token); + await this.process.StandardInput.FlushAsync(this.timeout.Token); + } + + public async Task ReadMessageAsync() + { + var message = await this.messages.Reader.ReadAsync(this.timeout.Token); + if (message.TryGetProperty("method", out _) && !message.TryGetProperty("id", out _)) + { + this.Notifications.Add(message); + } + + return message; + } + + public async Task ReadResponseAsync(int id, int[]? cancelledIds = null) + { + while (true) + { + var message = await this.ReadMessageAsync(); + if (message.TryGetProperty("id", out var responseId)) + { + Assert.False(message.TryGetProperty("method", out _), $"Unexpected server request: {message}"); + if (cancelledIds?.Contains(responseId.GetInt32()) == true) + { + Assert.True(message.TryGetProperty("error", out _) + || message.GetProperty("result").GetProperty("isError").GetBoolean(), + $"Cancelled request returned success: {message}"); + continue; + } + + Assert.Equal(id, responseId.GetInt32()); + return message; + } + } + } + +#pragma warning disable VSTHRD003 // Both stream-draining tasks are started by this helper and complete when the child exits. + public async Task CompleteAsync() + { + this.process.StandardInput.Close(); + await this.WaitForExitAsync(); + } + + public async Task WaitForExitAsync() + { + await this.process.WaitForExitAsync(this.timeout.Token); + await this.outputTask; + this.StdErr = await this.errorTask; + } + + public async ValueTask DisposeAsync() + { + try + { + if (!this.process.HasExited) + { + this.process.Kill(entireProcessTree: true); + await this.process.WaitForExitAsync(TestContext.Current.CancellationToken); + } + + await this.outputTask; + await this.errorTask; + } + finally + { + this.process.Dispose(); + this.timeout.Dispose(); + if (Directory.Exists(this.configDirectory)) + { + Directory.Delete(this.configDirectory, recursive: true); + } + } +#pragma warning restore VSTHRD003 + } + + private async Task CaptureOutputAsync() + { + Exception? failure = null; + try + { + while (await this.process.StandardOutput.ReadLineAsync() is { } line) + { + using var document = JsonDocument.Parse(line); + var message = document.RootElement.Clone(); + Assert.Equal("2.0", message.GetProperty("jsonrpc").GetString()); + Assert.True(message.TryGetProperty("method", out _) || message.TryGetProperty("result", out _) || message.TryGetProperty("error", out _), + $"Unexpected non-protocol output: {line}"); + this.MessageCount++; + await this.messages.Writer.WriteAsync(message, this.timeout.Token); + } + } + catch (Exception ex) + { + failure = ex; + throw; + } + finally + { + this.messages.Writer.TryComplete(failure); + } + } + } +} diff --git a/CosmosDBShell.Tests/Integration/ShellProcessTests.cs b/CosmosDBShell.Tests/Integration/ShellProcessTests.cs index 67332c7a..b2f05661 100644 --- a/CosmosDBShell.Tests/Integration/ShellProcessTests.cs +++ b/CosmosDBShell.Tests/Integration/ShellProcessTests.cs @@ -4,12 +4,12 @@ namespace CosmosShell.Tests.Integration; +using Azure.Data.Cosmos.Shell.Core; using System.ComponentModel; using System.Diagnostics; using System.Text; using System.Text.Json; using System.Text.RegularExpressions; -using Azure.Data.Cosmos.Shell.Core; using Azure.Data.Cosmos.Shell.Util; using Microsoft.Azure.Cosmos; @@ -272,6 +272,8 @@ public async Task MachineMode_OutputFailure_RemainsStructuredAndHonorsStderrRedi [InlineData("theme use MACHINE_NOPE", "MACHINE_NOPE", ShellExitCode.GeneralFailure)] [InlineData("help MACHINE_MISSING", "MACHINE_MISSING", ShellExitCode.UsageError)] [InlineData("edit machine.txt", "interactive terminal", ShellExitCode.GeneralFailure)] + [InlineData("watch", "positive --max", ShellExitCode.UsageError)] + [InlineData("watch --max=0", "positive --max", ShellExitCode.UsageError)] public async Task MachineMode_CommandFailure_ReportsSingleStructuredError(string command, string expected, int expectedExitCode) { var result = await RunShellAsync( @@ -661,35 +663,6 @@ public async Task ImportDryRun_MissingFile_RemainsOperationalFailure() Assert.Empty(result.StdOut); } - [Theory] - [InlineData("{\"name\":\"missing-id\"}")] - [InlineData("{\"id\":42}")] - public async Task ImportDryRun_InvalidId_ReturnsUsageExitCodeAndOfflineResult(string content) - { - var file = Path.GetTempFileName(); - try - { - await File.WriteAllTextAsync(file, content, TestContext.Current.CancellationToken); - var result = await RunShellAsync( - stdinScript: null, - extraArgs: ["--output", "json", "-c", $"import {JsonSerializer.Serialize(file)} --dry-run"], - cancellationToken: TestContext.Current.CancellationToken); - - Assert.Equal(ShellExitCode.UsageError, result.ExitCode); - Assert.Empty(result.StdOut); - using var error = JsonDocument.Parse(result.StdErr); - var import = error.RootElement.GetProperty("result"); - Assert.Equal(0, import.GetProperty("imported").GetInt32()); - Assert.Equal(0, import.GetProperty("validated").GetInt32()); - Assert.Equal("offline", import.GetProperty("validationScope").GetString()); - Assert.False(import.GetProperty("targetValidated").GetBoolean()); - } - finally - { - File.Delete(file); - } - } - [Theory] [InlineData(false, false)] [InlineData(false, true)] @@ -924,6 +897,98 @@ public async Task StdinPipedScript_EchoCommand_WritesArgumentToStdOut() Assert.Contains("hello from process", result.StdOut); } + [Theory] + [InlineData(null)] + [InlineData("--help")] + [InlineData("--lsp")] + [InlineData("--stdio")] + public async Task StdioOption_InResponseFile_IsRejectedWithoutStdout(string? additionalArgument) + { + var responseFile = Path.Join(Path.GetTempPath(), $"cosmosshell-stdio-{Guid.NewGuid():N}.rsp"); + await File.WriteAllTextAsync(responseFile, "--mcp-stdio", TestContext.Current.CancellationToken); + try + { + var result = await RunShellAsync( + stdinScript: null, + extraArgs: additionalArgument is null ? ["@" + responseFile] : ["@" + responseFile, additionalArgument], + cancellationToken: TestContext.Current.CancellationToken); + Assert.Equal(2, result.ExitCode); + Assert.Empty(result.StdOut); + Assert.Contains("response file", result.StdErr); + } + finally + { + File.Delete(responseFile); + } + } + + [Fact] + public async Task StdioOption_InResponseFile_WithDirectFalseValue_DoesNotStartProtocol() + { + var responseFile = Path.Join(Path.GetTempPath(), $"cosmosshell-stdio-{Guid.NewGuid():N}.rsp"); + await File.WriteAllTextAsync(responseFile, "--mcp-stdio", TestContext.Current.CancellationToken); + try + { + var result = await RunShellAsync( + stdinScript: null, + extraArgs: ["@" + responseFile, "--mcp-stdio=false"], + cancellationToken: TestContext.Current.CancellationToken); + Assert.Equal(2, result.ExitCode); + Assert.Empty(result.StdOut); + Assert.Contains("--mcp-stdio cannot be combined", result.StdErr); + } + finally + { + File.Delete(responseFile); + } + } + + [Theory] + [InlineData(false, "--help")] + [InlineData(false, "--lsp")] + [InlineData(true, "--help")] + [InlineData(true, "--lsp")] + public async Task MalformedStdioOption_ReportsUsageBeforeEarlyReturns(bool responseFile, string earlyOption) + { + var path = Path.Join(AppContext.BaseDirectory, $"malformed-stdio-{Guid.NewGuid():N}.rsp"); + try + { + const string option = "--mcp-stdio=invalid"; + if (responseFile) + { + await File.WriteAllTextAsync(path, option, TestContext.Current.CancellationToken); + } + + var result = await RunShellAsync( + stdinScript: null, + extraArgs: [responseFile ? "@" + path : option, earlyOption], + cancellationToken: TestContext.Current.CancellationToken); + + Assert.Equal(ShellExitCode.UsageError, result.ExitCode); + Assert.Empty(result.StdOut); + using var error = JsonDocument.Parse(result.StdErr); + Assert.Equal("error", error.RootElement.GetProperty("status").GetString()); + Assert.Contains("invalid", error.RootElement.GetProperty("error").GetString()); + Assert.DoesNotContain("Unhandled exception", result.StdErr); + } + finally + { + File.Delete(path); + } + } + + [Fact] + public async Task StdioOption_InCommandTail_RemainsCommandText() + { + var result = await RunShellAsync( + stdinScript: null, + extraArgs: ["-c", "echo \"--mcp-stdio\""], + cancellationToken: TestContext.Current.CancellationToken); + Assert.Equal(0, result.ExitCode); + Assert.Contains("--mcp-stdio", result.StdOut); + Assert.Empty(result.StdErr); + } + [Fact] public async Task InvariantGlobalization_ExecuteCommand_LoadsEnglishCatalog() { @@ -959,7 +1024,7 @@ public async Task ProcessStdOut_CanBePipedToFile() { // Emulates 'cosmosdbshell < script.txt > output.txt': the caller captures the // process's stdout and writes it to a file, then verifies the command ran. - var outFile = Path.Combine(Path.GetTempPath(), $"cosmosshell-proc-{Guid.NewGuid():N}.txt"); + var outFile = Path.Join(Path.GetTempPath(), $"cosmosshell-proc-{Guid.NewGuid():N}.txt"); try { var result = await RunShellAsync("echo \"PIPE_SMOKE_TEST\"", TestContext.Current.CancellationToken); @@ -1321,7 +1386,7 @@ private static async Task RunShellAsync( || (argsList?.Contains("-c") == true) || (argsList?.Contains("-k") == true); - var shellDll = Path.Combine(AppContext.BaseDirectory, "CosmosDBShell.dll"); + var shellDll = Path.Join(AppContext.BaseDirectory, "CosmosDBShell.dll"); if (!File.Exists(shellDll)) { throw SkipException.ForSkip($"CosmosDBShell.dll not found next to test assembly at '{shellDll}'."); @@ -1489,4 +1554,33 @@ private static string Strip(string text) } private sealed record ShellProcessResult(int ExitCode, string StdOut, string StdErr, string RawStdOut, string RawStdErr); + + [Theory] + [InlineData("{\"name\":\"missing-id\"}")] + [InlineData("{\"id\":42}")] + public async Task ImportDryRun_InvalidId_ReturnsUsageExitCodeAndOfflineResult(string content) + { + var file = Path.GetTempFileName(); + try + { + await File.WriteAllTextAsync(file, content, TestContext.Current.CancellationToken); + var result = await RunShellAsync( + stdinScript: null, + extraArgs: ["--output", "json", "-c", $"import {JsonSerializer.Serialize(file)} --dry-run"], + cancellationToken: TestContext.Current.CancellationToken); + + Assert.Equal(ShellExitCode.UsageError, result.ExitCode); + Assert.Empty(result.StdOut); + using var error = JsonDocument.Parse(result.StdErr); + var import = error.RootElement.GetProperty("result"); + Assert.Equal(0, import.GetProperty("imported").GetInt32()); + Assert.Equal(0, import.GetProperty("validated").GetInt32()); + Assert.Equal("offline", import.GetProperty("validationScope").GetString()); + Assert.False(import.GetProperty("targetValidated").GetBoolean()); + } + finally + { + File.Delete(file); + } + } } diff --git a/CosmosDBShell.Tests/McpConfirmationTests.cs b/CosmosDBShell.Tests/McpConfirmationTests.cs index 158f2cd4..3ec1c7dd 100644 --- a/CosmosDBShell.Tests/McpConfirmationTests.cs +++ b/CosmosDBShell.Tests/McpConfirmationTests.cs @@ -4,6 +4,7 @@ namespace CosmosShell.Tests; +using System.IO.Pipelines; using System.Text.Json; using Azure.Data.Cosmos.Shell.Mcp; using Microsoft.AspNetCore.Hosting.Server; @@ -16,6 +17,101 @@ namespace CosmosShell.Tests; [Collection(CosmosShell.Tests.Shell.ThemeStateTestCollection.Name)] public class McpConfirmationTests { + [Theory] + [InlineData(null, "2026-07-28")] + [InlineData("2025-11-25", "2025-11-25")] + public async Task DestructiveCommand_OverStdio_AsksClientAndHonorsDecline(string? requestedVersion, string negotiatedVersion) + { + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken); + timeout.CancelAfter(TimeSpan.FromSeconds(10)); + var input = new Pipe(); + var output = new Pipe(); + using var host = McpServer.CreateStdioHost(input.Reader.AsStream(), output.Writer.AsStream()); + await host.StartAsync(timeout.Token); + try + { + var prompts = new List(); + await using var client = await McpClient.CreateAsync( + new StreamClientTransport(input.Writer.AsStream(), output.Reader.AsStream()), + new McpClientOptions + { + ProtocolVersion = requestedVersion, + Handlers = new McpClientHandlers + { + ElicitationHandler = (request, _) => + { + prompts.Add(request?.Message); + return ValueTask.FromResult(new ElicitResult { Action = "decline" }); + }, + }, + }, + cancellationToken: timeout.Token); + Assert.Equal(negotiatedVersion, client.NegotiatedProtocolVersion); + var result = await client.CallToolAsync( + "rmdb", + new Dictionary { ["name"] = "StdioConfirmationTestDb" }, + cancellationToken: timeout.Token); + Assert.Contains("StdioConfirmationTestDb", Assert.Single(prompts)); + Assert.True(result.IsError); + Assert.Contains("was not approved", Assert.IsType(Assert.Single(result.Content)).Text); + } + finally + { + await host.StopAsync(TestContext.Current.CancellationToken); + } + } + + [Theory] + [InlineData(null, "2026-07-28")] // Stateless request; confirmation uses native multi-round-trip requests. + [InlineData("2025-11-25", "2025-11-25")] // Initialize handshake; confirmation is sent over the session. + public async Task DestructiveCommand_OverHttp_AsksClientAndHonorsDecline(string? requestedVersion, string negotiatedVersion) + { + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken); + timeout.CancelAfter(TimeSpan.FromSeconds(10)); + using var host = McpServer.CreateHost(new Program.CosmosShellOptions { McpPort = 0 }); + await host.StartAsync(timeout.Token); + try + { + var prompts = new List(); + var address = host.Services.GetRequiredService().Features.Get()!.Addresses.Single(); + var transport = new HttpClientTransport(new HttpClientTransportOptions + { + Endpoint = new Uri(address.TrimEnd('/') + "/"), + }); + await using var client = await McpClient.CreateAsync( + transport, + new McpClientOptions + { + ProtocolVersion = requestedVersion, + Handlers = new McpClientHandlers + { + ElicitationHandler = (request, _) => + { + prompts.Add(request?.Message); + return ValueTask.FromResult(new ElicitResult { Action = "decline" }); + }, + }, + }, + cancellationToken: timeout.Token); + Assert.Equal(negotiatedVersion, client.NegotiatedProtocolVersion); + + var result = await client.CallToolAsync( + "rmdb", + new Dictionary { ["name"] = "McpConfirmationTestDb" }, + cancellationToken: timeout.Token); + + var prompt = Assert.Single(prompts); + Assert.Contains("rmdb \"McpConfirmationTestDb\"", prompt); + Assert.True(result.IsError); + using var document = JsonDocument.Parse(Assert.IsType(Assert.Single(result.Content)).Text); + Assert.Contains("was not approved by the user", document.RootElement.GetProperty("error").GetString()); + } + finally + { + await host.StopAsync(TestContext.Current.CancellationToken); + } + } + [Theory] [InlineData("run", false, 1, "was not approved")] [InlineData("run", true, 0, "not connected")] @@ -131,55 +227,4 @@ public async Task Bulk_DryRunSaveRequiresConfirmationAndDeclineCreatesNoFile(str File.Delete(path); } } - - [Theory] - [InlineData(null, "2026-07-28")] // Stateless request; confirmation uses native multi-round-trip requests. - [InlineData("2025-11-25", "2025-11-25")] // Initialize handshake; confirmation is sent over the session. - public async Task DestructiveCommand_OverHttp_AsksClientAndHonorsDecline(string? requestedVersion, string negotiatedVersion) - { - using var timeout = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken); - timeout.CancelAfter(TimeSpan.FromSeconds(10)); - using var host = McpServer.CreateHost(new Program.CosmosShellOptions { McpPort = 0 }); - await host.StartAsync(timeout.Token); - try - { - var prompts = new List(); - var address = host.Services.GetRequiredService().Features.Get()!.Addresses.Single(); - var transport = new HttpClientTransport(new HttpClientTransportOptions - { - Endpoint = new Uri(address.TrimEnd('/') + "/"), - }); - await using var client = await McpClient.CreateAsync( - transport, - new McpClientOptions - { - ProtocolVersion = requestedVersion, - Handlers = new McpClientHandlers - { - ElicitationHandler = (request, _) => - { - prompts.Add(request?.Message); - return ValueTask.FromResult(new ElicitResult { Action = "decline" }); - }, - }, - }, - cancellationToken: timeout.Token); - Assert.Equal(negotiatedVersion, client.NegotiatedProtocolVersion); - - var result = await client.CallToolAsync( - "rmdb", - new Dictionary { ["name"] = "McpConfirmationTestDb" }, - cancellationToken: timeout.Token); - - var prompt = Assert.Single(prompts); - Assert.Contains("rmdb \"McpConfirmationTestDb\"", prompt); - Assert.True(result.IsError); - using var document = JsonDocument.Parse(Assert.IsType(Assert.Single(result.Content)).Text); - Assert.Contains("was not approved by the user", document.RootElement.GetProperty("error").GetString()); - } - finally - { - await host.StopAsync(TestContext.Current.CancellationToken); - } - } } diff --git a/CosmosDBShell.Tests/McpLocationSubscriptionTests.cs b/CosmosDBShell.Tests/McpLocationSubscriptionTests.cs index 271d45b6..9ff60d72 100644 --- a/CosmosDBShell.Tests/McpLocationSubscriptionTests.cs +++ b/CosmosDBShell.Tests/McpLocationSubscriptionTests.cs @@ -4,6 +4,7 @@ namespace CosmosShell.Tests; +using System.IO.Pipelines; using System.Text.Json; using Azure.Data.Cosmos.Shell.Core; using Azure.Data.Cosmos.Shell.Mcp; @@ -22,6 +23,64 @@ namespace CosmosShell.Tests; [Collection(CosmosShell.Tests.Shell.ThemeStateTestCollection.Name)] public class McpLocationSubscriptionTests { + [Fact] + public async Task StdioSubscription_ReceivesLocationChangeWithoutHttpSession() + { + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken); + timeout.CancelAfter(TimeSpan.FromSeconds(10)); + var input = new Pipe(); + var output = new Pipe(); + using var host = McpServer.CreateStdioHost(input.Reader.AsStream(), output.Writer.AsStream()); + Assert.Null(host.Services.GetService()); + await host.StartAsync(timeout.Token); + var subscriptions = host.Services.GetRequiredService(); + try + { + await using var client = await McpClient.CreateAsync( + new StreamClientTransport(input.Writer.AsStream(), output.Reader.AsStream()), + new McpClientOptions { ProtocolVersion = "2025-11-25" }, + cancellationToken: timeout.Token); + Assert.NotNull(client.ServerCapabilities.Resources); + Assert.True(client.ServerCapabilities.Resources.Subscribe); + Assert.False(client.ServerCapabilities.Resources.ListChanged); + var updated = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + await using var subscription = await client.SubscribeToResourceAsync( + ResourceOperations.CurrentLocationUri, + (notification, _) => + { + updated.TrySetResult(notification.Uri); + return ValueTask.CompletedTask; + }, + cancellationToken: timeout.Token); + Assert.Equal(1, subscriptions.SubscriberCount); + var originalState = ShellInterpreter.Instance.State; + using var cosmosClient = new CosmosClient( + "https://localhost:8081", + Convert.ToBase64String(new byte[64]), + new CosmosClientOptions { ConnectionMode = ConnectionMode.Gateway }); + try + { + ShellInterpreter.Instance.State = new DatabaseState("StdioNotificationTest", cosmosClient); + Assert.Equal(ResourceOperations.CurrentLocationUri, await updated.Task.WaitAsync(timeout.Token)); + var resource = await client.ReadResourceAsync(ResourceOperations.CurrentLocationUri, cancellationToken: timeout.Token); + using var json = JsonDocument.Parse(Assert.IsType(Assert.Single(resource.Contents)).Text); + Assert.Equal("/StdioNotificationTest", json.RootElement.GetProperty("currentLocation").GetString()); + await client.UnsubscribeFromResourceAsync(ResourceOperations.CurrentLocationUri, cancellationToken: timeout.Token); + Assert.Equal(0, subscriptions.SubscriberCount); + } + finally + { + ShellInterpreter.Instance.State = originalState; + } + } + finally + { + await host.StopAsync(TestContext.Current.CancellationToken); + } + + Assert.Equal(0, subscriptions.SubscriberCount); + } + [Theory] [InlineData(HttpTransportMode.StreamableHttp, "2025-11-25")] [InlineData(HttpTransportMode.Sse, "2024-11-05")] @@ -163,7 +222,7 @@ await admission.InvokeAsync(admissionContext, current => #pragma warning restore MCPEXP002 try { - subscriptions.Subscribe(server.SessionId, ResourceOperations.CurrentLocationUri); + subscriptions.Subscribe(server, ResourceOperations.CurrentLocationUri); Assert.Equal(1, subscriptions.SubscriberCount); Assert.False(session.IsCompleted); context.Uninitialize(); diff --git a/CosmosDBShell.Tests/Shell/ShellConfigDirectoryTests.cs b/CosmosDBShell.Tests/Shell/ShellConfigDirectoryTests.cs index 281aacd8..96c9d6d9 100644 --- a/CosmosDBShell.Tests/Shell/ShellConfigDirectoryTests.cs +++ b/CosmosDBShell.Tests/Shell/ShellConfigDirectoryTests.cs @@ -19,6 +19,26 @@ public sealed class ShellConfigDirectoryTestCollection [Collection(ShellConfigDirectoryTestCollection.Name)] public class ShellConfigDirectoryTests { + [Fact] + public void DisabledHistory_DoesNotLoadExistingCommands() + { + var isolatedDir = Path.Join(Path.GetTempPath(), $"cosmosshell-no-history-{Guid.NewGuid():N}"); + Directory.CreateDirectory(isolatedDir); + var historyFile = Path.Join(isolatedDir, "cmd_history"); + File.WriteAllText(historyFile, "echo HISTORY_SENTINEL\n"); + try + { + using var shell = new ShellInterpreter(isolatedDir, historyEnabled: false); + Assert.Empty(shell.History); + Assert.Equal(0, shell.PendingHistoryCount); + Assert.Equal("echo HISTORY_SENTINEL\n", File.ReadAllText(historyFile)); + } + finally + { + Directory.Delete(isolatedDir, recursive: true); + } + } + [Fact] public void ConfigDirEnvVar_RedirectsHistoryFileAwayFromRealUserDirectory() { diff --git a/CosmosDBShell.Tests/StdioInputStreamTests.cs b/CosmosDBShell.Tests/StdioInputStreamTests.cs new file mode 100644 index 00000000..bb84d11b --- /dev/null +++ b/CosmosDBShell.Tests/StdioInputStreamTests.cs @@ -0,0 +1,36 @@ +// ------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +// ------------------------------------------------------------ + +namespace CosmosShell.Tests; + +using Azure.Data.Cosmos.Shell.Mcp; +using Microsoft.Extensions.Hosting; +using NSubstitute; + +public class StdioInputStreamTests +{ + [Fact] + public async Task Reads_StopHostOnlyAtActualEof() + { + var lifetime = Substitute.For(); + using var input = new StdioInputStream(new MemoryStream([42])) { HostLifetime = lifetime }; + var buffer = new byte[1]; + Assert.Equal(0, await input.ReadAsync(Memory.Empty, TestContext.Current.CancellationToken)); + lifetime.DidNotReceive().StopApplication(); + Assert.Equal(1, await input.ReadAsync(buffer.AsMemory(), TestContext.Current.CancellationToken)); + Assert.Equal(42, buffer[0]); + lifetime.DidNotReceive().StopApplication(); + Assert.Equal(0, await input.ReadAsync(buffer.AsMemory(), TestContext.Current.CancellationToken)); + lifetime.Received(1).StopApplication(); + } + + [Fact] + public void SynchronousEof_StopsHost() + { + var lifetime = Substitute.For(); + using var input = new StdioInputStream(new MemoryStream()) { HostLifetime = lifetime }; + Assert.Equal(0, input.Read(new byte[1], 0, 1)); + lifetime.Received(1).StopApplication(); + } +} diff --git a/CosmosDBShell.Tests/StdioStartupInputTests.cs b/CosmosDBShell.Tests/StdioStartupInputTests.cs new file mode 100644 index 00000000..0002c707 --- /dev/null +++ b/CosmosDBShell.Tests/StdioStartupInputTests.cs @@ -0,0 +1,358 @@ +// ------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +// ------------------------------------------------------------ + +namespace CosmosShell.Tests; + +using System.IO.Pipelines; +using System.Diagnostics; +using System.Text; +using Azure.Data.Cosmos.Shell.Mcp; + +public class StdioStartupInputTests +{ + [Fact] + public async Task Dispose_DrainsTimeoutCallbackBeforeReleasingCancellationSources() + { + using var source = new MemoryStream(); + using var input = new StdioStartupInput(source, TimeSpan.FromSeconds(1)); + using var releaseCallback = new ManualResetEventSlim(); + var callbackEntered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + using var registration = input.StartupToken.Register(() => + { + callbackEntered.TrySetResult(); + releaseCallback.Wait(TimeSpan.FromSeconds(15)); + }); + try + { + await callbackEntered.Task.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken); + await Task.Run(input.Dispose, TestContext.Current.CancellationToken) + .WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + + Assert.False(File.Exists(input.StartupBufferPath)); + Assert.NotNull(input.StartupToken.WaitHandle); + } + finally + { + releaseCallback.Set(); + } + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task EmptyReads_PreserveBufferedRequests(bool synchronous) + { + using var source = new UninterruptibleInput(); + using var input = new StdioStartupInput(source); + input.Start(); + try + { + await source.Blocked.Task.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken); + Assert.Equal(0, await input.Input.ReadAsync(Memory.Empty, TestContext.Current.CancellationToken)); + await input.CompleteStartupAsync(); + if (synchronous) + { + Assert.Equal(0, input.Input.Read([], 0, 0)); + } + else + { + Assert.Equal(0, await input.Input.ReadAsync(Memory.Empty, TestContext.Current.CancellationToken)); + } + + source.Release.TrySetResult(); + using var received = new MemoryStream(); + await input.Input.CopyToAsync(received, TestContext.Current.CancellationToken); + Assert.Equal(UninterruptibleInput.Prefix, received.ToArray()); + } + finally + { + source.Release.TrySetResult(); + } + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task Dispose_DeletesStartupSpoolWithoutWaitingForUninterruptibleInput(bool timedOut) + { + using var source = new UninterruptibleInput(); + using var input = new StdioStartupInput( + source, timedOut ? TimeSpan.FromMilliseconds(50) : TimeSpan.FromSeconds(60)); + input.Start(); + try + { + await source.Blocked.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + if (timedOut) + { + await Assert.ThrowsAnyAsync(() => + Task.Delay(Timeout.InfiniteTimeSpan, input.StartupToken) + .WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken)); + Assert.True(input.TimedOut); + } + + input.Dispose(); + + Assert.False(source.Release.Task.IsCompleted); + Assert.False(File.Exists(input.StartupBufferPath)); + } + finally + { + source.Release.TrySetResult(); + } + } + + [Fact] + public async Task CompletedStartup_ReusesSpoolHandleAndDeletesItAfterReading() + { + using var source = new UninterruptibleInput(); + using var input = new StdioStartupInput(source); + input.Start(); + try + { + await source.Blocked.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + await input.CompleteStartupAsync(); + source.Release.TrySetResult(); + using var received = new MemoryStream(); + await input.Input.CopyToAsync(received, TestContext.Current.CancellationToken); + + Assert.Equal(UninterruptibleInput.Prefix, received.ToArray()); + Assert.False(File.Exists(input.StartupBufferPath)); + } + finally + { + source.Release.TrySetResult(); + } + } + + [Fact] + public async Task Eof_CancelsStartupAndPreservesBufferedProtocolBytes() + { + var source = new Pipe(); + using var input = new StdioStartupInput(source.Reader.AsStream()); + input.Start(); + var bytes = Encoding.UTF8.GetBytes("{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"ping\"}\n"); + await source.Writer.WriteAsync(bytes, TestContext.Current.CancellationToken); + await source.Writer.CompleteAsync(); + + await Assert.ThrowsAnyAsync(() => + Task.Delay(Timeout.InfiniteTimeSpan, input.StartupToken) + .WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken)); + Assert.False(input.TimedOut); + Assert.Null(input.InputError); + Assert.Empty(ReportCancellation(input).Messages); + using var received = new MemoryStream(); + await input.Input.CopyToAsync(received, TestContext.Current.CancellationToken); + Assert.Equal(bytes, received.ToArray()); + } + + [Fact] + public async Task PendingInput_StartupDeadlineCancelsWithoutEof() + { + Assert.Equal(TimeSpan.FromSeconds(60), StdioStartupInput.StartupTimeout); + var source = new Pipe(); + using var input = new StdioStartupInput(source.Reader.AsStream(), TimeSpan.FromMilliseconds(100)); + input.Start(); + + await Assert.ThrowsAnyAsync(() => + Task.Delay(Timeout.InfiniteTimeSpan, input.StartupToken) + .WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken)); + Assert.True(input.TimedOut); + Assert.Null(input.InputError); + await source.Writer.CompleteAsync(); + } + + [Fact] + public async Task CompletedStartup_DisablesDeadlineAndContinuesReading() + { + var source = new Pipe(); + using var input = new StdioStartupInput(source.Reader.AsStream(), TimeSpan.FromMilliseconds(100)); + input.Start(); + await input.CompleteStartupAsync(); + await Task.Delay(TimeSpan.FromMilliseconds(200), TestContext.Current.CancellationToken); + Assert.False(input.StartupToken.IsCancellationRequested); + Assert.False(input.TimedOut); + + await source.Writer.WriteAsync(new byte[] { 42 }, TestContext.Current.CancellationToken); + var received = new byte[1]; + Assert.Equal(1, await input.Input.ReadAsync(received.AsMemory(), TestContext.Current.CancellationToken)); + Assert.Equal(42, received[0]); + await source.Writer.CompleteAsync(); + } + + [Fact] + public async Task LargeQueuedInput_DrainsThroughEofAndPreservesBytes() + { + var source = new Pipe(); + using var input = new StdioStartupInput(source.Reader.AsStream()); + input.Start(); + var bytes = new byte[256 * 1024]; + Random.Shared.NextBytes(bytes); + + await source.Writer.WriteAsync(bytes, TestContext.Current.CancellationToken); + await source.Writer.CompleteAsync(); + await Assert.ThrowsAnyAsync(() => + Task.Delay(Timeout.InfiniteTimeSpan, input.StartupToken) + .WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken)); + + using var received = new MemoryStream(); + await input.Input.CopyToAsync(received, TestContext.Current.CancellationToken); + Assert.Equal(bytes, received.ToArray()); + Assert.False(input.TimedOut); + } + + [Fact] + public async Task ProductionDeadline_IsSixtySecondsAndTimeoutReportsConnectionError() + { + Assert.Equal(TimeSpan.FromSeconds(60), StdioStartupInput.StartupTimeout); + var source = new Pipe(); + using var input = new StdioStartupInput(source.Reader.AsStream(), TimeSpan.FromMilliseconds(50)); + input.Start(); + await Assert.ThrowsAnyAsync(() => + Task.Delay(Timeout.InfiniteTimeSpan, input.StartupToken) + .WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken)); + + await source.Writer.CompleteAsync(); + var received = new byte[1]; + Assert.Equal(0, await input.Input.ReadAsync(received, TestContext.Current.CancellationToken)); + Assert.True(input.TimedOut); + var (exitCode, messages) = ReportCancellation(input); + Assert.Equal(4, exitCode); + Assert.Contains("timed out after 60 seconds", Assert.Single(messages)); + } + + [Fact] + public async Task InputFailure_CancelsStartupAndSurfacesOriginalError() + { + var error = new IOException("STDIO_INPUT_FAILURE"); + using var input = new StdioStartupInput(new FaultingInput(error)); + input.Start(); + await Assert.ThrowsAnyAsync(() => + Task.Delay(Timeout.InfiniteTimeSpan, input.StartupToken) + .WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken)); + Assert.Same(error, input.InputError); + Assert.False(input.TimedOut); + var (exitCode, messages) = ReportCancellation(input); + Assert.Equal(1, exitCode); + Assert.Contains("STDIO_INPUT_FAILURE", Assert.Single(messages)); + var received = new byte[1]; + var actual = await Assert.ThrowsAsync(() => + input.Input.ReadAsync(received.AsMemory(), TestContext.Current.CancellationToken).AsTask()); + Assert.Same(error, actual); + } + + [Fact] + public async Task StartupBuffer_ExactlyAtLimit_PreservesAllBytesWithoutCancellation() + { + Assert.Equal(8 * 1024 * 1024, StdioStartupInput.MaximumStartupBufferBytes); + var bytes = new byte[StdioStartupInput.MaximumStartupBufferBytes]; + Random.Shared.NextBytes(bytes); + using var source = new UninterruptibleInput(bytes); + using var input = new StdioStartupInput(source); + input.Start(); + try + { + await source.Blocked.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + Assert.False(input.StartupToken.IsCancellationRequested); + Assert.Null(input.InputError); + await input.CompleteStartupAsync(); + source.Release.TrySetResult(); + using var received = new MemoryStream(); + await input.Input.CopyToAsync(received, TestContext.Current.CancellationToken); + + Assert.Equal(bytes, received.ToArray()); + Assert.False(File.Exists(input.StartupBufferPath)); + } + finally + { + source.Release.TrySetResult(); + } + } + + [Fact] + public async Task StartupBuffer_OneByteOverLimit_CancelsReportsErrorAndNeverExceedsLimit() + { + using var source = new MemoryStream(new byte[StdioStartupInput.MaximumStartupBufferBytes + 1]); + using var input = new StdioStartupInput(source); + input.Start(); + await Assert.ThrowsAnyAsync(() => + Task.Delay(Timeout.InfiniteTimeSpan, input.StartupToken) + .WaitAsync(TimeSpan.FromSeconds(30), TestContext.Current.CancellationToken)); + + Assert.False(input.TimedOut); + var error = Assert.IsType(input.InputError); + var (exitCode, messages) = ReportCancellation(input); + Assert.Equal(1, exitCode); + Assert.Contains("8 MiB", Assert.Single(messages)); + using var received = new MemoryStream(); + var actual = await Assert.ThrowsAsync(() => + input.Input.CopyToAsync(received, TestContext.Current.CancellationToken)); + Assert.Same(error, actual); + Assert.Equal(StdioStartupInput.MaximumStartupBufferBytes, received.Length); + Assert.False(File.Exists(input.StartupBufferPath)); + } + + [Fact] + public async Task CompletedStartup_InputOverStartupLimit_IsNotRejected() + { + var bytes = new byte[StdioStartupInput.MaximumStartupBufferBytes + 1]; + Random.Shared.NextBytes(bytes); + using var source = new MemoryStream(bytes); + using var input = new StdioStartupInput(source); + await input.CompleteStartupAsync(); + input.Start(); + using var received = new MemoryStream(); + await input.Input.CopyToAsync(received, TestContext.Current.CancellationToken); + + Assert.Equal(bytes, received.ToArray()); + Assert.Null(input.InputError); + Assert.False(input.TimedOut); + } + + private sealed class FaultingInput(Exception error) : MemoryStream + { + public override ValueTask ReadAsync( + Memory buffer, + CancellationToken cancellationToken = default) + => ValueTask.FromException(error); + } + + private sealed class UninterruptibleInput(byte[]? prefix = null) : MemoryStream(prefix ?? Prefix) + { + internal static readonly byte[] Prefix = Encoding.UTF8.GetBytes("{\"jsonrpc\":\"2.0\",\"method\":\"ping\"}\n"); + + internal TaskCompletionSource Blocked { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + + internal TaskCompletionSource Release { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + + public override async ValueTask ReadAsync( + Memory buffer, + CancellationToken cancellationToken = default) + { + if (this.Position < this.Length) + { + return await base.ReadAsync(buffer, cancellationToken); + } + + this.Blocked.TrySetResult(); + await this.Release.Task; + return 0; + } + } + + private static (int ExitCode, List Messages) ReportCancellation(StdioStartupInput input) + { + var originalExitCode = Environment.ExitCode; + try + { + Environment.ExitCode = 0; + var messages = new List(); + Program.ReportStdioStartupCancellation(input, messages.Add); + return (Environment.ExitCode, messages); + } + finally + { + Environment.ExitCode = originalExitCode; + } + } +} diff --git a/CosmosDBShell.Tests/ToolOperationsCallToolTests.cs b/CosmosDBShell.Tests/ToolOperationsCallToolTests.cs index f36870ae..fb4f6c68 100644 --- a/CosmosDBShell.Tests/ToolOperationsCallToolTests.cs +++ b/CosmosDBShell.Tests/ToolOperationsCallToolTests.cs @@ -186,6 +186,203 @@ public async Task CallTool_RestrictedCommand_ReturnsError() Assert.True(isError); Assert.Contains("restricted for MCP", root.GetProperty("error").GetString()); } + + } + + [Fact] + public void StdioCommandRemoval_RemovesUnsupportedCommandsAndAliasesButKeepsConfirmableCommands() + { + var runner = new CommandRunner(); + var expectedRemaining = runner.Commands.Where(entry => !ToolOperations.IsUnavailableInStdio(entry.Value)).Select(entry => entry.Key).ToList(); + Assert.Contains(runner.Commands.Values, command => command.CommandName == "jq"); + Assert.Contains(runner.Commands.Values, command => command.CommandName == "theme"); + + runner.RemoveCommands(ToolOperations.IsUnavailableInStdio); + + Assert.DoesNotContain(runner.Commands.Values, command => command.CommandName is "jq" or "theme"); + foreach (var name in new[] { "exit", "edit", "watch", "welcome", "sproc", "udf", "trigger" }) + { + Assert.False(runner.Commands.ContainsKey(name), $"Unsupported command '{name}' remains registered."); + } + + foreach (var name in new[] { "delete", "rm", "rmdb", "rmcon" }) + { + Assert.True(runner.Commands.ContainsKey(name), $"Confirmable command '{name}' was removed."); + } + + Assert.Equal(expectedRemaining.Order(), runner.Commands.Keys.Order()); + Assert.True(ShellInterpreter.Instance.App.Commands.ContainsKey("theme")); + } + + [Fact] + public void Stdio_PrintCommand_DoesNotRecordInMemoryHistory() + { + var shell = ShellInterpreter.Instance; + var originalOptions = shell.Options; + var originalHistory = shell.History.ToArray(); + var originalPending = shell.PendingHistoryCount; + try + { + shell.Options = new Program.CosmosShellOptions { McpStdio = true }; + shell.PrintCommand("echo STDIO_NO_HISTORY"); + Assert.Equal(originalHistory, shell.History); + Assert.Equal(originalPending, shell.PendingHistoryCount); + } + finally + { + shell.Options = originalOptions; + } + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task Stdio_ApprovedConfirmation_IsScopedToCommandAndNeverReadsConsole(bool failAfterConfirmation) + { + var shell = ShellInterpreter.Instance; + var originalOptions = shell.Options; + var originalApproval = shell.McpConfirmationApproved; + shell.Options = new Program.CosmosShellOptions { McpStdio = true }; + shell.McpConfirmationApproved = false; + try + { + Assert.Throws(() => ShellInterpreter.Confirm("command-rmdb-confirm_db_deletion")); + var result = await this.CreateToolOperations().ExecuteToolAsync( + shell.App.Commands["rmdb"], + new ConfirmationCheckingCommand(failAfterConfirmation), + "rmdb StdioScopeTest", + (_, _, _) => ValueTask.FromResult(new ElicitResult { Action = "accept" }), + TestContext.Current.CancellationToken); + Assert.Equal(failAfterConfirmation, result.IsError == true); + Assert.False(shell.McpConfirmationApproved); + Assert.Throws(() => ShellInterpreter.Confirm("command-rmdb-confirm_db_deletion")); + } + finally + { + shell.McpConfirmationApproved = originalApproval; + shell.Options = originalOptions; + } + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task CancelledTool_PropagatesCancellationWithoutLoggingFailure(bool queued) + { + var shell = ShellInterpreter.Instance; + var logger = new RecordingToolLogger(); + var tools = new ToolOperations(logger, this.locationSubscriptions); + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken); + timeout.CancelAfter(TimeSpan.FromSeconds(5)); + using var cancellation = CancellationTokenSource.CreateLinkedTokenSource(timeout.Token); + var gateEntered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var releaseGate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var gate = queued + ? shell.RunSerializedAsync( + async () => + { + gateEntered.SetResult(); + await releaseGate.Task.WaitAsync(timeout.Token); + return true; + }, timeout.Token) + : Task.FromResult(true); + var command = new CancellationCheckingCommand(); + try + { + if (queued) + { + await gateEntered.Task.WaitAsync(timeout.Token); + } + + var call = tools.ExecuteToolAsync( + shell.App.Commands["echo"], command, "echo CANCELLED_TOOL", null, cancellation.Token); + if (!queued) + { + await command.Started.Task.WaitAsync(timeout.Token); + } + + await cancellation.CancelAsync(); + await Assert.ThrowsAnyAsync(() => call.WaitAsync(timeout.Token)); + Assert.Equal(!queued, command.Started.Task.IsCompleted); + Assert.DoesNotContain(LogLevel.Error, logger.Levels); + } + finally + { + releaseGate.TrySetResult(); + await gate; + } + + var next = await tools.CallToolHandler( + CallContext("echo", new() { ["messages"] = Json("[\"AFTER_CANCELLATION\"]") }), timeout.Token); + Assert.False(next.IsError == true); + Assert.Contains("AFTER_CANCELLATION", Assert.IsType(Assert.Single(next.Content)).Text); + } + + [Fact] + public async Task CancelledConfirmation_NeverExecutesCommandAndReleasesShell() + { + var shell = ShellInterpreter.Instance; + var tools = this.CreateToolOperations(); + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken); + timeout.CancelAfter(TimeSpan.FromSeconds(5)); + using var cancellation = CancellationTokenSource.CreateLinkedTokenSource(timeout.Token); + var prompted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var command = new CancellationCheckingCommand(); + var call = tools.ExecuteToolAsync( + shell.App.Commands["rmdb"], command, "rmdb CANCELLED_CONFIRMATION", + async (_, _, token) => + { + prompted.SetResult(); + await Task.Delay(Timeout.InfiniteTimeSpan, token); + return new ElicitResult { Action = "accept" }; + }, cancellation.Token); + await prompted.Task.WaitAsync(timeout.Token); + await cancellation.CancelAsync(); + await Assert.ThrowsAnyAsync(() => call.WaitAsync(timeout.Token)); + Assert.False(command.Started.Task.IsCompleted); + Assert.False(shell.McpConfirmationApproved); + Assert.True(await shell.RunSerializedAsync(() => Task.FromResult(true), timeout.Token)); + } + + private sealed class CancellationCheckingCommand : CosmosCommand + { + public TaskCompletionSource Started { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + + public override async Task ExecuteAsync( + ShellInterpreter shell, CommandState commandState, string commandText, CancellationToken token) + { + this.Started.SetResult(); + await Task.Delay(Timeout.InfiniteTimeSpan, token); + return commandState; + } + } + + private sealed class RecordingToolLogger : ILogger + { + public List Levels { get; } = []; + + public IDisposable? BeginScope(TState state) + where TState : notnull => null; + + public bool IsEnabled(LogLevel logLevel) => true; + + public void Log( + LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) + => this.Levels.Add(logLevel); + } + + private sealed class ConfirmationCheckingCommand(bool failAfterConfirmation) : CosmosCommand + { + public override Task ExecuteAsync(ShellInterpreter shell, CommandState commandState, string commandText, CancellationToken token) + { + Assert.True(ShellInterpreter.Confirm("command-rmdb-confirm_db_deletion")); + if (failAfterConfirmation) + { + throw new InvalidOperationException("Confirmation scope test failure."); + } + + return Task.FromResult(commandState); + } } [Fact] diff --git a/CosmosDBShell.Tests/UtilTest/OutputPolicyTests.cs b/CosmosDBShell.Tests/UtilTest/OutputPolicyTests.cs index f7ed61c3..9e9df082 100644 --- a/CosmosDBShell.Tests/UtilTest/OutputPolicyTests.cs +++ b/CosmosDBShell.Tests/UtilTest/OutputPolicyTests.cs @@ -85,6 +85,17 @@ public void DefaultOutputFormat_QuietWithoutFormat_FallsBackToJson() Assert.Equal(OutputFormat.JSon, shell.DefaultOutputFormat); } + [Fact] + public void StdioMode_IsHeadlessWithoutSuppressingStderrDiagnostics() + { + using var shell = ShellInterpreter.CreateInstance(); + shell.Options = new Program.CosmosShellOptions { McpStdio = true }; + Assert.True(shell.IsMachineMode); + Assert.False(shell.Options.Quiet); + Assert.Equal(OutputFormat.JSon, shell.DefaultOutputFormat); + Assert.False(InfoCommand.ShouldRenderTables(null, shell, new CommandState())); + } + [Fact] public void DefaultOutputFormat_ExecuteAndQuitWithoutFormat_FallsBackToJson() { diff --git a/CosmosDBShell.Tests/UtilTest/ShellOutputTests.cs b/CosmosDBShell.Tests/UtilTest/ShellOutputTests.cs index 4978a66b..086acad6 100644 --- a/CosmosDBShell.Tests/UtilTest/ShellOutputTests.cs +++ b/CosmosDBShell.Tests/UtilTest/ShellOutputTests.cs @@ -14,13 +14,13 @@ public class ShellOutputTests [InlineData(true, false)] [InlineData(false, true)] [InlineData(true, true)] - public void Presentation_UsesCategoryPolicyForTextMarkupAndRenderables(bool quiet, bool machineMode) + public void Presentation_UsesCategoryPolicyForTextMarkupAndRenderables(bool quiet, bool stdio) { foreach (var kind in Enum.GetValues()) { using var stdout = new StringWriter(); using var stderr = new StringWriter(); - var output = CreateOutput(quiet, machineMode, stdout, stderr); + var output = CreateOutput(quiet, stdio, stdout, stderr); var marker = kind.ToString(); output.Write(kind, marker + "_text"); @@ -31,8 +31,11 @@ public void Presentation_UsesCategoryPolicyForTextMarkupAndRenderables(bool quie output.RenderLine(kind, marker + "_renderLine"); output.WriteException(kind, new InvalidOperationException(marker + "_exception")); - var suppressed = ((quiet || machineMode) && kind is ShellMessageKind.Information or ShellMessageKind.Progress) - || (machineMode && kind == ShellMessageKind.Result); + // CreateOutput treats quiet or stdio as machine mode, which suppresses command-level + // result presentation; machine-mode results go through WriteResult instead. + var machineMode = quiet || stdio; + var suppressed = (machineMode && kind is ShellMessageKind.Information or ShellMessageKind.Progress) + || ((stdio || machineMode) && kind == ShellMessageKind.Result); if (suppressed) { Assert.Empty(stdout.ToString()); @@ -40,7 +43,7 @@ public void Presentation_UsesCategoryPolicyForTextMarkupAndRenderables(bool quie continue; } - var useStderr = machineMode && kind is ShellMessageKind.Warning or ShellMessageKind.Error or ShellMessageKind.RequiredInstruction; + var useStderr = stdio || (quiet && kind is ShellMessageKind.Warning or ShellMessageKind.Error or ShellMessageKind.RequiredInstruction); var visible = (useStderr ? stderr : stdout).ToString(); Assert.Empty((useStderr ? stdout : stderr).ToString()); foreach (var suffix in new[] { "_text", "_line", "_markup", "_markupLine", "_renderable", "_renderLine", "_exception" }) @@ -60,15 +63,17 @@ public void StructuredMode_RoutesWarningsErrorsAndAuthenticationToStderr() { using var stdout = new StringWriter(); using var stderr = new StringWriter(); - var output = CreateOutput(false, true, stdout, stderr); + var output = CreateOutput(false, false, stdout, stderr, machineMode: true); output.MarkupLine(ShellMessageKind.Warning, "[yellow]warning[/]"); output.WriteLine(ShellMessageKind.Error, "error"); output.WriteLine(ShellMessageKind.RequiredInstruction, "login"); + output.WriteLine(ShellMessageKind.Information, "hidden information"); output.WriteLine(ShellMessageKind.Result, "eager table"); output.Render(ShellMessageKind.Result, new Text("eager renderable")); output.WriteResult("{\"result\":true}"); Assert.Equal("{\"result\":true}" + Environment.NewLine, stdout.ToString()); Assert.DoesNotContain("eager", stderr.ToString(), StringComparison.Ordinal); + Assert.DoesNotContain("hidden information", stdout.ToString(), StringComparison.Ordinal); Assert.Contains("warning", stderr.ToString()); Assert.Contains("error", stderr.ToString()); Assert.Contains("login", stderr.ToString()); @@ -81,23 +86,25 @@ public void Modes_AreEvaluatedAtWriteTime() using var stdout = new StringWriter(); using var stderr = new StringWriter(); var quiet = false; - var machineMode = false; - var output = new ShellOutput(() => quiet, () => machineMode, () => stdout, () => stderr); + var stdio = false; + var output = new ShellOutput(() => quiet, () => stdio, () => quiet || stdio, () => stdout, () => stderr); output.WriteLine(ShellMessageKind.Information, "before"); quiet = true; - machineMode = true; output.WriteLine(ShellMessageKind.Information, "hidden"); output.WriteLine(ShellMessageKind.Result, "command-level result hidden in machine mode"); output.WriteResult("result"); + stdio = true; + output.WriteResult("not a protocol response"); output.WriteLine(ShellMessageKind.RequiredInstruction, "device code"); Assert.Equal("before" + Environment.NewLine + "result" + Environment.NewLine, stdout.ToString()); Assert.Equal("device code" + Environment.NewLine, stderr.ToString()); } [Theory] - [InlineData(false, true)] - [InlineData(true, false)] - public void ClearScreen_OnlyTouchesInteractiveTerminal(bool machineMode, bool cleared) + [InlineData(false, false, true)] + [InlineData(true, false, false)] + [InlineData(false, true, false)] + public void ClearScreen_OnlyTouchesInteractiveTerminal(bool machineMode, bool stdio, bool cleared) { using var stdout = new StringWriter(); using var stderr = new StringWriter(); @@ -107,7 +114,7 @@ public void ClearScreen_OnlyTouchesInteractiveTerminal(bool machineMode, bool cl ColorSystem = ColorSystemSupport.NoColors, Out = new AnsiConsoleOutput(stdout), }); - var output = new ShellOutput(() => false, () => machineMode, () => stdout, () => stderr, () => terminal); + var output = new ShellOutput(() => false, () => stdio, () => machineMode, () => stdout, () => stderr, () => terminal); output.ClearScreen(); Assert.Equal(cleared, stdout.ToString().Length > 0); Assert.Empty(stderr.ToString()); @@ -136,10 +143,11 @@ public void Markup_PreservesLiteralBracesWithoutFormattingArguments() Assert.Equal("{\"value\":1}{\"value\":2}" + Environment.NewLine + "formatted" + Environment.NewLine, stdout.ToString()); } - private static ShellOutput CreateOutput(bool quiet, bool machineMode, StringWriter stdout, StringWriter stderr) + private static ShellOutput CreateOutput(bool quiet, bool stdio, StringWriter stdout, StringWriter stderr, bool machineMode = false) => new( () => quiet, - () => machineMode, + () => stdio, + () => machineMode || quiet || stdio, () => stdout, () => stderr, () => AnsiConsole.Create(new AnsiConsoleSettings diff --git a/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/BucketCommand.cs b/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/BucketCommand.cs index dfb42e1b..92a4dd79 100644 --- a/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/BucketCommand.cs +++ b/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/BucketCommand.cs @@ -195,11 +195,11 @@ private static void WriteClientSelection(ShellInterpreter shell, int? clientBuck { if (clientBucket.HasValue) { - shell.Output.MarkupLine(ShellMessageKind.Information, MessageService.GetString("command-bucket-current", new Dictionary { { "bucket", Theme.FormatTableValue(clientBucket.Value.ToString(CultureInfo.InvariantCulture)) } })); + shell.Output.MarkupLine(ShellMessageKind.Result, MessageService.GetString("command-bucket-current", new Dictionary { { "bucket", Theme.FormatTableValue(clientBucket.Value.ToString(CultureInfo.InvariantCulture)) } })); } else { - shell.Output.MarkupLine(ShellMessageKind.Information, MessageService.GetString("command-bucket-no_bucket")); + shell.Output.MarkupLine(ShellMessageKind.Result, MessageService.GetString("command-bucket-no_bucket")); } } @@ -241,6 +241,7 @@ private CommandState RunClientCommand(ShellInterpreter shell, CosmosClient clien throw CommandException.Usage("bucket", MessageService.GetString("command-bucket-error-unexpected_args")); } + string? message = null; if (this.Classify() == BucketActionKind.ClientSet) { int bucket = int.Parse(this.Action!.Trim(), CultureInfo.InvariantCulture); @@ -254,26 +255,30 @@ private CommandState RunClientCommand(ShellInterpreter shell, CosmosClient clien if (bucket == 0) { client.ClientOptions.ThroughputBucket = null; - shell.Output.MarkupLine(ShellMessageKind.Information, MessageService.GetString("command-bucket-reset_bucket")); + message = MessageService.GetString("command-bucket-reset_bucket"); } else { client.ClientOptions.ThroughputBucket = bucket; - shell.Output.MarkupLine(ShellMessageKind.Information, MessageService.GetString("command-bucket-switched_bucket", new Dictionary { { "bucket", Theme.FormatTableValue(bucket.ToString(CultureInfo.InvariantCulture)) } })); + message = MessageService.GetString("command-bucket-switched_bucket", new Dictionary { { "bucket", Theme.FormatTableValue(bucket.ToString(CultureInfo.InvariantCulture)) } }); } } - else - { - WriteClientSelection(shell, client.ClientOptions.ThroughputBucket); - } + var clientBucket = client.ClientOptions.ThroughputBucket; return new CommandState { - Result = new ShellJson(JsonSerializer.SerializeToElement(new JsonObject + Result = new ShellJson(JsonSerializer.SerializeToElement(new { clientBucket })), + RenderUser = () => { - ["clientBucket"] = client.ClientOptions.ThroughputBucket, - })), - RenderUser = () => { }, + if (message is null) + { + WriteClientSelection(shell, clientBucket); + } + else + { + shell.Output.MarkupLine(ShellMessageKind.Result, message); + } + }, }; } diff --git a/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/ConflictCommand.cs b/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/ConflictCommand.cs index e2bdb32c..5f486d37 100644 --- a/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/ConflictCommand.cs +++ b/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/ConflictCommand.cs @@ -136,7 +136,7 @@ private static CommandState BuildResult(string containerName, ConflictResolution return new CommandState { Result = new ShellJson(jsonDoc.RootElement.Clone()), - RenderUser = () => ShellInterpreter.WriteLine(MessageService.GetArgsString( + RenderUser = () => ShellInterpreter.Instance.Output.WriteLine(ShellMessageKind.Result, MessageService.GetArgsString( messageId, "container", containerName, diff --git a/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/TtlCommand.cs b/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/TtlCommand.cs index 1ba51162..cb92375b 100644 --- a/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/TtlCommand.cs +++ b/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/TtlCommand.cs @@ -137,7 +137,7 @@ private static CommandState BuildResult(string containerName, ContainerTtlView v return new CommandState { Result = new ShellJson(jsonDoc.RootElement.Clone()), - RenderUser = () => ShellInterpreter.WriteLine(MessageService.GetArgsString( + RenderUser = () => ShellInterpreter.Instance.Output.WriteLine(ShellMessageKind.Result, MessageService.GetArgsString( "command-ttl-status-" + StatusFor(view.DefaultTimeToLive), "container", containerName, @@ -160,7 +160,7 @@ private static CommandState BuildAnalyticalResult(string containerName, Containe return new CommandState { Result = new ShellJson(jsonDoc.RootElement.Clone()), - RenderUser = () => ShellInterpreter.WriteLine(MessageService.GetArgsString( + RenderUser = () => ShellInterpreter.Instance.Output.WriteLine(ShellMessageKind.Result, MessageService.GetArgsString( view.AnalyticalTimeToLiveSeconds is null or 0 ? "command-ttl-analytical-status-disabled" : view.AnalyticalTimeToLiveSeconds == -1 diff --git a/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/CommandRunner.cs b/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/CommandRunner.cs index 16b90f1a..f9c5ad45 100644 --- a/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/CommandRunner.cs +++ b/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/CommandRunner.cs @@ -42,6 +42,17 @@ internal bool IsExternal(string v) return false; } + /// + /// Removes every command matching , including all of its aliases. + /// + internal void RemoveCommands(Func predicate) + { + foreach (var name in this.Commands.Where(entry => predicate(entry.Value)).Select(entry => entry.Key).ToList()) + { + this.Commands.Remove(name); + } + } + internal bool IsOptionPrefix(string? currentCommand, string name) { if (currentCommand == null) diff --git a/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/OutputPolicy.cs b/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/OutputPolicy.cs index b778ad9d..dadfb6b0 100644 --- a/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/OutputPolicy.cs +++ b/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/OutputPolicy.cs @@ -14,19 +14,20 @@ namespace Azure.Data.Cosmos.Shell.Core; internal static class OutputPolicy { // Command code presents results only for interactive users. Machine-mode results are - // emitted once by the interpreter through ShellOutput.WriteResult. - internal static bool ShouldPresent(ShellMessageKind kind, bool quiet, bool machineMode) + // emitted once by the interpreter through ShellOutput.WriteResult; MCP stdio returns + // them in protocol responses. + internal static bool ShouldPresent(ShellMessageKind kind, bool quiet, bool stdio, bool machineMode) => kind switch { - ShellMessageKind.Information or ShellMessageKind.Progress => !quiet && !machineMode, - ShellMessageKind.Result => !machineMode, + ShellMessageKind.Information or ShellMessageKind.Progress => !quiet && !machineMode && !stdio, + ShellMessageKind.Result => !stdio && !machineMode, ShellMessageKind.Warning or ShellMessageKind.Error or ShellMessageKind.RequiredInstruction => true, _ => throw new ArgumentOutOfRangeException(nameof(kind)), }; // Interactive confirmation prompts stay on the terminal even when 2> is active. - internal static bool UseStandardError(ShellMessageKind kind, bool machineMode, bool errorRedirected = false) - => (machineMode && kind is ShellMessageKind.Warning or ShellMessageKind.Error or ShellMessageKind.RequiredInstruction) + internal static bool UseStandardError(ShellMessageKind kind, bool machineMode, bool stdio, bool errorRedirected = false) + => stdio || (machineMode && kind is ShellMessageKind.Warning or ShellMessageKind.Error or ShellMessageKind.RequiredInstruction) || (errorRedirected && kind is ShellMessageKind.Warning or ShellMessageKind.Error); /// diff --git a/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ShellInterpreter.cs b/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ShellInterpreter.cs index c4a34825..8d23f331 100644 --- a/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ShellInterpreter.cs +++ b/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ShellInterpreter.cs @@ -35,11 +35,6 @@ public partial class ShellInterpreter : IDisposable private const string SessionRequestChargeWarningThresholdVariable = "sessionRequestChargeWarningThreshold"; - // Declared before Instance: static initializers run in order and the constructor reads history. - private static readonly object HistoryFileLock = new(); - - internal static readonly ShellInterpreter Instance = new(); - private const int MAXHISTORYITEMS = 60; private const int HistoryFileOpenRetryCount = 10; @@ -58,10 +53,16 @@ public partial class ShellInterpreter : IDisposable // user command that just happens to start with the prefix string. private const string EncodedHistoryLineMarker = "E:"; + private static readonly object HistoryFileLock = new(); + + private static readonly Lazy SharedInstance = new(() => new ShellInterpreter(historyEnabled: !stdioStartup)); + private static readonly TimeSpan HistoryFileOpenRetryDelay = TimeSpan.FromMilliseconds(25); private static CancellationTokenSource? currentTokenSource; + private static bool stdioStartup; + private readonly string cfgPath; private readonly string welcomeMarkerFile; @@ -119,13 +120,14 @@ public partial class ShellInterpreter : IDisposable private bool sessionRequestChargeWarningIssued; private long sessionRequestChargeGeneration; - internal ShellInterpreter(string? configPath = null) + internal ShellInterpreter(string? configPath = null, bool historyEnabled = true) { this.State = new DisconnectedState(); this.errorRedirectWriter = new ErrorRedirectWriter(this); this.Output = new ShellOutput( () => this.Options?.Quiet == true, - () => this.IsMachineMode, + () => this.IsMcpStdio, + () => stdioStartup || this.IsMachineMode, standardError: () => this.ErrOutRedirect != null ? this.errorRedirectWriter : Console.Error, errorRedirected: () => this.ErrOutRedirect != null); @@ -144,27 +146,30 @@ internal ShellInterpreter(string? configPath = null) this.HistoryFile = Path.Join(this.cfgPath, "cmd_history"); this.welcomeMarkerFile = Path.Join(this.cfgPath, "welcome_seen"); - try + if (historyEnabled) { - List entries = []; - lock (HistoryFileLock) + try { - if (File.Exists(this.HistoryFile)) + List entries = []; + lock (HistoryFileLock) { - using var stream = this.OpenHistoryFileWithExclusiveLock(FileAccess.Read); - entries = ReadHistoryEntries(stream); + if (File.Exists(this.HistoryFile)) + { + using var stream = this.OpenHistoryFileWithExclusiveLock(FileAccess.Read); + entries = ReadHistoryEntries(stream); + } } - } - foreach (var entry in entries) + foreach (var entry in entries) + { + this.RecordHistoryEntry(entry, persist: false); + } + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { - this.RecordHistoryEntry(entry, persist: false); + System.Diagnostics.Debug.WriteLine(ex); } } - catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) - { - System.Diagnostics.Debug.WriteLine(ex); - } Console.CancelKeyPress += this.Console_CancelKeyPress; this.editorCancelTokenSource = new CancellationTokenSource(); @@ -172,8 +177,16 @@ internal ShellInterpreter(string? configPath = null) internal event Action? LocationChanged; + internal static ShellInterpreter Instance => SharedInstance.Value; + internal ShellOutput Output { get; } + /// + /// Gets a value indicating whether the shell runs as a headless MCP stdio server, + /// including during startup before options are applied. + /// + internal bool IsMcpStdio => stdioStartup || this.Options?.McpStdio == true; + /// /// Gets the line editor instance used by the shell, or null if not available. /// @@ -424,14 +437,16 @@ internal State State /// interactive rendering (friendly views, ANSI colors, banners) is suppressed in /// favor of deterministic structured output. Machine mode is entered via /// --quiet, a structured output format (--output json or --output csv), - /// or an execute-and-quit (-c) invocation. The human-facing table and + /// a headless --mcp-stdio server, or an execute-and-quit (-c) invocation. The human-facing table and /// user formats are not machine mode. See . /// - internal bool IsMachineMode => OutputPolicy.IsMachineMode( + internal bool IsMachineMode => this.Options?.McpStdio == true || OutputPolicy.IsMachineMode( this.Options?.Output, this.Options?.Quiet == true, !string.IsNullOrWhiteSpace(this.Options?.ExecuteAndQuit)); + internal bool McpConfirmationApproved { get; set; } + /// /// Gets the session default , resolved from the global /// --output option and then the COSMOSDB_SHELL_FORMAT environment variable. @@ -462,6 +477,19 @@ internal OutputFormat DefaultOutputFormat } } + /// + /// Disables history loading before the shared stdio interpreter is constructed. + /// + internal static void ConfigureStdioStartup() + { + if (SharedInstance.IsValueCreated) + { + throw new InvalidOperationException("Stdio mode must be configured before creating the shell interpreter."); + } + + stdioStartup = true; + } + /// /// Creates a new shell interpreter instance. /// @@ -528,6 +556,16 @@ public static bool Confirm(string message, ShellInterpreter? shell = null) internal static bool Confirm(string message, ShellInterpreter shell, Func readKey) { + if (shell.Options?.McpStdio == true) + { + if (shell.McpConfirmationApproved) + { + return true; + } + + throw new CommandException("confirm", MessageService.GetString("mcp-error-stdio-console-input")); + } + using var pause = shell.PauseOperationTimeout(); var yes = char.ToUpper(MessageService.GetString("yes_char")[0]); var no = char.ToUpper(MessageService.GetString("no_char")[0]); @@ -1099,34 +1137,39 @@ internal void PrintVersion(CommandState? commandState) { var version = GetDisplayVersion(typeof(VersionCommand).Assembly); var port = this.McpPort; + var stdio = this.Options?.McpStdio == true; var repoUrl = GetRepositoryUrl(typeof(VersionCommand).Assembly); if (commandState == null) { - RenderVersionBanner(this.Output, ShellMessageKind.Information, version, port, repoUrl); + RenderVersionBanner(this.Output, ShellMessageKind.Information, version, port, repoUrl, stdio); return; } var json = new Dictionary { ["version"] = version, - ["mcpEnabled"] = port != null, + ["mcpEnabled"] = port != null || stdio, ["mcpPort"] = port, // will be null if not enabled - ["mcpStatus"] = port != null ? "on" : "off", + ["mcpStatus"] = port != null || stdio ? "on" : "off", ["repository"] = repoUrl, }; var jsonElement = System.Text.Json.JsonSerializer.SerializeToElement(json); commandState.Result = new ShellJson(jsonElement); - commandState.RenderUser = () => RenderVersionBanner(this.Output, ShellMessageKind.Result, version, port, repoUrl); + commandState.RenderUser = () => RenderVersionBanner(this.Output, ShellMessageKind.Result, version, port, repoUrl, stdio); } - private static void RenderVersionBanner(ShellOutput output, ShellMessageKind kind, string version, int? port, string repoUrl) + private static void RenderVersionBanner(ShellOutput output, ShellMessageKind kind, string version, int? port, string repoUrl, bool stdio) { var versionString = MessageService.GetArgsString("command-version", "version", version); output.MarkupLine(kind, versionString); - if (port != null) + if (stdio) + { + output.MarkupLine(kind, Theme.FormatWarning(MessageService.GetString("command-version-mcp-stdio"))); + } + else if (port != null) { var mcpPortString = MessageService.GetArgsString("command-version-mcp", "mcp_port", port?.ToString() ?? string.Empty); output.MarkupLine(kind, Theme.FormatWarning(mcpPortString)); @@ -1673,34 +1716,42 @@ internal async Task ConnectAsync(string connectionString, string? loginHint = nu // which has its own dedicated step below and honors --tenant there. if (client == null && credentialMethod != CredentialMethod.AzureCli && (!string.IsNullOrWhiteSpace(tenantId) || !string.IsNullOrWhiteSpace(loginHint))) { - var browserOptions = new InteractiveBrowserCredentialOptions + if (AllowsInteractiveBrowser(this.IsMcpStdio)) { - RedirectUri = new Uri(ConnectCommand.EntraRedirectUrl), - }; - if (!string.IsNullOrWhiteSpace(tenantId)) - { - browserOptions.TenantId = tenantId; - } + var browserOptions = new InteractiveBrowserCredentialOptions + { + RedirectUri = new Uri(ConnectCommand.EntraRedirectUrl), + }; + if (!string.IsNullOrWhiteSpace(tenantId)) + { + browserOptions.TenantId = tenantId; + } - if (!string.IsNullOrWhiteSpace(loginHint)) - { - browserOptions.LoginHint = loginHint; - } + if (!string.IsNullOrWhiteSpace(loginHint)) + { + browserOptions.LoginHint = loginHint; + } - if (authorityHostUri != null) - { - browserOptions.AuthorityHost = authorityHostUri; - } + if (authorityHostUri != null) + { + browserOptions.AuthorityHost = authorityHostUri; + } - WriteLine(MessageService.GetString("shell-connect-browser-auth")); - var browserCredential = new InteractiveBrowserCredential(browserOptions); - if (await this.TryConnectWithTokenCredentialAsync(tokenEndpoint, browserCredential, options, subscriptionId, resourceGroupName, authorityHostUri, allowCredentialFallback: true, token)) + WriteLine(MessageService.GetString("shell-connect-browser-auth")); + var browserCredential = new InteractiveBrowserCredential(browserOptions); + if (await this.TryConnectWithTokenCredentialAsync(tokenEndpoint, browserCredential, options, subscriptionId, resourceGroupName, authorityHostUri, allowCredentialFallback: true, token)) + { + return; + } + + // Browser auth failed; fall back to device code. + WriteLine(MessageService.GetString("shell-connect-devicecode-fallback")); + } + else { - return; + this.Output.WriteLine(ShellMessageKind.RequiredInstruction, MessageService.GetString("shell-connect-devicecode-stdio")); } - // Browser auth failed; fall back to device code. - WriteLine(MessageService.GetString("shell-connect-devicecode-fallback")); var deviceCodeOptions = new DeviceCodeCredentialOptions { DeviceCodeCallback = (code, cancellationToken) => @@ -1755,15 +1806,7 @@ internal async Task ConnectAsync(string connectionString, string? loginHint = nu if (client == null) { WriteLine(MessageService.GetString("shell-connect-default-auth")); - var dacOptions = new DefaultAzureCredentialOptions - { - ExcludeInteractiveBrowserCredential = false, - }; - if (authorityHostUri != null) - { - dacOptions.AuthorityHost = authorityHostUri; - } - + var dacOptions = CreateDefaultCredentialOptions(authorityHostUri, AllowsInteractiveBrowser(this.IsMcpStdio)); var dacCredential = new DefaultAzureCredential(dacOptions); // CodeQL [SM05137] Interactive developer CLI, not a hosted service: this is the last-resort fallback that adopts the developer's local identity (Azure CLI/azd, Visual Studio, env vars, or VM managed identity). No fixed service identity exists to pin to. await this.TryConnectWithTokenCredentialAsync(tokenEndpoint, dacCredential, options, subscriptionId, resourceGroupName, authorityHostUri, allowCredentialFallback: false, token); } @@ -2272,6 +2315,11 @@ private static int GetConsoleWidth() internal void PrintCommand(string cmdString) { + if (this.Options?.McpStdio == true) + { + return; + } + // Print the shell prompt similar to how it appears when typing command // AnsiConsole.Markup(new CosmosShellPrompt(this).GetPromptString()); // AnsiConsole.Write(" "); @@ -2888,6 +2936,30 @@ protected virtual void Dispose(bool disposing) return Console.ReadLine(); } + /// + /// Determines whether a sign-in may open a browser. A headless MCP stdio server has + /// no user at the terminal, and the platform browser launcher (for example + /// xdg-open) inherits the process stdout that carries the MCP protocol. + /// + /// Whether the shell runs as an MCP stdio server. + /// when interactive browser sign-in is allowed. + internal static bool AllowsInteractiveBrowser(bool mcpStdio) => !mcpStdio; + + internal static DefaultAzureCredentialOptions CreateDefaultCredentialOptions(Uri? authorityHost, bool allowInteractiveBrowser) + { + var options = new DefaultAzureCredentialOptions + { + ExcludeInteractiveBrowserCredential = !allowInteractiveBrowser, + ExcludeBrokerCredential = !allowInteractiveBrowser, + }; + if (authorityHost != null) + { + options.AuthorityHost = authorityHost; + } + + return options; + } + internal static CosmosClientOptions CreateClientOptions(ConnectionMode requestedMode, bool isEmulator = false) { var options = new CosmosClientOptions diff --git a/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ShellOutput.cs b/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ShellOutput.cs index cf8cc3ef..311c9f01 100644 --- a/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ShellOutput.cs +++ b/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/ShellOutput.cs @@ -19,6 +19,7 @@ internal enum ShellMessageKind internal sealed class ShellOutput( Func quiet, + Func stdio, Func machineMode, Func? standardOutput = null, Func? standardError = null, @@ -32,15 +33,15 @@ internal sealed class ShellOutput( private IAnsiConsole? cachedPlainConsole; // Early failures and terminal initialization diagnostics always use stderr. - internal static ShellOutput StandardError { get; } = new(() => false, () => true); + internal static ShellOutput StandardError { get; } = new(() => false, () => false, () => true); /// - /// Clears the interactive terminal. Machine mode has no screen to clear, + /// Clears the interactive terminal. Machine mode and MCP stdio have no screen to clear, /// and emitting terminal control sequences there would corrupt their output streams. /// internal void ClearScreen() { - if (!machineMode()) + if (!machineMode() && !stdio()) { (console?.Invoke() ?? AnsiConsole.Console).Clear(); } @@ -49,11 +50,14 @@ internal void ClearScreen() /// /// Writes the interpreter's final, already formatted command result. Unlike /// presentation, this is the machine-mode - /// stdout contract. + /// stdout contract; MCP stdio returns results through the protocol instead. /// internal void WriteResult(string text) { - (standardOutput?.Invoke() ?? Console.Out).WriteLine(text); + if (!stdio()) + { + (standardOutput?.Invoke() ?? Console.Out).WriteLine(text); + } } internal void WriteLine(ShellMessageKind kind, string message = "", params object[] args) @@ -172,7 +176,7 @@ internal void WriteException(ShellMessageKind kind, Exception exception, Excepti { if (this.ShouldPresent(kind)) { - if (machineMode()) + if (machineMode() || stdio()) { this.GetWriter(kind).WriteLine(exception); } @@ -184,10 +188,10 @@ internal void WriteException(ShellMessageKind kind, Exception exception, Excepti } private bool ShouldPresent(ShellMessageKind kind) - => OutputPolicy.ShouldPresent(kind, quiet(), machineMode()); + => OutputPolicy.ShouldPresent(kind, quiet(), stdio(), machineMode()); private bool UseStandardError(ShellMessageKind kind) - => OutputPolicy.UseStandardError(kind, machineMode(), errorRedirected?.Invoke() == true); + => OutputPolicy.UseStandardError(kind, machineMode(), stdio(), errorRedirected?.Invoke() == true); private TextWriter GetWriter(ShellMessageKind kind) => this.UseStandardError(kind) @@ -196,7 +200,7 @@ private TextWriter GetWriter(ShellMessageKind kind) private IAnsiConsole GetConsole(ShellMessageKind kind) { - if (!machineMode() && !this.UseStandardError(kind)) + if (!machineMode() && !stdio() && !this.UseStandardError(kind)) { return console?.Invoke() ?? AnsiConsole.Console; } diff --git a/CosmosDBShell/Azure.Data.Cosmos.Shell.Mcp/LocationResourceSubscriptions.cs b/CosmosDBShell/Azure.Data.Cosmos.Shell.Mcp/LocationResourceSubscriptions.cs index e038769f..26bf7b0f 100644 --- a/CosmosDBShell/Azure.Data.Cosmos.Shell.Mcp/LocationResourceSubscriptions.cs +++ b/CosmosDBShell/Azure.Data.Cosmos.Shell.Mcp/LocationResourceSubscriptions.cs @@ -39,9 +39,16 @@ internal sealed class LocationResourceSubscriptions : BackgroundService private readonly ILogger logger; - public LocationResourceSubscriptions(ILogger logger, IHostApplicationLifetime? lifetime = null) + private readonly bool isStdio; + + private ModelContextProtocol.Server.McpServer? stdioServer; + + private bool stdioSubscribed; + + public LocationResourceSubscriptions(ILogger logger, IHostApplicationLifetime? lifetime = null, bool isStdio = false) { this.logger = logger; + this.isStdio = isStdio; this.stoppingRegistration = lifetime?.ApplicationStopping.Register(this.stopping.Cancel) ?? default; ShellInterpreter.Instance.LocationChanged += this.OnLocationChanged; } @@ -52,7 +59,7 @@ internal int SubscriberCount { lock (this.sync) { - return this.subscribedSessionIds.Count; + return this.subscribedSessionIds.Count + (this.stdioSubscribed ? 1 : 0); } } } @@ -103,9 +110,20 @@ public async Task RunSessionAsync(ModelContextProtocol.Server.McpServer server, } } - public void Subscribe(string? sessionId, string uri) + public void Subscribe(ModelContextProtocol.Server.McpServer server, string uri) { ValidateUri(uri); + lock (this.sync) + { + if (this.isStdio) + { + this.stdioServer = server; + this.stdioSubscribed = true; + return; + } + } + + var sessionId = server.SessionId; if (string.IsNullOrEmpty(sessionId)) { throw new McpProtocolException( @@ -122,9 +140,20 @@ public void Subscribe(string? sessionId, string uri) } } - public void Unsubscribe(string? sessionId, string uri) + public void Unsubscribe(ModelContextProtocol.Server.McpServer server, string uri) { ValidateUri(uri); + lock (this.sync) + { + if (this.isStdio) + { + this.stdioSubscribed = false; + this.stdioServer = null; + return; + } + } + + var sessionId = server.SessionId; if (string.IsNullOrEmpty(sessionId)) { return; @@ -205,6 +234,12 @@ public async ValueTask ListenAsync(RequestContext this.sessions.TryGetValue(sessionId, out var server) ? server : null) .OfType() .ToArray(); + if (this.stdioSubscribed && this.stdioServer is not null) + { + servers = [.. servers, this.stdioServer]; + } + foreach (var stream in this.listenStreams) { stream.Updates.Writer.TryWrite(true); diff --git a/CosmosDBShell/Azure.Data.Cosmos.Shell.Mcp/McpServer.cs b/CosmosDBShell/Azure.Data.Cosmos.Shell.Mcp/McpServer.cs index 9234d3e2..84e30648 100644 --- a/CosmosDBShell/Azure.Data.Cosmos.Shell.Mcp/McpServer.cs +++ b/CosmosDBShell/Azure.Data.Cosmos.Shell.Mcp/McpServer.cs @@ -21,8 +21,7 @@ namespace Azure.Data.Cosmos.Shell.Mcp; using static Program; /// -/// MCP Server implementation for running shell commands via HTTP. -/// Provides a local HTTP endpoint that accepts command execution requests. +/// MCP Server implementation for running shell commands via HTTP or stdio. /// SECURITY NOTE: This server is designed to run locally only and should not be exposed to external networks. /// internal class McpServer @@ -32,7 +31,7 @@ internal class McpServer public static IHost CreateHost(CosmosShellOptions serverArguments) { var builder = WebApplication.CreateBuilder([]); - ConfigureMcpServer(builder.Services); + ConfigureMcpServer(builder.Services).WithHttpTransport(ConfigureHttpTransport); builder.WebHost .ConfigureKestrel(server => { @@ -52,12 +51,31 @@ public static IHost CreateHost(CosmosShellOptions serverArguments) return application; } - private static void ConfigureMcpServer(IServiceCollection services) + public static IHost CreateStdioHost(Stream input, Stream output) + { + var builder = Host.CreateApplicationBuilder(new HostApplicationBuilderSettings + { + Args = [], + DisableDefaults = true, + }); + builder.Logging.AddConsole(options => options.LogToStandardErrorThreshold = LogLevel.Trace); + builder.Logging.SetMinimumLevel(LogLevel.Warning); + var protocolInput = new StdioInputStream(input); + ConfigureMcpServer(builder.Services, stdio: true).WithStreamServerTransport(protocolInput, output); + var host = builder.Build(); + protocolInput.HostLifetime = host.Services.GetRequiredService(); + return host; + } + + private static IMcpServerBuilder ConfigureMcpServer(IServiceCollection services, bool stdio = false) { services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); - services.AddSingleton(); + services.AddSingleton(services => new LocationResourceSubscriptions( + services.GetRequiredService>(), + services.GetRequiredService(), + stdio)); services.AddHostedService(services => services.GetRequiredService()); services.AddOptions() .Configure((mcpServerOptions, toolOperations, locationSubscriptions) => @@ -93,8 +111,7 @@ private static void ConfigureMcpServer(IServiceCollection services) }); // SDK resource collections advertise list changes even when configured otherwise. - var mcpServerBuilder = services.AddMcpServer(); - mcpServerBuilder.WithHttpTransport(ConfigureHttpTransport); + return services.AddMcpServer(); } internal static void ConfigureHttpTransport(HttpServerTransportOptions options) diff --git a/CosmosDBShell/Azure.Data.Cosmos.Shell.Mcp/StdioInputStream.cs b/CosmosDBShell/Azure.Data.Cosmos.Shell.Mcp/StdioInputStream.cs new file mode 100644 index 00000000..34a6aba1 --- /dev/null +++ b/CosmosDBShell/Azure.Data.Cosmos.Shell.Mcp/StdioInputStream.cs @@ -0,0 +1,82 @@ +// ------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +// ------------------------------------------------------------ + +namespace Azure.Data.Cosmos.Shell.Mcp; + +using Microsoft.Extensions.Hosting; + +internal sealed class StdioInputStream(Stream input) : Stream +{ + public IHostApplicationLifetime? HostLifetime { get; set; } + + public override bool CanRead => input.CanRead; + + public override bool CanSeek => false; + + public override bool CanWrite => false; + + public override long Length => throw new NotSupportedException(); + + public override long Position + { + get => throw new NotSupportedException(); + set => throw new NotSupportedException(); + } + + public override int Read(byte[] buffer, int offset, int count) + { + var read = input.Read(buffer, offset, count); + this.ObserveRead(read, count); + return read; + } + + public override int Read(Span buffer) + { + var read = input.Read(buffer); + this.ObserveRead(read, buffer.Length); + return read; + } + + public override async Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + { + var read = await input.ReadAsync(buffer, offset, count, cancellationToken).ConfigureAwait(false); + this.ObserveRead(read, count); + return read; + } + + public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + var read = await input.ReadAsync(buffer, cancellationToken).ConfigureAwait(false); + this.ObserveRead(read, buffer.Length); + return read; + } + + public override void Flush() => throw new NotSupportedException(); + + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + + public override void SetLength(long value) => throw new NotSupportedException(); + + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + + protected override void Dispose(bool disposing) + { + if (disposing) + { + input.Dispose(); + } + + base.Dispose(disposing); + } + + private void ObserveRead(int read, int requested) + { + if (read == 0 && requested > 0) + { + // RunAsync can await open subscription handlers after EOF, so shutdown cannot wait for RunAsync. + var lifetime = this.HostLifetime ?? throw new InvalidOperationException("The stdio host lifetime has not been configured."); + lifetime.StopApplication(); + } + } +} diff --git a/CosmosDBShell/Azure.Data.Cosmos.Shell.Mcp/StdioStartupInput.cs b/CosmosDBShell/Azure.Data.Cosmos.Shell.Mcp/StdioStartupInput.cs new file mode 100644 index 00000000..21ca3e70 --- /dev/null +++ b/CosmosDBShell/Azure.Data.Cosmos.Shell.Mcp/StdioStartupInput.cs @@ -0,0 +1,344 @@ +// ------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +// ------------------------------------------------------------ + +namespace Azure.Data.Cosmos.Shell.Mcp; + +using System.IO.Pipelines; +using Azure.Data.Cosmos.Shell.Util; + +internal sealed class StdioStartupInput : IDisposable +{ + internal const int MaximumStartupBufferBytes = 8 * 1024 * 1024; + internal static readonly TimeSpan StartupTimeout = TimeSpan.FromSeconds(60); + + private readonly Stream input; + private readonly Pipe liveBuffer = new(); + private readonly string startupBufferPath = Path.Join(Path.GetTempPath(), $"cosmos-stdio-{Guid.NewGuid():N}.tmp"); + private readonly FileStream startupBuffer; + private readonly SemaphoreSlim startupBufferLock = new(1, 1); + private readonly TaskCompletionSource startupBufferReady = + new(TaskCreationOptions.RunContinuationsAsynchronously); + + private readonly CancellationTokenSource stopping = new(); + private readonly CancellationTokenSource inputEnded = new(); + private readonly CancellationTokenSource deadline = new(); + private readonly CancellationTokenSource startupCancellation; + private readonly Timer deadlineTimer; + private Task pump = Task.CompletedTask; + + private Exception? inputError; + private bool startupBufferCompleted; + private int startupTermination; + private int disposed; + + public StdioStartupInput(Stream input, TimeSpan? timeout = null) + { + this.input = input; + var bufferOptions = new FileStreamOptions + { + Mode = FileMode.CreateNew, + Access = FileAccess.ReadWrite, + Share = FileShare.None, + Options = FileOptions.Asynchronous | FileOptions.SequentialScan | FileOptions.DeleteOnClose, + }; + if (!OperatingSystem.IsWindows()) + { + bufferOptions.UnixCreateMode = UnixFileMode.UserRead | UnixFileMode.UserWrite; + } + + this.startupBuffer = new FileStream(this.startupBufferPath, bufferOptions); + this.Input = new StartupBufferedStream( + this.startupBufferReady.Task, + this.liveBuffer.Reader.AsStream()); + this.startupCancellation = CancellationTokenSource.CreateLinkedTokenSource( + this.inputEnded.Token, this.deadline.Token); + this.StartupToken = this.startupCancellation.Token; + this.deadlineTimer = new Timer( + static state => ((StdioStartupInput)state!).CancelForTimeout(), + this, + timeout ?? StartupTimeout, + Timeout.InfiniteTimeSpan); + } + + private enum StartupTermination + { + None, + TimedOut, + InputEnded, + InputError, + } + + public Stream Input { get; } + + internal string StartupBufferPath => this.startupBufferPath; + + public CancellationToken StartupToken { get; } + + public Exception? InputError => Volatile.Read(ref this.startupTermination) == (int)StartupTermination.InputError + ? Volatile.Read(ref this.inputError) + : null; + + public bool TimedOut => Volatile.Read(ref this.startupTermination) == (int)StartupTermination.TimedOut; + + public void Start() => this.pump = this.PumpAsync(); + + public async Task CompleteStartupAsync() + { + this.deadlineTimer.Change(Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan); + await this.CompleteStartupBufferAsync().ConfigureAwait(false); + } + + public void Dispose() + { + if (Interlocked.Exchange(ref this.disposed, 1) != 0) + { + return; + } + + var timerStopped = this.deadlineTimer.DisposeAsync().AsTask(); + this.stopping.Cancel(); + + // The stdin pump may never unblock. Release the spool independently of its lifetime. + this.startupBufferLock.Wait(); + try + { + this.startupBufferCompleted = true; + this.startupBuffer.Dispose(); + this.startupBufferReady.TrySetCanceled(this.stopping.Token); + } + finally + { + this.startupBufferLock.Release(); + } + + this.Input.Dispose(); + this.input.Dispose(); + + // Console pipe reads may not be interruptible. Do not hold process shutdown + // open waiting for a read. Queued timeout callbacks must also finish before + // their cancellation sources can be disposed. + _ = Task.WhenAll(this.pump, timerStopped).ContinueWith( + _ => + { + this.startupCancellation.Dispose(); + this.deadline.Dispose(); + this.inputEnded.Dispose(); + this.stopping.Dispose(); + this.startupBufferLock.Dispose(); + }, + CancellationToken.None, + TaskContinuationOptions.ExecuteSynchronously, + TaskScheduler.Default); + } + + private async Task PumpAsync() + { + Exception? error = null; + try + { + var bytes = new byte[64 * 1024]; + while (true) + { + var read = await this.input.ReadAsync(bytes, this.stopping.Token).ConfigureAwait(false); + if (read == 0) + { + break; + } + + await this.startupBufferLock.WaitAsync(this.stopping.Token).ConfigureAwait(false); + try + { + if (!this.startupBufferCompleted) + { + if (this.startupBuffer.Length > MaximumStartupBufferBytes - read) + { + throw new IOException(MessageService.GetString("mcp-error-stdio-startup-buffer-limit")); + } + + await this.startupBuffer.WriteAsync( + bytes.AsMemory(0, read), + this.stopping.Token).ConfigureAwait(false); + continue; + } + } + finally + { + this.startupBufferLock.Release(); + } + + await this.liveBuffer.Writer.WriteAsync( + bytes.AsMemory(0, read), + this.stopping.Token).ConfigureAwait(false); + } + } + catch (OperationCanceledException) when (this.stopping.IsCancellationRequested) + { + // Disposal cancels the input pump; the pipe is completed in the finally block. + } + catch (Exception ex) + { + error = ex; + Volatile.Write(ref this.inputError, ex); + Interlocked.CompareExchange( + ref this.startupTermination, + (int)StartupTermination.InputError, + (int)StartupTermination.None); + } + finally + { + await this.CompleteStartupBufferAsync().ConfigureAwait(false); + await this.liveBuffer.Writer.CompleteAsync(error).ConfigureAwait(false); + if (!this.stopping.IsCancellationRequested) + { + Interlocked.CompareExchange( + ref this.startupTermination, + (int)StartupTermination.InputEnded, + (int)StartupTermination.None); + await this.inputEnded.CancelAsync().ConfigureAwait(false); + } + } + } + + private async Task CompleteStartupBufferAsync() + { + await this.startupBufferLock.WaitAsync().ConfigureAwait(false); + try + { + if (this.startupBufferCompleted) + { + return; + } + + await this.startupBuffer.FlushAsync().ConfigureAwait(false); + this.startupBuffer.Position = 0; + this.startupBufferCompleted = true; + if (!this.startupBufferReady.TrySetResult(this.startupBuffer)) + { + await this.startupBuffer.DisposeAsync().ConfigureAwait(false); + } + } + finally + { + this.startupBufferLock.Release(); + } + } + + private void CancelForTimeout() + { + if (Interlocked.CompareExchange( + ref this.startupTermination, + (int)StartupTermination.TimedOut, + (int)StartupTermination.None) == (int)StartupTermination.None) + { + this.deadline.Cancel(); + } + } + + private sealed class StartupBufferedStream(Task startupBuffer, Stream liveInput) : Stream + { + private Stream? prefix; + private bool prefixCompleted; + + public override bool CanRead => true; + + public override bool CanSeek => false; + + public override bool CanWrite => false; + + public override long Length => throw new NotSupportedException(); + + public override long Position + { + get => throw new NotSupportedException(); + set => throw new NotSupportedException(); + } + + public override void Flush() + { + } + +#pragma warning disable VSTHRD002 // Synchronously waiting is required by the Stream.Read contract. + public override int Read(byte[] buffer, int offset, int count) + { + ArgumentNullException.ThrowIfNull(buffer); + ArgumentOutOfRangeException.ThrowIfNegative(offset); + ArgumentOutOfRangeException.ThrowIfNegative(count); + if (buffer.Length - offset < count) + { + throw new ArgumentException("Offset and count exceed the buffer bounds."); + } + + if (count == 0) + { + return 0; + } + + if (!this.prefixCompleted) + { + this.prefix ??= startupBuffer.GetAwaiter().GetResult(); + var read = this.prefix.Read(buffer, offset, count); + if (read > 0) + { + return read; + } + + this.prefixCompleted = true; + this.prefix.Dispose(); + } + + return liveInput.Read(buffer, offset, count); + } +#pragma warning restore VSTHRD002 + + public override async ValueTask ReadAsync( + Memory buffer, + CancellationToken cancellationToken = default) + { + if (buffer.IsEmpty) + { + return 0; + } + + if (!this.prefixCompleted) + { + this.prefix ??= await startupBuffer.WaitAsync(cancellationToken).ConfigureAwait(false); + var read = await this.prefix.ReadAsync(buffer, cancellationToken).ConfigureAwait(false); + if (read > 0) + { + return read; + } + + this.prefixCompleted = true; + await this.prefix.DisposeAsync().ConfigureAwait(false); + } + + return await liveInput.ReadAsync(buffer, cancellationToken).ConfigureAwait(false); + } + + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + + public override void SetLength(long value) => throw new NotSupportedException(); + + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + + protected override void Dispose(bool disposing) + { + if (disposing) + { + this.prefix?.Dispose(); + liveInput.Dispose(); + if (this.prefix is null) + { + _ = startupBuffer.ContinueWith( + static task => task.Result.Dispose(), + CancellationToken.None, + TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.ExecuteSynchronously, + TaskScheduler.Default); + } + } + + base.Dispose(disposing); + } + } +} diff --git a/CosmosDBShell/Azure.Data.Cosmos.Shell.Mcp/ToolOperations.cs b/CosmosDBShell/Azure.Data.Cosmos.Shell.Mcp/ToolOperations.cs index 497ca5bf..c4741bd7 100644 --- a/CosmosDBShell/Azure.Data.Cosmos.Shell.Mcp/ToolOperations.cs +++ b/CosmosDBShell/Azure.Data.Cosmos.Shell.Mcp/ToolOperations.cs @@ -65,16 +65,23 @@ internal delegate ValueTask ConfirmationPrompt( private ValueTask SubscribeToResourcesAsync(RequestContext context, CancellationToken cancellationToken) { - this.locationSubscriptions.Subscribe(context.Server.SessionId, context.Params?.Uri ?? string.Empty); + this.locationSubscriptions.Subscribe(context.Server, context.Params?.Uri ?? string.Empty); return ValueTask.FromResult(new EmptyResult()); } private ValueTask UnsubscribeFromResourcesAsync(RequestContext context, CancellationToken cancellationToken) { - this.locationSubscriptions.Unsubscribe(context.Server.SessionId, context.Params?.Uri ?? string.Empty); + this.locationSubscriptions.Unsubscribe(context.Server, context.Params?.Uri ?? string.Empty); return ValueTask.FromResult(new EmptyResult()); } + /// + /// Determines whether a command cannot run in MCP stdio mode. + /// + internal static bool IsUnavailableInStdio(CommandFactory command) + => command.IsExternal || command.CommandName == "theme" + || (command.McpRestricted && !RequiresConfirmation(command)); + internal static Tool GetTool(CommandFactory command) { var descriptionParts = new[] { command.Description, command.McpDescription } @@ -746,6 +753,10 @@ private async ValueTask OnCallToolsAsync( }, requestState: ConfirmationRequestState.Create(commandLine, stateVersion)); } + else if (clientCapabilities?.Elicitation != null && server is not null) + { + prompt = (request, _, token) => server.ElicitAsync(request, token); + } return await this.ExecuteToolAsync(command, cmd, commandLine, prompt, cancellationToken, parameters.Params); } @@ -791,6 +802,8 @@ internal async Task ExecuteToolAsync( return McpResponseFactory.CreateError(ContextChangedMessage, shell.State); } + var previousApproval = shell.McpConfirmationApproved; + shell.McpConfirmationApproved = confirmedVersion.HasValue; var previousMcpInvocation = shell.IsMcpInvocation; shell.IsMcpInvocation = true; try @@ -807,11 +820,17 @@ internal async Task ExecuteToolAsync( } finally { + shell.McpConfirmationApproved = previousApproval; shell.IsMcpInvocation = previousMcpInvocation; } }, cancellationToken); } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + this.logger?.LogInformation("MCP command '{Command}' was cancelled.", command.CommandName); + throw; + } catch (Exception ex) { var message = CommandException.GetSummaryMessage(ex); diff --git a/CosmosDBShell/Program.cs b/CosmosDBShell/Program.cs index 411699ac..3ac90033 100644 --- a/CosmosDBShell/Program.cs +++ b/CosmosDBShell/Program.cs @@ -55,6 +55,63 @@ public static async Task Main(string[] args) // accidentally trigger LSP mode. args = NormalizeArguments(args); + var preCommandArgs = TakePreCommandArgs(args); + var directStdioTokens = preCommandArgs.Where(a => a == "--mcp-stdio" + || a.StartsWith("--mcp-stdio=", StringComparison.Ordinal) + || a.StartsWith("--mcp-stdio:", StringComparison.Ordinal)).ToArray(); + bool stdioRequested = directStdioTokens.Length > 0; + var (rootCommand, optionMap) = BuildRootCommand(); + var parseResult = rootCommand.Parse(args.Where((argument, index) => + index >= preCommandArgs.Length + || argument is not ("--help" or "-h" or "-?" or "/?" or "/h" or "--version")).ToArray()); + if (parseResult.Errors.Count > 0 + && (stdioRequested || parseResult.GetResult(optionMap.McpStdio) is { Implicit: false })) + { + WriteErrorLine(System.Text.Json.JsonSerializer.Serialize(new + { + status = "error", + error = string.Join("; ", GetParseErrorMessages(parseResult)), + })); + Environment.ExitCode = ShellExitCode.UsageError; + return; + } + + bool stdioDirectlyEnabled = directStdioTokens.Any(IsDirectlyEnabledMcpStdioToken); + + // Response files are expanded before any protocol-mode early return so a hidden + // stdio request cannot bypass the direct-command-line transport requirement. + if (parseResult.GetValue(optionMap.McpStdio) && !stdioDirectlyEnabled) + { + WriteErrorLine(MessageService.GetString("mcp-error-stdio-response-file")); + Environment.ExitCode = ShellExitCode.UsageError; + return; + } + + using var protocolInput = stdioRequested ? Console.OpenStandardInput() : null; + using var protocolOutput = stdioRequested ? Console.OpenStandardOutput() : null; + if (stdioRequested) + { + ShellInterpreter.ConfigureStdioStartup(); + + // Only the transport may use the original streams; commands cannot consume MCP input. + Console.SetOut(Console.Error); + Console.SetIn(TextReader.Null); + AnsiConsole.Console = AnsiConsole.Create(new AnsiConsoleSettings + { + Ansi = AnsiSupport.No, + ColorSystem = ColorSystemSupport.NoColors, + Interactive = InteractionSupport.No, + Out = new AnsiConsoleOutput(Console.Error), + }); + + if (preCommandArgs.Any(a => a is "--lsp" or "--stdio")) + { + WriteErrorLine(MessageService.GetString("mcp-error-stdio-incompatible-options")); + Environment.ExitCode = ShellExitCode.UsageError; + return; + } + } + // Handle LSP mode early, before any other code can write to stdout. // The LSP protocol requires exclusive access to stdin/stdout. Only // inspect the prefix before -c / -k so that a command tail of literally @@ -77,22 +134,18 @@ public static async Task Main(string[] args) // before -c / -k so that a command tail of literally "--help" or // "--version" (e.g. `-c --help`) is forwarded to the shell command // instead of intercepted here. - var preCommandArgs = TakePreCommandArgs(args); if (preCommandArgs.Any(a => a is "--help" or "-h" or "-?" or "/?" or "/h")) { - ShellInterpreter.Instance.Output.WriteResult(BuildHelpText()); + WriteStartupResult(BuildHelpText(), stdioRequested); return; } if (preCommandArgs.Any(a => a is "--version")) { - WriteVersionHeading(); + WriteVersionHeading(stdioRequested); return; } - var (rootCommand, optionMap) = BuildRootCommand(); - var parseResult = rootCommand.Parse(args); - if (parseResult.Errors.Count > 0) { var outputMode = parseResult.GetValue(optionMap.Output); @@ -100,7 +153,7 @@ public static async Task Main(string[] args) var isNonInteractive = !string.IsNullOrWhiteSpace( parseResult.GetValue(optionMap.ExecuteAndQuit)); - var isMachineMode = OutputPolicy.IsMachineMode(outputMode, quiet, isNonInteractive); + var isMachineMode = stdioRequested || OutputPolicy.IsMachineMode(outputMode, quiet, isNonInteractive); if (isMachineMode) { var errorStrings = GetParseErrorMessages(parseResult); @@ -145,6 +198,7 @@ public static async Task Main(string[] args) ConnectAzureCli = parseResult.GetValue(optionMap.ConnectAzureCli), Database = parseResult.GetValue(optionMap.Database), Container = parseResult.GetValue(optionMap.Container), + McpStdio = parseResult.GetValue(optionMap.McpStdio), StartLspServer = parseResult.GetValue(optionMap.StartLspServer), LspStdio = parseResult.GetValue(optionMap.LspStdio), Verbose = parseResult.GetValue(optionMap.Verbose), @@ -160,6 +214,18 @@ public static async Task Main(string[] args) o.McpPort = mcpValue ?? DefaultMcpPort; } + if (stdioRequested && (!o.McpStdio || o.McpPort.HasValue + || parseResult.GetResult(optionMap.ExecuteAndQuit) is not null + || parseResult.GetResult(optionMap.ExecuteAndContinue) is not null + || o.ClearHistory + || o.StartLspServer + || o.LspStdio)) + { + WriteErrorLine(MessageService.GetString("mcp-error-stdio-incompatible-options")); + Environment.ExitCode = ShellExitCode.UsageError; + return; + } + // --diagnostics supports an optional value: when present without a path, // logging is written to a timestamped file in the config directory. var diagnosticsResult = parseResult.GetResult(optionMap.Diagnostics); @@ -247,7 +313,7 @@ public static async Task Main(string[] args) o.Output = "json"; } - var startupMachineMode = OutputPolicy.IsMachineMode( + var startupMachineMode = o.McpStdio || OutputPolicy.IsMachineMode( o.Output, o.Quiet, !string.IsNullOrWhiteSpace(executeAndQuitCommand)); void WriteStartupError(string message) @@ -305,7 +371,9 @@ void WriteStartupError(string message) if (startupMachineMode) { colorSystemVal = 0; // Force NoColors in machine mode - o.Quiet = true; // Suppress informational messages to keep output clean + + // Stdio diagnostics may use stderr, including device-code login instructions. + o.Quiet = !o.McpStdio || o.Quiet; } AnsiConsole.Profile.Capabilities.ColorSystem = colorSystemVal switch @@ -327,7 +395,7 @@ void WriteStartupError(string message) Ansi = AnsiSupport.No, ColorSystem = ColorSystemSupport.NoColors, Interactive = InteractionSupport.No, - Out = new AnsiConsoleOutput(TextWriter.Null), + Out = new AnsiConsoleOutput(o.McpStdio ? Console.Error : TextWriter.Null), }); } @@ -345,14 +413,20 @@ void WriteStartupError(string message) tracing = TracingBootstrap.Initialize(o.OtlpEndpoint); } + using var startupInput = o.McpStdio && o.ConnectionString != null + ? new StdioStartupInput(protocolInput!) + : null; + if (o.ConnectionString != null) { using var connectTokenSource = ShellInterpreter.UserCancellationTokenSource; - var connectToken = connectTokenSource.Token; + using var startupConnectCancellation = CancellationTokenSource.CreateLinkedTokenSource( + connectTokenSource.Token, startupInput?.StartupToken ?? CancellationToken.None); + var connectToken = startupConnectCancellation.Token; try { var credentialMethod = ShellInterpreter.ResolveCredentialMethod(o.ConnectVSCodeCredential, o.ConnectAzureCli); - await ShellInterpreter.Instance.ConnectAsync( + var connectTask = ShellInterpreter.Instance.ConnectAsync( o.ConnectionString, o.ConnectHint, o.ConnectionMode, @@ -363,16 +437,21 @@ await ShellInterpreter.Instance.ConnectAsync( subscriptionId: o.ConnectSubscription, resourceGroupName: o.ConnectResourceGroup, token: connectToken); + + // Preserve connection argument validation even when stdin is already closed. + startupInput?.Start(); + await connectTask; } catch (OperationCanceledException) when (connectToken.IsCancellationRequested) { + ReportStdioStartupCancellation(startupInput, WriteStartupError); return; } catch (Exception ex) { Environment.ExitCode = ShellExitCode.FromException(ex); - var inMachineMode = OutputPolicy.IsMachineMode( + var inMachineMode = o.McpStdio || OutputPolicy.IsMachineMode( o.Output, o.Quiet, !string.IsNullOrWhiteSpace(o.ExecuteAndQuit)); if (!inMachineMode @@ -402,8 +481,10 @@ await ShellInterpreter.Instance.ConnectAsync( if (o.Database != null) { - var navigationTokenSource = ShellInterpreter.UserCancellationTokenSource; - var navigationToken = navigationTokenSource.Token; + using var navigationTokenSource = ShellInterpreter.UserCancellationTokenSource; + using var startupNavigationCancellation = CancellationTokenSource.CreateLinkedTokenSource( + navigationTokenSource.Token, startupInput?.StartupToken ?? CancellationToken.None); + var navigationToken = startupNavigationCancellation.Token; try { var navigation = new CdCommand @@ -416,6 +497,7 @@ await ShellInterpreter.Instance.ConnectAsync( } catch (OperationCanceledException) when (navigationToken.IsCancellationRequested) { + ReportStdioStartupCancellation(startupInput, WriteStartupError); return; } catch (CommandException ex) @@ -426,6 +508,34 @@ await ShellInterpreter.Instance.ConnectAsync( } } + if (o.McpStdio) + { + if (startupInput is not null) + { + await startupInput.CompleteStartupAsync(); + } + + if (startupInput?.StartupToken.IsCancellationRequested == true) + { + ReportStdioStartupCancellation(startupInput, WriteStartupError); + return; + } + + try + { + ShellInterpreter.Instance.App.RemoveCommands(ToolOperations.IsUnavailableInStdio); + host = McpServer.CreateStdioHost(startupInput?.Input ?? protocolInput!, protocolOutput!); + await host.RunAsync(); + } + catch (Exception ex) + { + WriteStartupError(MessageService.GetArgsString("mcp-error-server-failed-start", "message", ex.Message)); + Environment.ExitCode = ShellExitCode.GeneralFailure; + } + + return; + } + // Start MCP server if requested Task? hostTask = null; @@ -527,7 +637,21 @@ await ShellInterpreter.Instance.ConnectAsync( } } - private static void WriteVersionHeading() + internal static void ReportStdioStartupCancellation(StdioStartupInput? input, Action writeError) + { + if (input?.InputError is { } error) + { + writeError(MessageService.GetArgsString("mcp-error-stdio-input", "message", error.Message)); + Environment.ExitCode = ShellExitCode.FromException(error); + } + else if (input?.TimedOut == true) + { + writeError(MessageService.GetString("mcp-error-stdio-startup-timeout")); + Environment.ExitCode = ShellExitCode.ConnectionError; + } + } + + private static void WriteVersionHeading(bool stdio = false) { var assembly = typeof(Program).Assembly; var product = assembly.GetCustomAttribute()?.Product; @@ -541,7 +665,21 @@ private static void WriteVersionHeading() var heading = string.IsNullOrEmpty(commit) ? $"{product} {version}" : $"{product} {version} ({commit})"; - ShellInterpreter.Instance.Output.WriteResult(heading); + WriteStartupResult(heading, stdio); + } + + // Explicit --help/--version output is the requested result; in stdio mode it must + // stay off the protocol stream. + private static void WriteStartupResult(string text, bool stdio) + { + if (stdio) + { + ShellOutput.StandardError.WriteLine(ShellMessageKind.RequiredInstruction, text); + } + else + { + ShellInterpreter.Instance.Output.WriteResult(text); + } } private static async Task StopHostAsync(IHost? host, Task? hostTask) @@ -627,6 +765,16 @@ internal static string[] TakePreCommandArgs(string[] args) return args; } + private static bool IsDirectlyEnabledMcpStdioToken(string token) + { + if (token == "--mcp-stdio") + { + return true; + } + + return bool.TryParse(token["--mcp-stdio=".Length..], out var enabled) && enabled; + } + internal static (RootCommand Command, OptionMap Map) BuildRootCommand() { var colorSystem = new Option("--color-system", "--cs") @@ -721,6 +869,7 @@ internal static (RootCommand Command, OptionMap Map) BuildRootCommand() Description = MessageService.GetString("help-McpPort"), Arity = ArgumentArity.ZeroOrOne, }; + var mcpStdio = new Option("--mcp-stdio") { Description = MessageService.GetString("help-McpStdio") }; var startLspServer = new Option("--lsp") { Description = MessageService.GetString("help-EnableLspServer") }; var lspStdio = new Option("--stdio") @@ -765,6 +914,7 @@ internal static (RootCommand Command, OptionMap Map) BuildRootCommand() database, container, mcpPort, + mcpStdio, startLspServer, lspStdio, verbose, @@ -774,7 +924,7 @@ internal static (RootCommand Command, OptionMap Map) BuildRootCommand() }, }; - // Startup help/version are handled before parsing, not by built-in actions. + // Startup help/version are handled separately, not by built-in actions. foreach (var option in root.Options.Where(option => option is System.CommandLine.Help.HelpOption or VersionOption).ToArray()) { root.Options.Remove(option); @@ -800,6 +950,7 @@ internal static (RootCommand Command, OptionMap Map) BuildRootCommand() database, container, mcpPort, + mcpStdio, startLspServer, lspStdio, verbose, @@ -990,6 +1141,8 @@ public class CosmosShellOptions public int? McpPort { get; set; } + public bool McpStdio { get; set; } + public bool StartLspServer { get; set; } public bool LspStdio { get; set; } @@ -1027,6 +1180,7 @@ internal sealed record OptionMap( Option Database, Option Container, Option McpPort, + Option McpStdio, Option StartLspServer, Option LspStdio, Option Verbose, diff --git a/CosmosDBShell/lang/en.ftl b/CosmosDBShell/lang/en.ftl index 4c7bbe73..560d523f 100644 --- a/CosmosDBShell/lang/en.ftl +++ b/CosmosDBShell/lang/en.ftl @@ -133,6 +133,7 @@ shell-connect-static-token-expiry = Expires in { $timespan } (expiration: { $exp shell-connect-vscode-credential-auth = Connecting with Visual Studio Code credential... shell-connect-vscode-credential-fallback = Visual Studio Code credential unavailable, falling back... shell-connect-devicecode-fallback = Browser authentication failed, falling back to device code authentication... +shell-connect-devicecode-stdio = Browser sign-in is unavailable in MCP stdio mode. Using device code sign-in instead. shell-connect-arm-discovery-failed = Using Cosmos DB data plane. shell-connect-arm-discovery-ambiguous = Multiple ARM Cosmos DB accounts match the connected endpoint. Reconnect with --subscription and --resource-group, or use --connect-subscription and --connect-resource-group at startup, to specify which account to use. Using Cosmos DB data plane for now. shell-connect-verbose-hint = Run with --verbose for full exception details. @@ -1338,6 +1339,14 @@ help-StartupContainer = Navigate to this container after connecting at startup. help-EnableMcpServer = Enable MCP server for programmatic control of the shell help-EnableLspServer = Enable Language Server Protocol (LSP) server for editor integration help-McpPort = Enable MCP HTTP server with Streamable HTTP and legacy SSE. Optionally specify a port with --mcp ; default is 6128. +help-McpStdio = Run a headless MCP server over stdin/stdout, with diagnostics on stderr and no listening port. +command-version-mcp-stdio = MCP server: stdio +mcp-error-stdio-incompatible-options = Error: --mcp-stdio cannot be combined with --mcp, --lsp, --stdio, -c, -k, or --clear-history, and must be enabled. +mcp-error-stdio-response-file = Error: --mcp-stdio must be passed directly on the command line, not through a response file. +mcp-error-stdio-console-input = Interactive console input is unavailable in MCP stdio mode. Use MCP elicitation for confirmation. +mcp-error-stdio-startup-timeout = MCP stdio startup connection and navigation timed out after 60 seconds. Use a non-interactive credential or connect through an MCP tool after starting the server. +mcp-error-stdio-input = MCP stdio input failed: { $message } +mcp-error-stdio-startup-buffer-limit = Startup input exceeded the 8 MiB buffering limit. Wait for startup to finish before sending more requests. help-Verbose = Print full exception details instead of only the message. help-Theme = Color theme profile to apply at startup. Falls back to the COSMOSDB_SHELL_THEME environment variable. help-Diagnostics = Write timestamped diagnostic logs to a file. Optionally specify a path with --diagnostics ; defaults to a timestamped file in the shell configuration directory. diff --git a/README.md b/README.md index 2787b9dd..95fb8743 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# Azure Cosmos DB Shell +# Azure Cosmos DB Shell A terminal-native shell for Azure Cosmos DB — navigate databases like a filesystem, query interactively, and script with variables, loops, and functions. Supports Entra ID, MCP for AI tool integration, and works with the local emulator. @@ -41,10 +41,24 @@ Exports replace their destination only after successful completion, preserving a `import --dry-run` validates input and item IDs offline without writes or target requests. It reports `validated` records and `imported: 0`; it does not verify target partition keys, permissions, conflicts, or other service constraints. See [dry-run limits](docs/commands.md#dry-run-validation-scope). -MCP command execution is serialized with the shell, and destructive confirmations are invalidated by connection or navigation changes. Ordinary explicit null MCP arguments are omitted; null continuation tokens and null `rm` partition-key/ETag safety options are rejected. MCP invocations are echoed in the shell so their activity stays visible, and they are recorded in history alongside interactive commands. Concurrent shells merge history under a shared lock and publish complete replacements instead of truncating the saved file. Recognized credentials are masked in saved history; recalled key-based connections need a fresh key. Continue to treat the history file as sensitive. See [MCP security](docs/mcp.md#security) and [history](docs/navigation.md#history). +MCP command execution is serialized with the shell, and destructive confirmations are invalidated by connection or navigation changes. Ordinary explicit null MCP arguments are omitted; null continuation tokens and null `rm` partition-key/ETag safety options are rejected. HTTP MCP invocations are echoed in the shell and recorded in history. Stdio mode neither loads existing history nor records commands. Concurrent interactive/HTTP shells merge history under a shared lock and publish complete replacements instead of truncating the saved file. Recognized credentials are masked in saved history; recalled key-based connections need a fresh key. Continue to treat the history file as sensitive. See [MCP security](docs/mcp.md#security) and [history](docs/navigation.md#history). + +Use `cosmosdbshell --mcp-stdio` for a client-owned, headless MCP process without a +listening port. Stdin and stdout are reserved exclusively for MCP; diagnostics go +to stderr, commands are not echoed, and closing stdin stops the server. +Startup connection and navigation have a shared 60-second timeout and are +cancelled when stdin closes; timeout errors go to stderr with exit code 4. +Interactive-only commands, `jq`, and `theme` are omitted from stdio tools and help; +destructive commands remain available through MCP confirmation. Existing +`--mcp [port]` HTTP mode remains available alongside the interactive shell. See +[stdio setup](docs/mcp.md#stdio-headless-mode). MCP clients supporting resource subscriptions can watch `cosmos://shell/current-location` for interactive navigation and connection changes; the resource includes the current account endpoint separately from the location. The resource list is static, so the server does not advertise `resources.listChanged`. See [MCP location updates](docs/mcp.md#shell-location-updates). +MCP stdio startup buffers at most 8 MiB of protocol input. Exceeding that limit cancels startup with an error on stderr and exit code `1`; it does not limit normal transport after startup. + +Machine-mode `watch` requires a positive `--max` and returns the collected changes as its final result; interactive watches can still follow without a limit. See [watch](docs/commands.md#watch). + `--mcp` supports Streamable HTTP at `http://127.0.0.1:6128/` and legacy SSE at `http://127.0.0.1:6128/sse` on the same server, without an extra option. Both share the interactive shell's state. Use trusted local clients; prefer Streamable HTTP when available. See [MCP transports](docs/mcp.md#start-mcp-server). Legacy SSE allows at most 16 outstanding MCP requests across all sessions; excess requests receive HTTP 429 before reaching the SDK, without being queued. Replies and cancellation notifications remain available. @@ -209,7 +223,7 @@ Packaging runs produce preview versions in the form `1.0.-preview.` | Option | Description | | ------ | ----------- | | `--output ` | The output format to use (`user`, `json`, `table`, `csv`). Alias: `-o`. Falls back to `COSMOSDB_SHELL_FORMAT`. | -| `--quiet` | Suppress standard informational output. Alias: `-q` | +| `--quiet` | Suppress informational messages, progress, banners, and command echoes; preserve results, warnings, errors, and required authentication instructions. Alias: `-q` | | `-c ` | Execute and exit | | `-k ` | Execute and stay | | `--connect ` | Connection string or endpoint URL | @@ -223,6 +237,7 @@ Packaging runs produce preview versions in the form `1.0.-preview.` | `--database ` | Navigate to this database after connecting at startup | | `--container ` | Navigate to this container after connecting at startup. Requires `--database` | | `--mcp [port]` | Enable MCP server on the given port, or `6128` by default | +| `--mcp-stdio` | Run headless MCP over stdin/stdout; diagnostics use stderr and no port is opened | | `--diagnostics [path]` | Write timestamped diagnostic logs to a file, or to a timestamped file in the config directory by default | | `--otel [endpoint]` | Enable distributed tracing (sampled W3C `traceparent`); optional OTLP `endpoint`, else `OTEL_EXPORTER_OTLP_ENDPOINT` | | `--verbose` | Print full exception details | @@ -281,7 +296,7 @@ When running scripts or automation, Cosmos DB Shell maps execution failures to a These values are a public contract: existing codes are never repurposed, and new failure categories get new codes. See the [CI/CD guide](docs/ci.md#exit-code-contract) for full details. -> **Machine Mode**: Using `--output json` or `--output csv` or `--quiet` (or running `-c` without specifying `--output`, which defaults to `json`) disables ANSI colors, suppresses connection/informational banners, and redirects early parser/connection exceptions to `STDERR` as structured JSON. Data-operation commands emit their result in the selected structured format (JSON or CSV) on `STDOUT`; diagnostic and interactive commands may still write plain text. Interactively, commands render a friendly, human-readable view instead; the default `user` output format selects that friendly view and automatically falls back to JSON whenever output is redirected, piped, or run in machine mode. Bare piped stdin (`echo "..." | cosmosdbshell`) is not implicitly machine mode—pass `-c`, `--output json`, or `--quiet` to opt in. +> **Machine Mode**: Using `--output json` or `--output csv` or `--quiet` (or running `-c` without specifying `--output`, which defaults to `json`) disables ANSI colors, suppresses connection/informational banners, and redirects parser, connection, and command failures to `STDERR` as structured JSON. Data-operation commands emit their result in the selected structured format (JSON or CSV) on `STDOUT`; diagnostic and interactive commands may still write plain text. Warnings, errors, and required authentication instructions remain visible on `STDERR`, even with `--quiet`; explicitly enabled diagnostic logging is unaffected. In MCP stdio mode, results are returned only through MCP and visible messages use `STDERR`. Interactively, commands render a friendly, human-readable view instead; the default `user` output format selects that friendly view and automatically falls back to JSON whenever output is redirected, piped, or run in machine mode. Bare piped stdin (`echo "..." | cosmosdbshell`) is not implicitly machine mode—pass `-c`, `--output json`, or `--quiet` to opt in. ## Theming @@ -367,6 +382,8 @@ Runtime commands for working with files: `theme save` writes a self-contained theme file with every color and style slot populated, so the saved file can be moved or edited without depending on another custom profile. +Successful `theme validate` runs preserve warnings on stderr in machine mode, including `--quiet`. Failed directory scans emit only the structured error on stderr. + ## How to Contribute We welcome contributions! See [CONTRIBUTING.md](./CONTRIBUTING.md) for ways to help, project architecture, and PR guidelines. diff --git a/docs/commands.md b/docs/commands.md index 7c10ac44..5d1a8283 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -1830,6 +1830,7 @@ The `bucket` command has two surfaces: - `bucket` shows this client's current throughput bucket selection. - `bucket <1-5>` tags this client's requests with the given throughput bucket. - `bucket 0` clears the client-side selection. + - All three return a structured `clientBucket` value in machine mode and MCP responses (`null` when no bucket is selected); interactive output retains the readable selection message. - **Container limits** (read with `show`, change with `set`/`clear`): - `bucket show` lists the throughput bucket limits configured on the current container. - `bucket set <1-5> <1-100>` limits a bucket to a maximum percentage of the container's throughput. diff --git a/docs/connect.md b/docs/connect.md index a879e030..0345a8b2 100644 --- a/docs/connect.md +++ b/docs/connect.md @@ -26,6 +26,8 @@ The credential type is determined by the first matching rule (top-to-bottom): > **Note:** Step 3 is primarily a startup option (`--connect-vscode-credential`); it is also accepted as a hidden option on the interactive `connect` command. > > **Note:** `--azure-cli` takes precedence over the priority 6 interactive selection, so combining `--azure-cli` with `--tenant` uses `AzureCliCredential` (honoring the tenant) rather than triggering the browser/device-code flow. +> +> **Note:** In MCP stdio mode (`--mcp-stdio`) the shell never opens a browser. Priority 6 uses `DeviceCodeCredential` directly, and priority 8 uses `DefaultAzureCredential` without its interactive browser step. See [MCP stdio](mcp.md#stdio-headless-mode). The `--authority-host` option is honored by the Entra ID credentials that accept it: `VisualStudioCodeCredential` (priority 3), `ManagedIdentityCredential` (priority 5), the interactive `InteractiveBrowserCredential`/`DeviceCodeCredential` (priority 6), and `DefaultAzureCredential` (priority 8). It does not affect which credential type is selected, and the static token (priority 4) and account key paths ignore it. `AzureCliCredential` (priority 7) uses the cloud that the Azure CLI is already configured for, so it does not accept `--authority-host`; if you supply both, the value is ignored and a warning is printed. Use `az cloud set` to change the Azure CLI cloud instead. diff --git a/docs/mcp.md b/docs/mcp.md index c7691036..f51b0f34 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -45,6 +45,86 @@ Session cleanup is independent of the originating HTTP request's lifetime. Ending a session releases its location subscriptions and any outstanding legacy SSE admission state, even after the initialization request has ended. +### Stdio (Headless Mode) + +For an MCP client that launches and owns its server process, use: + +```bash +cosmosdbshell --mcp-stdio +``` + +This opens no HTTP listener and does not run an interactive shell. Each process +has its own connection and navigation state: + +- **stdin** accepts newline-delimited MCP JSON-RPC messages only, never shell scripts. +- **stdout** carries MCP messages only: responses, requests, and notifications. + Banners, command echoes, colors, and ordinary result rendering are disabled. +- **stderr** carries startup errors, logs, and any incidental command diagnostics. + Tool results and errors remain in MCP response envelopes. +- `--quiet` suppresses informational messages and progress, not warnings, errors, + required authentication instructions, or explicit diagnostic logging. +- Closing stdin stops the server and releases the shell's resources. +- Startup connection and navigation share a 60-second timeout. Closing stdin + cancels pending startup; a timeout is reported on stderr with exit code `4`. + Requests received during startup are buffered in a private delete-on-close + temporary file, capped at 8 MiB. Exceeding the cap cancels startup, reports an + input error on stderr, and exits with code `1`; normal transport after startup + is unaffected. Shutdown releases the file even if a stdin read remains blocked. +- Stdio mode does not load existing shell history or record commands in memory or + on disk. Existing history files are left untouched. Explicit `--diagnostics` + logging remains available through the normal secret-redaction pipeline. + +`--mcp-stdio` cannot be combined with `--mcp`, `--lsp`/`--stdio`, `-c`, `-k`, +or `--clear-history`, and must be passed directly rather than through a +response file (`@file`). Help and version output requested with `--mcp-stdio` goes +to stderr and exits without starting the server. + +Startup connection and navigation options are supported, for example +`--connect --connect-azure-cli --database --container `. +Prefer an existing Azure CLI login, managed identity, or another non-interactive +credential for unattended clients. + +Stdio mode never opens a browser: a headless server has no user at its terminal, +and the browser launcher could write to the protocol stdout. When `--tenant`/`--hint` +(or `--connect-tenant`/`--connect-hint` at startup) would start browser sign-in, the +shell uses device code sign-in instead; an endpoint-only connection uses +`DefaultAzureCredential` without its interactive browser step. Device code instructions +are written to stderr, even with `--quiet`, so a person must read them from the +client's server log. Tool sign-in waits until the code expires unless the client +cancels the tool call, which ends the attempt immediately. A startup `--connect` +that uses device code completes before the server answers MCP requests and is +subject to the shared 60-second startup timeout. For sign-in that may take longer, +start without `--connect` and invoke the `connect` tool after the MCP handshake. + +The `jq` and `theme` commands are not available in stdio mode: they are omitted +from the tool list and `help`, and calls to them fail as unknown tools. Both +launch external processes or manage terminal presentation, which has no meaning +for a headless server and could write to the protocol streams. Commands restricted +to non-MCP use (`exit`, `edit`, `watch`, `welcome`, `sproc`, `udf`, and `trigger`) +are also omitted, including their aliases. HTTP mode retains its existing tool +and help lists. Destructive commands (`delete`, `rm`, `rmdb`, and `rmcon`) remain +listed and callable through confirmation. They +use MCP confirmation/elicitation, never console input, and are refused when the +client cannot confirm. + +Launch an installed tool or a previously built executable, not `dotnet run` +with a build step: build output can contaminate stdout before the application +starts. + +Example VS Code `.vscode/mcp.json`: + +```json +{ + "servers": { + "localCosmosDBShellStdio": { + "type": "stdio", + "command": "cosmosdbshell", + "args": ["--mcp-stdio"] + } + } +} +``` + ## VS Code Setup > **Requires VS Code 1.103+** @@ -101,6 +181,11 @@ The MCP server runs locally with your user permissions. Connected clients can ex - Query and retrieve documents - Create, update, and delete resources +Stdio mode has no unauthenticated localhost listener; access is through the pipes +owned by the launching client. It is not a sandbox: that client still exercises +the process owner's filesystem and Cosmos permissions. Trust the client and its +agents just as you would for HTTP mode. + Server-side programming commands — stored procedures (`sproc`), user-defined functions (`udf`), and triggers (`trigger`) — are restricted from MCP. Run those commands manually in the shell. Transactional batches invoked through MCP must use the one-shot `batch run` subcommand. Stateful batch subcommands (`begin`, `add`, `execute`, `cancel`, `status`, and `show`, including their aliases) are restricted to the interactive shell because MCP tool calls share no client-specific batch state. @@ -119,7 +204,7 @@ This replaces any opt-in write flag: destructive writes are allowed to be invoke Confirmation includes the connected account endpoint and current navigation location alongside the command and its explicit target arguments. If the connection or navigation state changes while confirmation is pending, the approved command is refused without executing; retry it to confirm the new context. Even navigating away and back invalidates the pending confirmation. A pending confirmation also expires when the MCP server restarts. -Shell and MCP command execution is serialized against the shared interpreter. Confirmation prompts do not hold the execution lock, so the shell remains usable while waiting. Clients still share a connection and navigation context: pass explicit `database` and `container` arguments for independent operations rather than relying on an earlier `cd` call. +Shell and MCP command execution is serialized against the shared interpreter. Confirmation prompts do not hold the execution lock, so the HTTP-mode shell remains usable while waiting. HTTP clients share a connection and navigation context; each stdio process has its own context. Pass explicit `database` and `container` arguments for independent operations rather than relying on an earlier `cd` call. The MCP confirmation applies even when a command is invoked with a force / no-prompt argument (for example `rmdb OldDB true`). That argument only skips the *interactive shell* prompt; it does not bypass the MCP elicitation gate. @@ -158,7 +243,7 @@ The HTTP server serves `2026-07-28` requests without a session and gives a sessi ### Data Exposure -MCP tool invocations are echoed as command lines in the shell window, so anyone watching the terminal can see what a connected client is doing. They are also recorded in the shell history, with recognized credentials such as connection-string account keys replaced by `[REDACTED]`. Recalled key-based connections require a fresh key. Existing saved credentials are removed on the next successful history save; this does not clean backups or mask the command echo. Continue to protect the history file, since arbitrary secrets under unrelated names may not be recognized. On Linux and macOS, the shell restricts the history file to its owner. See [history](navigation.md#history) for details. +HTTP MCP tool invocations are echoed as command lines in the shell window, so anyone watching the terminal can see what a connected client is doing. They are also recorded in the shell history, with recognized credentials such as connection-string account keys replaced by `[REDACTED]`. Stdio mode does neither and does not load existing history. Recalled key-based connections require a fresh key. Existing saved credentials are removed on the next successful history save; this does not clean backups or mask the command echo. Continue to protect the history file, since arbitrary secrets under unrelated names may not be recognized. On Linux and macOS, the shell restricts the history file to its owner. See [history](navigation.md#history) for details. Positional arguments must be supplied without gaps: a call that provides a positional parameter while omitting an earlier one is rejected, because the equivalent shell command line would bind the value to the omitted slot. diff --git a/docs/navigation.md b/docs/navigation.md index b715deac..cde2f1ea 100644 --- a/docs/navigation.md +++ b/docs/navigation.md @@ -326,6 +326,7 @@ Start the shell with options to customize behavior: | `--database ` | Navigate to this database after connecting at startup | | `--container ` | Navigate to this container after connecting at startup. Requires `--database` | | `--mcp [port]` | Enable MCP server with Streamable HTTP and legacy SSE on the given port, or `6128` by default | +| `--mcp-stdio` | Run a headless MCP server over stdin/stdout, with diagnostics on stderr and no listening port | | `--diagnostics [path]` | Write timestamped diagnostic logs (commands, timing, errors, connection events) to a file, or to a timestamped file in the config directory by default | | `--otel [endpoint]` | Enable distributed tracing so requests carry a sampled W3C `traceparent`. Optionally export spans to an OTLP `endpoint`; falls back to the `OTEL_EXPORTER_OTLP_ENDPOINT` environment variable | | `--color-system ` | Color scheme: 0=off, 1=standard, 2=truecolor (alias: `--cs`) | @@ -356,7 +357,8 @@ falls back to JSON whenever output is redirected, piped, or run in machine mode. Quiet is not a universal mute: warnings, errors, and required instructions (such as authentication prompts and previews shown before a confirmation) remain visible on `STDERR`, without ANSI styling. Explicit diagnostic logging is unaffected. -Command results are separate from informational messages and remain on `STDOUT`. +Command results are separate from informational messages and remain on `STDOUT` +(or in MCP responses for `--mcp-stdio`). Bulk-write errors include per-item diagnostics in that single structured error: imports identify source lines, and item-array writes identify 1-based item positions. Up to 100 item diagnostics are listed, followed by a count of any omitted ones. @@ -438,6 +440,8 @@ cosmosdbshell --mcp cosmosdbshell --mcp 5050 # The same server also accepts legacy clients at http://127.0.0.1:5050/sse +# Client-owned, headless MCP server; stdin/stdout carry only MCP messages +cosmosdbshell --mcp-stdio # Capture a diagnostic log to the default location in the config directory cosmosdbshell --diagnostics @@ -451,3 +455,10 @@ cosmosdbshell --otel # Enable distributed tracing and export spans to an OTLP collector cosmosdbshell --otel http://localhost:4317 ``` + +`--mcp-stdio` is mutually exclusive with `--mcp`, `--lsp`/`--stdio`, `-c`, `-k`, +and `--clear-history`. It does not read stdin as a shell script or start a prompt. +Startup `--connect`, credential options, `--database`, and `--container` remain +available. Startup connection and navigation share a 60-second timeout and are +cancelled when stdin closes. A timeout is reported on stderr with exit code `4`. +See [MCP stdio mode](mcp.md#stdio-headless-mode). diff --git a/l10n/CosmosDBShell.json b/l10n/CosmosDBShell.json index 2fa29dc8..6611e620 100644 --- a/l10n/CosmosDBShell.json +++ b/l10n/CosmosDBShell.json @@ -1248,6 +1248,7 @@ "command-version-example-1": "Display the current Cosmos Shell version", "command-version-mcp": "MCP running on port {0}", "command-version-mcp-off": "MCP server is off.", + "command-version-mcp-stdio": "MCP server: stdio", "command-version-repo": "Report issues at [link={0}]{1}[/]", "command-watch-description": "Tail the change feed of a container, streaming new and modified items as they arrive.", "command-watch-description-container": "The container to watch.", @@ -1439,6 +1440,7 @@ "help-HelpCommandScreenText": "Display this help screen.", "help-HelpOptionDescription": "Show this help text and exit.", "help-McpPort": "Enable MCP HTTP server with Streamable HTTP and legacy SSE. Optionally specify a port with --mcp \u003Cport\u003E; default is 6128.", + "help-McpStdio": "Run a headless MCP server over stdin/stdout, with diagnostics on stderr and no listening port.", "help-NotesHeadingText": "NOTES:", "help-OptionGroupWord": "Group", "help-OptionsHeadingText": "OPTIONS:", @@ -1561,6 +1563,12 @@ "mcp-error-creating-server": "Error creating MCP server: {0}", "mcp-error-invalid-port": "Error: --mcp port must be greater than 0.", "mcp-error-server-failed-start": "MCP server failed to start: {0}", + "mcp-error-stdio-console-input": "Interactive console input is unavailable in MCP stdio mode. Use MCP elicitation for confirmation.", + "mcp-error-stdio-incompatible-options": "Error: --mcp-stdio cannot be combined with --mcp, --lsp, --stdio, -c, -k, or --clear-history, and must be enabled.", + "mcp-error-stdio-input": "MCP stdio input failed: {0}", + "mcp-error-stdio-response-file": "Error: --mcp-stdio must be passed directly on the command line, not through a response file.", + "mcp-error-stdio-startup-buffer-limit": "Startup input exceeded the 8 MiB buffering limit. Wait for startup to finish before sending more requests.", + "mcp-error-stdio-startup-timeout": "MCP stdio startup connection and navigation timed out after 60 seconds. Use a non-interactive credential or connect through an MCP tool after starting the server.", "no_char": "N", "otel-error-invalid-endpoint": "Error: --otel endpoint \u0027{0}\u0027 is not a valid absolute URI.", "parser-error-prefix": "parse error", @@ -1587,6 +1595,7 @@ "shell-connect-default-auth": "Connecting with DefaultAzureCredential...", "shell-connect-devicecode-auth": "Browser authentication failed. Falling back to device code authentication.", "shell-connect-devicecode-fallback": "Browser authentication failed, falling back to device code authentication...", + "shell-connect-devicecode-stdio": "Browser sign-in is unavailable in MCP stdio mode. Using device code sign-in instead.", "shell-connect-error-cosmos-detail": "Cosmos DB request failed: HTTP {0} {1}, sub-status {2}, activity id {3}.", "shell-connect-key-auth": "Connecting with account key...", "shell-connect-key-env": "Using the account key from the COSMOSDB_SHELL_ACCOUNT_KEY environment variable.",