Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
9e6800e
Add headless MCP stdio mode
mkrueger Oct 5, 2026
d85ad03
Disable shell history in MCP stdio mode
mkrueger Oct 5, 2026
f1b84b7
Centralize shell output through a category-based policy
mkrueger Oct 5, 2026
3ee1474
Update Copilot instructions for MCP stdio and output policy
mkrueger Oct 5, 2026
49523cb
Keep MCP stdio sign-in non-interactive
mkrueger Oct 5, 2026
51b010e
Bound MCP stdio startup and handle request cancellation
mkrueger Oct 6, 2026
26d45da
Merge remote-tracking branch 'origin/main' into dev/mkrueger/mcp_stdio
mkrueger Oct 6, 2026
eaa80c1
Preserve machine output contracts
mkrueger Oct 6, 2026
6e5d07d
Harden stdio startup validation
mkrueger Oct 6, 2026
ef31a1f
Use safe process test path joins
mkrueger Oct 6, 2026
4f8ff03
Disable broker authentication in stdio mode
mkrueger Oct 6, 2026
14d9dfd
Document stdio LSP incompatibility
mkrueger Oct 6, 2026
13d5e3e
Suppress strict theme warnings in machine mode
mkrueger Oct 6, 2026
387368c
Harden stdio startup buffering
mkrueger Oct 6, 2026
a621198
Validate direct stdio option values
mkrueger Oct 6, 2026
9132828
Merge main and preserve successful theme validation warnings
mkrueger Oct 7, 2026
6dda05c
Merge main and fix stdio startup spool cleanup
mkrueger Oct 9, 2026
b4658ee
Require bounded watch results in machine mode
mkrueger Oct 9, 2026
0abc080
Bound MCP stdio startup buffering
mkrueger Oct 9, 2026
98a2fed
Defer changelog updates in #239 until release preparation
mkrueger Nov 5, 2026
aa0d19c
Merge main and preserve MCP stdio output contracts
mkrueger Nov 5, 2026
f62fe4f
Merge latest main into MCP stdio branch
mkrueger Nov 5, 2026
992250e
Drain startup timer callbacks and preserve quiet editor prompts
mkrueger Nov 5, 2026
31e55d5
Isolate stdio device-code test from inherited credentials
mkrueger Nov 5, 2026
5fe9233
Return client bucket selection as a structured command result
mkrueger Nov 5, 2026
7286fd7
Merge history redaction while preserving MCP stdio isolation
mkrueger Nov 5, 2026
3292142
Merge requested usage and error-output fixes into MCP stdio
mkrueger Nov 5, 2026
ba8c088
Classify bucket and watch argument failures as usage errors
mkrueger Nov 5, 2026
671cb8c
Reject malformed stdio options before startup dispatch
mkrueger Nov 5, 2026
c36c168
Merge remote-tracking branch 'origin/main' into dev/mkrueger/mcp_stdio
mkrueger Nov 20, 2026
f49fd73
Preserve required stdio output after merge
mkrueger Nov 20, 2026
5c67718
Preserve quiet command history after merge
mkrueger Nov 20, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .github/copilot-instructions.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<T>`; 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

Expand Down
6 changes: 3 additions & 3 deletions CosmosDBShell.Analyzer/DirectConsoleOutputAnalyzer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ namespace CosmosShell.Analyzer
{
/// <summary>
/// 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.
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class DirectConsoleOutputAnalyzer : DiagnosticAnalyzer
Expand All @@ -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<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Rule); } }

Expand Down
32 changes: 31 additions & 1 deletion CosmosDBShell.Tests/CommandTests/BucketCommandTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<ShellJson>(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)]
Expand Down Expand Up @@ -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<CommandException>(
var error = await Assert.ThrowsAsync<CommandException>(
() => command.ExecuteAsync(shell, new CommandState(), "bucket 99", CancellationToken.None));

Assert.Equal(ShellExitCode.UsageError, ShellExitCode.FromException(error));
Assert.Null(client.ClientOptions.ThroughputBucket);
}

Expand Down
77 changes: 77 additions & 0 deletions CosmosDBShell.Tests/CommandTests/ConnectCommandTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Comment thread
mkrueger marked this conversation as resolved.
Resolved
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<Exception>(() => 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<ConnectedState>(shell.State);
}

[Fact]
public void LocalEmulatorInactivityTimeout_IsInitializedOnSharedAndNewInstances()
{
Expand Down
14 changes: 14 additions & 0 deletions CosmosDBShell.Tests/CommandTests/QueryCommandTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<CommandException>(() =>
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;
Expand Down
Loading