From bab00db65c5e28afe62d7a1903eebc6729b78937 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mike=20Kr=C3=BCger?= Date: Fri, 20 Nov 2026 17:11:57 +0100 Subject: [PATCH 1/6] Require confirmation for MCP filesystem reads Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- CosmosDBShell.Tests/McpConfirmationTests.cs | 78 +++++++++ .../ToolOperationsCallToolTests.cs | 164 ++++++++++++++++-- CosmosDBShell.Tests/ToolOperationsTests.cs | 23 +++ .../CatCommand.cs | 2 + .../DirCommand.cs | 2 + .../HelpCommand.cs | 4 +- .../ConfirmationRequestState.cs | 2 +- .../McpAnnotationAttribute.cs | 2 +- .../ToolOperations.cs | 71 +++++--- docs/mcp.md | 17 ++ 10 files changed, 325 insertions(+), 40 deletions(-) diff --git a/CosmosDBShell.Tests/McpConfirmationTests.cs b/CosmosDBShell.Tests/McpConfirmationTests.cs index 158f2cd4..8618954a 100644 --- a/CosmosDBShell.Tests/McpConfirmationTests.cs +++ b/CosmosDBShell.Tests/McpConfirmationTests.cs @@ -6,6 +6,7 @@ namespace CosmosShell.Tests; using System.Text.Json; using Azure.Data.Cosmos.Shell.Mcp; +using Azure.Data.Cosmos.Shell.Util; using Microsoft.AspNetCore.Hosting.Server; using Microsoft.AspNetCore.Hosting.Server.Features; using Microsoft.Extensions.DependencyInjection; @@ -16,6 +17,83 @@ namespace CosmosShell.Tests; [Collection(CosmosShell.Tests.Shell.ThemeStateTestCollection.Name)] public class McpConfirmationTests { + [Theory] + [InlineData("dir", "accept", null)] + [InlineData("cat", "accept", null)] + [InlineData("dir", "decline", null)] + [InlineData("cat", "decline", null)] + [InlineData("dir", "accept", "2025-11-25")] + [InlineData("cat", "accept", "2025-11-25")] + [InlineData("dir", "decline", "2025-11-25")] + [InlineData("cat", "decline", "2025-11-25")] + public async Task LocalFilesystemRead_OverHttp_RequiresApproval(string commandName, string action, string? requestedVersion) + { + 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); + var directory = Path.Combine(Path.GetTempPath(), $"mcp-local-read-{Guid.NewGuid():N}"); + var file = Path.Combine(directory, "sample.txt"); + try + { + Directory.CreateDirectory(directory); + await File.WriteAllTextAsync(file, "approved local content", timeout.Token); + 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 = action }); + }, + }, + }, + cancellationToken: timeout.Token); + var arguments = commandName == "dir" + ? new Dictionary { ["directory"] = directory, ["filter"] = "*.txt" } + : new Dictionary { ["path"] = file }; + var result = await client.CallToolAsync(commandName, arguments, cancellationToken: timeout.Token); + + var prompt = Assert.Single(prompts); + Assert.Contains("Confirm local filesystem access", prompt); + Assert.Contains(ShellLiteral.Quote(commandName == "dir" ? directory : file), prompt); + Assert.Contains(Directory.GetCurrentDirectory(), prompt); + Assert.DoesNotContain("destructive", prompt); + Assert.Equal(action != "accept", result.IsError == true); + using var document = JsonDocument.Parse(Assert.IsType(Assert.Single(result.Content)).Text); + if (action == "accept") + { + if (commandName == "cat") + { + Assert.Equal("approved local content", document.RootElement.GetProperty("result").GetString()); + } + else + { + var entry = Assert.Single(document.RootElement.GetProperty("result").GetProperty("values").EnumerateArray()); + Assert.Equal("sample.txt", entry.GetProperty("name").GetString()); + } + } + else + { + Assert.Contains("was not approved", document.RootElement.GetProperty("error").GetString()); + Assert.False(document.RootElement.TryGetProperty("result", out _)); + } + } + finally + { + await host.StopAsync(TestContext.Current.CancellationToken); + File.Delete(file); + Directory.Delete(directory); + } + } + [Theory] [InlineData("run", false, 1, "was not approved")] [InlineData("run", true, 0, "not connected")] diff --git a/CosmosDBShell.Tests/ToolOperationsCallToolTests.cs b/CosmosDBShell.Tests/ToolOperationsCallToolTests.cs index f36870ae..89f57210 100644 --- a/CosmosDBShell.Tests/ToolOperationsCallToolTests.cs +++ b/CosmosDBShell.Tests/ToolOperationsCallToolTests.cs @@ -193,7 +193,7 @@ public async Task ConfirmDestructive_NoElicitationSupport_RefusesAndDoesNotExecu { var tool = CreateToolOperations(); - var result = await tool.ConfirmDestructiveAsync( + var result = await tool.ConfirmCommandAsync( null, "rmdb", "rmdb mydb", @@ -210,6 +210,144 @@ public async Task ConfirmDestructive_NoElicitationSupport_RefusesAndDoesNotExecu } } + [Theory] + [InlineData("dir", "{}")] + [InlineData("dir", "{\"filter\":\"*.json\"}")] + [InlineData("dir", "{\"directory\":\"missing-directory\",\"recursive\":true,\"list\":true}")] + [InlineData("dir", "{\"d\":\"missing-directory\",\"r\":true,\"l\":true}")] + [InlineData("cat", "{\"path\":\"missing-file.json\"}")] + public async Task CallTool_LocalFilesystemReadsWithoutConfirmation_RefuseBeforeAccess(string commandName, string argumentsJson) + { + var history = ShellInterpreter.Instance.History.ToArray(); + var arguments = JsonSerializer.Deserialize>(argumentsJson); + + var result = await CreateToolOperations().CallToolHandler( + CallContext(commandName, arguments), TestContext.Current.CancellationToken); + + var (isError, root, document) = ReadResult(result); + using (document) + { + Assert.True(isError); + Assert.Contains("accesses the local filesystem", root.GetProperty("error").GetString()); + Assert.Contains("does not support confirmation prompts", root.GetProperty("error").GetString()); + Assert.DoesNotContain("is destructive", root.GetProperty("error").GetString()); + } + + Assert.Equal(history, ShellInterpreter.Instance.History); + } + + [Theory] + [InlineData("dir", "accept")] + [InlineData("cat", "accept")] + [InlineData("dir", "decline")] + [InlineData("cat", "decline")] + [InlineData("dir", "cancel")] + [InlineData("cat", "cancel")] + [InlineData("dir", "throw")] + [InlineData("cat", "throw")] + public async Task ExecuteTool_LocalFilesystemReads_OnlyAccessFilesAfterApproval(string commandName, string action) + { + var directory = Path.Combine(Path.GetTempPath(), $"cosmos-mcp-read-{Guid.NewGuid():N}"); + Directory.CreateDirectory(directory); + var file = Path.Combine(directory, "sample.txt"); + const string content = "local file confirmation test"; + await File.WriteAllTextAsync(file, content, TestContext.Current.CancellationToken); + var shell = ShellInterpreter.Instance; + CosmosCommand command = commandName == "dir" + ? new DirCommand { Directory = directory, Filter = "*.txt", Recursive = true, ListOnly = true } + : new CatCommand { FilePath = file }; + var commandLine = commandName == "dir" + ? $"dir \"*.txt\" --directory \"{directory}\" --recursive --list" + : $"cat \"{file}\""; + var history = shell.History.ToArray(); + try + { + var result = await CreateToolOperations().ExecuteToolAsync( + shell.App.Commands[commandName], command, commandLine, + (request, _, _, confirmationCommandLine) => + { + Assert.Contains("Confirm local filesystem access", request.Message); + Assert.Contains(commandLine, request.Message); + Assert.Contains(Directory.GetCurrentDirectory(), request.Message); + Assert.Contains("returned to the MCP client", request.Message); + Assert.DoesNotContain("permanently change or delete", request.Message); + Assert.Equal( + new[] { commandLine, Directory.GetCurrentDirectory() }, + JsonSerializer.Deserialize(confirmationCommandLine)); + if (action == "throw") + { + throw new InvalidOperationException("prompt failed"); + } + + return new ValueTask(new ElicitResult { Action = action }); + }, TestContext.Current.CancellationToken); + + var (isError, root, document) = ReadResult(result); + using (document) + { + Assert.Equal(action != "accept", isError); + if (action == "accept") + { + if (commandName == "cat") + { + Assert.Equal(content, root.GetProperty("result").GetString()); + } + else + { + var entry = Assert.Single(root.GetProperty("result").GetProperty("values").EnumerateArray()); + Assert.Equal("sample.txt", entry.GetProperty("name").GetString()); + Assert.Equal(file, entry.GetProperty("path").GetString()); + } + } + else + { + Assert.Equal(history, shell.History); + Assert.False(root.TryGetProperty("result", out _)); + } + } + } + finally + { + File.Delete(file); + Directory.Delete(directory); + } + } + + [Theory] + [InlineData("dir", false)] + [InlineData("cat", false)] + [InlineData("dir", true)] + [InlineData("cat", true)] + public async Task ExecuteTool_LocalFilesystemConfirmationRetry_BindsWorkingDirectory(string commandName, bool differentDirectory) + { + var shell = ShellInterpreter.Instance; + var commandLine = $"{commandName} sample"; + var command = new TrackingCommand(); + var exception = await Assert.ThrowsAsync(() => CreateToolOperations().ExecuteToolAsync( + shell.App.Commands[commandName], command, commandLine, + (request, stateVersion, _, confirmationCommandLine) => throw new InputRequiredException( + inputRequests: new Dictionary { ["confirm"] = InputRequest.ForElicitation(request) }, + requestState: ConfirmationRequestState.Create( + differentDirectory + ? JsonSerializer.Serialize(new[] { commandLine, Path.Combine(Directory.GetCurrentDirectory(), "other") }) + : confirmationCommandLine, + stateVersion)), + TestContext.Current.CancellationToken)); + + Assert.False(command.Executed); + var retry = ConfirmationRetry("accept", exception.Result.RequestState!); + var result = await CreateToolOperations().ExecuteToolAsync( + shell.App.Commands[commandName], command, commandLine, null, TestContext.Current.CancellationToken, retry); + + Assert.Equal(differentDirectory, result.IsError == true); + Assert.Equal(!differentDirectory, command.Executed); + var replay = new TrackingCommand(); + var replayResult = await CreateToolOperations().ExecuteToolAsync( + shell.App.Commands[commandName], replay, commandLine, null, TestContext.Current.CancellationToken, retry); + Assert.True(replayResult.IsError); + Assert.False(replay.Executed); + } + [Fact] public async Task CallTool_RmWithPartitionKeyAndETag_ConfirmationShowsTargetConditions() { @@ -292,7 +430,7 @@ public async Task CallTool_RmWithJsonNullSafetyOption_ConfirmedCommandFailsWitho factory, command, "rm \"order-123\" --key \"id\" --partition-key \"customer-42\"", - (_, _, _) => new ValueTask(new ElicitResult { Action = "accept" }), + (_, _, _, _) => new ValueTask(new ElicitResult { Action = "accept" }), TestContext.Current.CancellationToken); Assert.True(result.IsError); @@ -335,8 +473,8 @@ public async Task ConfirmDestructive_UserAccepts_ReturnsNull() { var tool = CreateToolOperations(); - var result = await tool.ConfirmDestructiveAsync( - (_, _, _) => new ValueTask(new ElicitResult { Action = "accept" }), + var result = await tool.ConfirmCommandAsync( + (_, _, _, _) => new ValueTask(new ElicitResult { Action = "accept" }), "rmdb", "rmdb mydb", CancellationToken.None); @@ -354,7 +492,7 @@ public async Task ExecuteTool_ContextChangesDuringConfirmation_RefusesExecution( { var result = await CreateToolOperations().ExecuteToolAsync( shell.App.Commands["rm"], command, "rm test-*", - (request, _, _) => + (request, _, _, _) => { Assert.Contains("Account:", request.Message); Assert.Contains("Current location:", request.Message); @@ -458,7 +596,7 @@ public async Task ExecuteTool_UnchangedContextAfterConfirmation_ExecutesCommand( var command = new TrackingCommand(); var result = await CreateToolOperations().ExecuteToolAsync( ShellInterpreter.Instance.App.Commands["rm"], command, "rm test-*", - (_, _, _) => new ValueTask(new ElicitResult { Action = "accept" }), + (_, _, _, _) => new ValueTask(new ElicitResult { Action = "accept" }), TestContext.Current.CancellationToken); Assert.False(result.IsError == true); Assert.True(command.Executed); @@ -484,7 +622,7 @@ public async Task ExecuteTool_WithoutAnsiTerminal_EchoesPlainlyAndStillExecutes( var result = await CreateToolOperations().ExecuteToolAsync( ShellInterpreter.Instance.App.Commands["rm"], command, "rm test-*", - (_, _, _) => new ValueTask(new ElicitResult { Action = "accept" }), + (_, _, _, _) => new ValueTask(new ElicitResult { Action = "accept" }), TestContext.Current.CancellationToken); Assert.False(result.IsError == true); @@ -507,8 +645,8 @@ public async Task ConfirmDestructive_UserDeclines_ReturnsErrorAndDoesNotExecute( { var tool = CreateToolOperations(); - var result = await tool.ConfirmDestructiveAsync( - (_, _, _) => new ValueTask(new ElicitResult { Action = action }), + var result = await tool.ConfirmCommandAsync( + (_, _, _, _) => new ValueTask(new ElicitResult { Action = action }), "rmdb", "rmdb mydb", CancellationToken.None); @@ -529,8 +667,8 @@ public async Task ConfirmDestructive_ElicitationThrows_ReturnsErrorAndDoesNotExe { var tool = CreateToolOperations(); - var result = await tool.ConfirmDestructiveAsync( - (_, _, _) => throw new InvalidOperationException("boom"), + var result = await tool.ConfirmCommandAsync( + (_, _, _, _) => throw new InvalidOperationException("boom"), "rmdb", "rmdb mydb", CancellationToken.None); @@ -1111,9 +1249,9 @@ public async Task ExecuteTool_MrtrPrompt_RequestsConfirmationWithoutExecuting() var exception = await Assert.ThrowsAsync(() => CreateToolOperations().ExecuteToolAsync( shell.App.Commands["rm"], command, "rm test-*", - (request, stateVersion, _) => throw new InputRequiredException( + (request, stateVersion, _, confirmationCommandLine) => throw new InputRequiredException( inputRequests: new Dictionary { ["confirm"] = InputRequest.ForElicitation(request) }, - requestState: ConfirmationRequestState.Create("rm test-*", stateVersion)), + requestState: ConfirmationRequestState.Create(confirmationCommandLine, stateVersion)), TestContext.Current.CancellationToken)); Assert.False(command.Executed); diff --git a/CosmosDBShell.Tests/ToolOperationsTests.cs b/CosmosDBShell.Tests/ToolOperationsTests.cs index 36542f83..3e14f3d7 100644 --- a/CosmosDBShell.Tests/ToolOperationsTests.cs +++ b/CosmosDBShell.Tests/ToolOperationsTests.cs @@ -328,6 +328,29 @@ public void GetTool_MarksStoredProceduresRestrictedForMcp() Assert.True(tool.Annotations.OpenWorldHint); } + [Theory] + [InlineData("dir")] + [InlineData("cat")] + public void GetTool_LocalFilesystemReads_RequireConfirmationWithoutDestructiveHints(string commandName) + { + var factory = new CommandRunner().Commands[commandName]; + var tool = ToolOperations.GetTool(factory); + + Assert.True(factory.McpRestricted); + Assert.True(factory.McpAnnotation!.Confirmable); + Assert.False(factory.McpAnnotation.Destructive); + Assert.Contains("local filesystem", tool.Description); + Assert.Contains("requires explicit user confirmation", tool.Description); + Assert.DoesNotContain("cannot be invoked through MCP", tool.Description); + Assert.NotNull(tool.Annotations); + Assert.True(tool.Annotations.ReadOnlyHint); + Assert.NotEqual(true, tool.Annotations.DestructiveHint); + + var help = HelpCommand.PrintCommandHelp(commandName, new CommandRunner(), plain: true); + var helpJson = Assert.IsType(help.Result).Value; + Assert.Contains("requires explicit user confirmation", helpJson.GetProperty("isRestricted").GetString()); + } + [Fact] public void GetTool_DoesNotAppendWarningForUnrestrictedCommands() { diff --git a/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/CatCommand.cs b/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/CatCommand.cs index 29b7bb3b..3137596e 100644 --- a/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/CatCommand.cs +++ b/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/CatCommand.cs @@ -5,6 +5,7 @@ namespace Azure.Data.Cosmos.Shell.Commands; using Azure.Data.Cosmos.Shell.Core; +using Azure.Data.Cosmos.Shell.Mcp; using Azure.Data.Cosmos.Shell.Parser; using Azure.Data.Cosmos.Shell.States; using Azure.Data.Cosmos.Shell.Util; @@ -12,6 +13,7 @@ namespace Azure.Data.Cosmos.Shell.Commands; [CosmosCommand("cat")] [CosmosExample("cat config.json", DescriptionKey = "command-cat-example-1")] [CosmosExample("cat data.txt", DescriptionKey = "command-cat-example-2")] +[McpAnnotation(Restricted = true, Confirmable = true, ReadOnly = true, Idempotent = true)] internal class CatCommand : CosmosCommand, IStateVisitor { [CosmosParameter("path", IsRequired = false, ParameterType = ParameterType.File)] diff --git a/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/DirCommand.cs b/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/DirCommand.cs index d7b05fa3..1cf2c094 100644 --- a/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/DirCommand.cs +++ b/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/DirCommand.cs @@ -7,6 +7,7 @@ namespace Azure.Data.Cosmos.Shell.Commands; using System.Text.Json; using Azure.Data.Cosmos.Shell.Core; +using Azure.Data.Cosmos.Shell.Mcp; using Azure.Data.Cosmos.Shell.Parser; using Azure.Data.Cosmos.Shell.Util; @@ -23,6 +24,7 @@ namespace Azure.Data.Cosmos.Shell.Commands; [CosmosExample("dir *.cs --directory=src", DescriptionKey = "command-dir-example-5")] [CosmosExample("dir -r", DescriptionKey = "command-dir-example-6")] [CosmosExample("dir -l", DescriptionKey = "command-dir-example-7")] +[McpAnnotation(Restricted = true, Confirmable = true, ReadOnly = true, Idempotent = true)] internal class DirCommand : CosmosCommand { [CosmosParameter("filter", IsRequired = false)] diff --git a/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/HelpCommand.cs b/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/HelpCommand.cs index a1b4f66e..a0a29f96 100644 --- a/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/HelpCommand.cs +++ b/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/HelpCommand.cs @@ -408,7 +408,9 @@ public static CommandState PrintCommandHelp(string cmdStr, CommandRunner app, bo { helpJson["isRestricted"] = cmd.CommandName == "bulk" ? MessageService.GetString("command-bulk-mcp-help") - : "This tool can't be run via MCP. User only."; + : cmd.CommandName is "dir" or "cat" + ? "Local filesystem access through MCP requires explicit user confirmation." + : "This tool can't be run via MCP. User only."; } // Add statements JSON (for parity) diff --git a/CosmosDBShell/Azure.Data.Cosmos.Shell.Mcp/ConfirmationRequestState.cs b/CosmosDBShell/Azure.Data.Cosmos.Shell.Mcp/ConfirmationRequestState.cs index a967ad65..e0191c65 100644 --- a/CosmosDBShell/Azure.Data.Cosmos.Shell.Mcp/ConfirmationRequestState.cs +++ b/CosmosDBShell/Azure.Data.Cosmos.Shell.Mcp/ConfirmationRequestState.cs @@ -10,7 +10,7 @@ namespace Azure.Data.Cosmos.Shell.Mcp; using Microsoft.AspNetCore.WebUtilities; /// -/// Creates and validates the MRTR requestState for destructive-command confirmation. +/// Creates and validates the MRTR requestState for command confirmation. /// The state binds an approval to the exact command line and shell state version it was /// requested for, and is signed so a client cannot fabricate or retarget it. Each state /// carries a nonce that can be read once and expires after , so a diff --git a/CosmosDBShell/Azure.Data.Cosmos.Shell.Mcp/McpAnnotationAttribute.cs b/CosmosDBShell/Azure.Data.Cosmos.Shell.Mcp/McpAnnotationAttribute.cs index e8e2eaa6..96b7c793 100644 --- a/CosmosDBShell/Azure.Data.Cosmos.Shell.Mcp/McpAnnotationAttribute.cs +++ b/CosmosDBShell/Azure.Data.Cosmos.Shell.Mcp/McpAnnotationAttribute.cs @@ -40,7 +40,7 @@ public McpAnnotationAttribute() public bool Destructive { get; set; } /// - /// Gets or sets a value indicating whether a restricted destructive command may run + /// Gets or sets a value indicating whether a restricted command may run /// over MCP after the user confirms it through an elicitation prompt, instead of being /// hard-blocked. Applies only when is also set. /// diff --git a/CosmosDBShell/Azure.Data.Cosmos.Shell.Mcp/ToolOperations.cs b/CosmosDBShell/Azure.Data.Cosmos.Shell.Mcp/ToolOperations.cs index 497ca5bf..99adbe51 100644 --- a/CosmosDBShell/Azure.Data.Cosmos.Shell.Mcp/ToolOperations.cs +++ b/CosmosDBShell/Azure.Data.Cosmos.Shell.Mcp/ToolOperations.cs @@ -53,7 +53,8 @@ public ToolOperations(ILogger logger, LocationResourceSubscripti internal delegate ValueTask ConfirmationPrompt( ElicitRequestParams request, long stateVersion, - CancellationToken cancellationToken); + CancellationToken cancellationToken, + string confirmationCommandLine); public McpRequestHandler ListToolsHandler => this.OnListToolsAsync; @@ -90,9 +91,11 @@ internal static Tool GetTool(CommandFactory command) if (RequiresConfirmation(command)) { - description += command.CommandName == "bulk" - ? "Warning: Bulk writes and dry-run selections that save a plan require explicit user confirmation, even with yes=true. Only dry runs without save skip confirmation and issue no database writes. Bulk operations are not transactions." - : "Warning: This command is destructive. When invoked through MCP it always requires explicit user confirmation before it runs — even when a force or no-prompt argument is supplied. If the client cannot confirm, the command is refused."; + description += command.CommandName is "dir" or "cat" + ? "Warning: This command accesses the local filesystem and requires explicit user confirmation before it runs. File contents, names, and paths may contain sensitive information. If the client cannot confirm, the command is refused." + : command.CommandName == "bulk" + ? "Warning: Bulk writes and dry-run selections that save a plan require explicit user confirmation, even with yes=true. Only dry runs without save skip confirmation and issue no database writes. Bulk operations are not transactions." + : "Warning: This command is destructive. When invoked through MCP it always requires explicit user confirmation before it runs — even when a force or no-prompt argument is supplied. If the client cannot confirm, the command is refused."; } else { @@ -461,8 +464,7 @@ private static bool RequiresConfirmation(CommandFactory command) var annotation = command.McpAnnotation; return command.McpRestricted && annotation is not null - && annotation.Confirmable - && annotation.Destructive; + && annotation.Confirmable; } private static bool IsExplicitJsonNull(JsonElement value) @@ -739,12 +741,12 @@ private async ValueTask OnCallToolsAsync( { // Multi-round-trip request: the client prompts the user and retries this call with the answer. // On sessions that predate MRTR, the SDK sends an elicitation request and retries for us. - prompt = (request, stateVersion, _) => throw new InputRequiredException( + prompt = (request, stateVersion, _, confirmationCommandLine) => throw new InputRequiredException( inputRequests: new Dictionary { [ConfirmationInputKey] = InputRequest.ForElicitation(request), }, - requestState: ConfirmationRequestState.Create(commandLine, stateVersion)); + requestState: ConfirmationRequestState.Create(confirmationCommandLine, stateVersion)); } return await this.ExecuteToolAsync(command, cmd, commandLine, prompt, cancellationToken, parameters.Params); @@ -760,15 +762,25 @@ internal async Task ExecuteToolAsync( { var shell = ShellInterpreter.Instance; long? confirmedVersion = null; + string? confirmedWorkingDirectory = null; if (RequiresConfirmation(command) && cmd is not BulkCommand { DryRun: true, Save: null }) { var snapshot = await shell.RunSerializedAsync( - () => Task.FromResult((Version: shell.StateVersion, Context: DescribeContext(shell.State))), cancellationToken); + () => + { + var workingDirectory = command.CommandName is "dir" or "cat" ? Directory.GetCurrentDirectory() : null; + var context = workingDirectory is null + ? DescribeContext(shell.State) + : $"Local working directory: {workingDirectory}"; + return Task.FromResult((Version: shell.StateVersion, Context: context, WorkingDirectory: workingDirectory)); + }, + cancellationToken); + var confirmationCommandLine = GetConfirmationCommandLine(commandLine, snapshot.WorkingDirectory); var confirmation = requestParams?.InputResponses?.TryGetValue(ConfirmationInputKey, out var response) == true ? this.EvaluateConfirmationResponse( - response, requestParams.RequestState, command.CommandName, commandLine, snapshot.Version) - : await this.ConfirmDestructiveAsync( - prompt, command.CommandName, commandLine, cancellationToken, snapshot.Context, snapshot.Version); + response, requestParams.RequestState, command.CommandName, confirmationCommandLine, snapshot.Version) + : await this.ConfirmCommandAsync( + prompt, command.CommandName, commandLine, cancellationToken, snapshot.Context, snapshot.Version, snapshot.WorkingDirectory); if (confirmation != null) { @@ -776,6 +788,7 @@ internal async Task ExecuteToolAsync( } confirmedVersion = snapshot.Version; + confirmedWorkingDirectory = snapshot.WorkingDirectory; } this.logger?.LogTrace($"Requested '{command.CommandName}'."); @@ -786,7 +799,9 @@ internal async Task ExecuteToolAsync( return await shell.RunSerializedAsync( async () => { - if (confirmedVersion.HasValue && confirmedVersion.Value != shell.StateVersion) + if ((confirmedVersion.HasValue && confirmedVersion.Value != shell.StateVersion) + || (confirmedWorkingDirectory is not null + && !string.Equals(confirmedWorkingDirectory, Directory.GetCurrentDirectory(), StringComparison.Ordinal))) { return McpResponseFactory.CreateError(ContextChangedMessage, shell.State); } @@ -879,43 +894,51 @@ private static string DescribeContext(State state) return this.EvaluateElicitResult(result, commandName); } - // Gates a destructive command behind a user confirmation. Returns null when the + private static string GetConfirmationCommandLine(string commandLine, string? workingDirectory) + { + return workingDirectory is null ? commandLine : JsonSerializer.Serialize(new[] { commandLine, workingDirectory }); + } + + // Gates a restricted command behind a user confirmation. Returns null when the // operation is approved and should proceed; otherwise returns the CallToolResult // to send back (refusal, denial, or a failed confirmation). A prompt may instead // throw InputRequiredException, which ends this call and asks the client to retry // with the user's answer. Fails closed: when the client cannot confirm, the // command is refused rather than executed. - internal async ValueTask ConfirmDestructiveAsync( + internal async ValueTask ConfirmCommandAsync( ConfirmationPrompt? prompt, string commandName, string commandLine, CancellationToken cancellationToken, string? context = null, - long stateVersion = 0) + long stateVersion = 0, + string? workingDirectory = null) { if (prompt == null) { this.logger?.LogWarning( - "Destructive command '{Command}' requires confirmation, but the MCP client does not support elicitation.", + "Command '{Command}' requires confirmation, but the MCP client does not support elicitation.", commandName); return McpResponseFactory.CreateError( - $"Command '{commandName}' is destructive and needs your confirmation, but this MCP client does not support confirmation prompts (elicitation). Run '{commandLine}' manually in the shell.", + $"Command '{commandName}' {(workingDirectory is null ? "is destructive" : "accesses the local filesystem")} and needs your confirmation, but this MCP client does not support confirmation prompts (elicitation). Run '{commandLine}' manually in the shell.", ShellInterpreter.Instance.State); } var request = new ElicitRequestParams { Message = - $"Confirm destructive operation. The agent wants to run: {commandLine}\n" + + $"Confirm {(workingDirectory is null ? "destructive operation" : "local filesystem access")}. The agent wants to run: {commandLine}\n" + (context is null ? string.Empty : context + "\n") + - "This can permanently change or delete data in the connected Azure Cosmos DB account and cannot be undone. Approve this operation?", + (workingDirectory is null + ? "This can permanently change or delete data in the connected Azure Cosmos DB account and cannot be undone. Approve this operation?" + : "This reads local file contents or lists local files and directories. The results will be returned to the MCP client and may contain sensitive information. Approve this operation?"), RequestedSchema = new ElicitRequestParams.RequestSchema(), }; ElicitResult result; try { - result = await prompt(request, stateVersion, cancellationToken); + result = await prompt(request, stateVersion, cancellationToken, GetConfirmationCommandLine(commandLine, workingDirectory)); } catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { @@ -927,7 +950,7 @@ private static string DescribeContext(State state) } catch (Exception ex) when (ex is not OperationCanceledException) { - this.logger?.LogWarning(ex, "Confirmation prompt for destructive command '{Command}' failed.", commandName); + this.logger?.LogWarning(ex, "Confirmation prompt for command '{Command}' failed.", commandName); return McpResponseFactory.CreateError( $"Confirmation for '{commandName}' could not be completed ({ex.GetType().Name}). Nothing was executed.", ShellInterpreter.Instance.State); @@ -942,7 +965,7 @@ private static string DescribeContext(State state) { var action = string.IsNullOrEmpty(result?.Action) ? "cancel" : result.Action; this.logger?.LogInformation( - "User did not approve destructive command '{Command}' (action={Action}).", + "User did not approve command '{Command}' (action={Action}).", commandName, action); return McpResponseFactory.CreateError( @@ -950,7 +973,7 @@ private static string DescribeContext(State state) ShellInterpreter.Instance.State); } - this.logger?.LogInformation("User approved destructive command '{Command}'.", commandName); + this.logger?.LogInformation("User approved command '{Command}'.", commandName); return null; } } diff --git a/docs/mcp.md b/docs/mcp.md index c7691036..8c5e02bf 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -121,6 +121,23 @@ Confirmation includes the connected account endpoint and current navigation loca 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. +### Local Filesystem Read Confirmation + +The `dir` and `cat` tools also require explicit user confirmation before accessing +the local filesystem. `dir` lists local files and directories; `cat` reads local +file contents. Their results are returned to the MCP client and may expose +sensitive information. These tools remain read-only, not destructive. + +The prompt shows the exact command, including filters and options, and the local +working directory used for relative paths. Approval is bound to both that command +and working directory, using the same single-use, expiring confirmation as +destructive commands. Declined, cancelled, invalid, or unavailable confirmation +prevents execution. A changed working directory or shell context requires a new +confirmation. + +Interactive shell use is unchanged. Cosmos DB navigation with `cd` and listing +with `ls` do not require this filesystem confirmation. + 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. For single-item deletions, prefer `rm` with `key: "id"`, `partition-key`, and `dry-run: true` first, then repeat the call with the returned `etag` in the `etag` argument. The confirmation prompt shows the `--partition-key` and `--etag` values, and the delete only succeeds if the item still has the reviewed ETag, including when the item changes while the confirmation is pending. See [Deleting a single item safely](commands.md#deleting-a-single-item-safely). From 05e42dba3de06e5b4c5b383e78f057d82c301a23 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mike=20Kr=C3=BCger?= Date: Fri, 20 Nov 2026 18:32:07 +0100 Subject: [PATCH 2/6] Preserve boolean options in MCP confirmation commands --- CosmosDBShell.Tests/McpConfirmationTests.cs | 4 ++-- .../ToolOperationsCallToolTests.cs | 23 ++++++++++++++++--- .../ToolOperations.cs | 5 ++++ 3 files changed, 27 insertions(+), 5 deletions(-) diff --git a/CosmosDBShell.Tests/McpConfirmationTests.cs b/CosmosDBShell.Tests/McpConfirmationTests.cs index 8618954a..7038e2a1 100644 --- a/CosmosDBShell.Tests/McpConfirmationTests.cs +++ b/CosmosDBShell.Tests/McpConfirmationTests.cs @@ -32,8 +32,8 @@ public async Task LocalFilesystemRead_OverHttp_RequiresApproval(string commandNa timeout.CancelAfter(TimeSpan.FromSeconds(10)); using var host = McpServer.CreateHost(new Program.CosmosShellOptions { McpPort = 0 }); await host.StartAsync(timeout.Token); - var directory = Path.Combine(Path.GetTempPath(), $"mcp-local-read-{Guid.NewGuid():N}"); - var file = Path.Combine(directory, "sample.txt"); + var directory = Path.Join(Path.GetTempPath(), $"mcp-local-read-{Guid.NewGuid():N}"); + var file = Path.Join(directory, "sample.txt"); try { Directory.CreateDirectory(directory); diff --git a/CosmosDBShell.Tests/ToolOperationsCallToolTests.cs b/CosmosDBShell.Tests/ToolOperationsCallToolTests.cs index 89f57210..f47c629e 100644 --- a/CosmosDBShell.Tests/ToolOperationsCallToolTests.cs +++ b/CosmosDBShell.Tests/ToolOperationsCallToolTests.cs @@ -15,6 +15,7 @@ namespace CosmosShell.Tests; using Azure.Data.Cosmos.Shell.Core; using Azure.Data.Cosmos.Shell.Commands; using Azure.Data.Cosmos.Shell.Mcp; +using Azure.Data.Cosmos.Shell.Parser; using Azure.Data.Cosmos.Shell.States; using Microsoft.Extensions.Logging.Abstractions; @@ -247,9 +248,9 @@ public async Task CallTool_LocalFilesystemReadsWithoutConfirmation_RefuseBeforeA [InlineData("cat", "throw")] public async Task ExecuteTool_LocalFilesystemReads_OnlyAccessFilesAfterApproval(string commandName, string action) { - var directory = Path.Combine(Path.GetTempPath(), $"cosmos-mcp-read-{Guid.NewGuid():N}"); + var directory = Path.Join(Path.GetTempPath(), $"cosmos-mcp-read-{Guid.NewGuid():N}"); Directory.CreateDirectory(directory); - var file = Path.Combine(directory, "sample.txt"); + var file = Path.Join(directory, "sample.txt"); const string content = "local file confirmation test"; await File.WriteAllTextAsync(file, content, TestContext.Current.CancellationToken); var shell = ShellInterpreter.Instance; @@ -329,7 +330,7 @@ public async Task ExecuteTool_LocalFilesystemConfirmationRetry_BindsWorkingDirec inputRequests: new Dictionary { ["confirm"] = InputRequest.ForElicitation(request) }, requestState: ConfirmationRequestState.Create( differentDirectory - ? JsonSerializer.Serialize(new[] { commandLine, Path.Combine(Directory.GetCurrentDirectory(), "other") }) + ? JsonSerializer.Serialize(new[] { commandLine, Path.Join(Directory.GetCurrentDirectory(), "other") }) : confirmationCommandLine, stateVersion)), TestContext.Current.CancellationToken)); @@ -769,6 +770,22 @@ public void HistoryFormatting_UsesInvariantCultureForOptionsAndPositionals() } } + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task FormatOptionForHistory_BooleanRoundTripsWithoutAddingAFilter(bool recursive) + { + var shell = ShellInterpreter.Instance; + var factory = shell.App.Commands["dir"]; + var option = factory.Options.Single(o => o.Name[0] == "recursive"); + var parser = new StatementParser("dir" + ToolOperations.FormatOptionForHistory(option, recursive)); + var statement = Assert.IsType(Assert.Single(parser.ParseStatements())); + var command = Assert.IsType(await statement.CreateCommandAsync(factory, shell, new CommandState(), TestContext.Current.CancellationToken)); + + Assert.Equal(recursive, command.Recursive); + Assert.Null(command.Filter); + } + [Fact] public async Task CallTool_NullNullableValueOption_IsOmitted() { diff --git a/CosmosDBShell/Azure.Data.Cosmos.Shell.Mcp/ToolOperations.cs b/CosmosDBShell/Azure.Data.Cosmos.Shell.Mcp/ToolOperations.cs index 99adbe51..240a7106 100644 --- a/CosmosDBShell/Azure.Data.Cosmos.Shell.Mcp/ToolOperations.cs +++ b/CosmosDBShell/Azure.Data.Cosmos.Shell.Mcp/ToolOperations.cs @@ -263,6 +263,11 @@ internal static bool MatchesArgumentName(string[] names, string? argumentName) internal static string FormatOptionForHistory(Option option, object? value) { + if (value is bool flag) + { + return $" --{option.Name[0]}={(flag ? "true" : "false")}"; + } + return $" --{option.Name[0]} {ShellLiteral.Quote(FormatValueForHistory(value))}"; } From 4e022cacdc728ebf868fb1f75b52023307d44bff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mike=20Kr=C3=BCger?= Date: Fri, 20 Nov 2026 20:14:52 +0100 Subject: [PATCH 3/6] Prevent emulator startup updates from breaking PostgreSQL --- .github/workflows/integration-tests.yml | 3 +++ CONTRIBUTING.md | 7 +++++++ 2 files changed, 10 insertions(+) diff --git a/.github/workflows/integration-tests.yml b/.github/workflows/integration-tests.yml index e2e0dc9e..22a67862 100644 --- a/.github/workflows/integration-tests.yml +++ b/.github/workflows/integration-tests.yml @@ -47,6 +47,9 @@ jobs: services: cosmosdb: image: mcr.microsoft.com/cosmosdb/linux/azure-cosmos-emulator:vnext-preview + # Prevent startup package updates from replacing modules under running PostgreSQL. + # Remove when Azure/azure-cosmos-db-emulator-docker#390 is fixed in this image. + options: --add-host packages.microsoft.com:127.0.0.1 ports: - 8081:8081 env: diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 843fddf4..8134149a 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -175,6 +175,13 @@ You can develop and test without an Azure subscription by using the [Azure Cosmo dotnet run --project CosmosDBShell/CosmosDBShell.csproj -- --connect "https://localhost:8081" ``` +For Linux preview emulator HTTP 500 errors with `PostgresError(SqlState(E58P01))`, +see [the upstream startup package-update issue](https://github.com/Azure/azure-cosmos-db-emulator-docker/issues/390). +The integration workflow temporarily starts the service with +`--add-host packages.microsoft.com:127.0.0.1` to prevent package updates from +replacing PostgreSQL modules while the server is running. The workaround does not +skip tests or suppress emulator errors and should be removed once the image is fixed. + ### Live Serverless Smoke Test The emulator cannot reproduce serverless behavior. To verify database and container creation against a real serverless account, set `COSMOSDB_SHELL_SERVERLESS_TEST_CONNECTION_STRING` to that account's connection string and run the `LiveServerless` test category. The test creates and then deletes a uniquely named database; without the variable, it is skipped. From d89a28b9009e686a39446f0f3a580c9ead1c15a0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mike=20Kr=C3=BCger?= Date: Mon, 23 Nov 2026 10:27:45 +0100 Subject: [PATCH 4/6] Restrict MCP filesystem tools and confirm file transfers (#305) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- CosmosDBShell.Tests/McpConfirmationTests.cs | 94 +++++++++--- .../ToolOperationsCallToolTests.cs | 139 +++++++++--------- CosmosDBShell.Tests/ToolOperationsTests.cs | 25 +++- .../CatCommand.cs | 2 +- .../DirCommand.cs | 2 +- .../ExportCommand.cs | 2 + .../HelpCommand.cs | 2 +- .../ImportCommand.cs | 2 + .../JqCommand.cs | 2 + .../ToolOperations.cs | 18 ++- docs/mcp.md | 20 ++- 11 files changed, 197 insertions(+), 111 deletions(-) diff --git a/CosmosDBShell.Tests/McpConfirmationTests.cs b/CosmosDBShell.Tests/McpConfirmationTests.cs index 7038e2a1..45326934 100644 --- a/CosmosDBShell.Tests/McpConfirmationTests.cs +++ b/CosmosDBShell.Tests/McpConfirmationTests.cs @@ -18,26 +18,30 @@ namespace CosmosShell.Tests; public class McpConfirmationTests { [Theory] - [InlineData("dir", "accept", null)] - [InlineData("cat", "accept", null)] - [InlineData("dir", "decline", null)] - [InlineData("cat", "decline", null)] - [InlineData("dir", "accept", "2025-11-25")] - [InlineData("cat", "accept", "2025-11-25")] - [InlineData("dir", "decline", "2025-11-25")] - [InlineData("cat", "decline", "2025-11-25")] - public async Task LocalFilesystemRead_OverHttp_RequiresApproval(string commandName, string action, string? requestedVersion) + [InlineData("import", "accept", null)] + [InlineData("export", "accept", null)] + [InlineData("import", "decline", null)] + [InlineData("export", "decline", null)] + [InlineData("import", "accept", "2025-11-25")] + [InlineData("export", "accept", "2025-11-25")] + [InlineData("import", "decline", "2025-11-25")] + [InlineData("export", "decline", "2025-11-25")] + public async Task FileTransfer_OverHttp_RequiresApproval(string commandName, string action, string? requestedVersion) { 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); var directory = Path.Join(Path.GetTempPath(), $"mcp-local-read-{Guid.NewGuid():N}"); - var file = Path.Join(directory, "sample.txt"); + var file = Path.Join(directory, "sample.json"); + var shell = Azure.Data.Cosmos.Shell.Core.ShellInterpreter.Instance; + var originalState = shell.State; try { + shell.State = new Azure.Data.Cosmos.Shell.States.DisconnectedState(); Directory.CreateDirectory(directory); - await File.WriteAllTextAsync(file, "approved local content", timeout.Token); + const string content = "[{\"id\":\"approved-local-content\"}]"; + await File.WriteAllTextAsync(file, content, timeout.Token); var prompts = new List(); var address = host.Services.GetRequiredService().Features.Get()!.Addresses.Single(); var transport = new HttpClientTransport(new HttpClientTransportOptions { Endpoint = new Uri(address.TrimEnd('/') + "/") }); @@ -56,28 +60,29 @@ public async Task LocalFilesystemRead_OverHttp_RequiresApproval(string commandNa }, }, cancellationToken: timeout.Token); - var arguments = commandName == "dir" - ? new Dictionary { ["directory"] = directory, ["filter"] = "*.txt" } - : new Dictionary { ["path"] = file }; + var arguments = commandName == "import" + ? new Dictionary { ["file"] = file, ["dry-run"] = true } + : new Dictionary { ["file"] = file, ["force"] = true }; var result = await client.CallToolAsync(commandName, arguments, cancellationToken: timeout.Token); var prompt = Assert.Single(prompts); Assert.Contains("Confirm local filesystem access", prompt); - Assert.Contains(ShellLiteral.Quote(commandName == "dir" ? directory : file), prompt); + Assert.Contains(ShellLiteral.Quote(file), prompt); Assert.Contains(Directory.GetCurrentDirectory(), prompt); + Assert.Contains("Account:", prompt); + Assert.Contains("Current location:", prompt); Assert.DoesNotContain("destructive", prompt); - Assert.Equal(action != "accept", result.IsError == true); + Assert.Equal(action != "accept" || commandName == "export", result.IsError == true); using var document = JsonDocument.Parse(Assert.IsType(Assert.Single(result.Content)).Text); if (action == "accept") { - if (commandName == "cat") + if (commandName == "import") { - Assert.Equal("approved local content", document.RootElement.GetProperty("result").GetString()); + Assert.Equal(1, document.RootElement.GetProperty("result").GetProperty("validated").GetInt32()); } else { - var entry = Assert.Single(document.RootElement.GetProperty("result").GetProperty("values").EnumerateArray()); - Assert.Equal("sample.txt", entry.GetProperty("name").GetString()); + Assert.Contains("not connected", document.RootElement.GetProperty("error").GetString(), StringComparison.OrdinalIgnoreCase); } } else @@ -85,15 +90,64 @@ public async Task LocalFilesystemRead_OverHttp_RequiresApproval(string commandNa Assert.Contains("was not approved", document.RootElement.GetProperty("error").GetString()); Assert.False(document.RootElement.TryGetProperty("result", out _)); } + + Assert.Equal(content, await File.ReadAllTextAsync(file, timeout.Token)); } finally { await host.StopAsync(TestContext.Current.CancellationToken); + shell.State = originalState; File.Delete(file); Directory.Delete(directory); } } + [Theory] + [InlineData("cat", null)] + [InlineData("dir", null)] + [InlineData("jq", null)] + [InlineData("cat", "2025-11-25")] + [InlineData("dir", "2025-11-25")] + [InlineData("jq", "2025-11-25")] + public async Task RestrictedFilesystemCommand_OverHttp_RefusesEvenWithConfirmationSupport(string commandName, string? requestedVersion) + { + 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 = 0; + 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 = (_, _) => + { + prompts++; + return ValueTask.FromResult(new ElicitResult { Action = "accept" }); + }, + }, + }, + cancellationToken: timeout.Token); + var result = await client.CallToolAsync(commandName, cancellationToken: timeout.Token); + + Assert.True(result.IsError); + Assert.Equal(0, prompts); + using var document = JsonDocument.Parse(Assert.IsType(Assert.Single(result.Content)).Text); + Assert.Contains($"Command '{commandName}' is restricted for MCP", 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")] diff --git a/CosmosDBShell.Tests/ToolOperationsCallToolTests.cs b/CosmosDBShell.Tests/ToolOperationsCallToolTests.cs index f47c629e..d266711f 100644 --- a/CosmosDBShell.Tests/ToolOperationsCallToolTests.cs +++ b/CosmosDBShell.Tests/ToolOperationsCallToolTests.cs @@ -217,7 +217,31 @@ public async Task ConfirmDestructive_NoElicitationSupport_RefusesAndDoesNotExecu [InlineData("dir", "{\"directory\":\"missing-directory\",\"recursive\":true,\"list\":true}")] [InlineData("dir", "{\"d\":\"missing-directory\",\"r\":true,\"l\":true}")] [InlineData("cat", "{\"path\":\"missing-file.json\"}")] - public async Task CallTool_LocalFilesystemReadsWithoutConfirmation_RefuseBeforeAccess(string commandName, string argumentsJson) + [InlineData("jq", "{\"args\":[\"-n\",\"--rawfile\",\"text\",\"missing-file.json\",\"$text\"]}")] + public async Task CallTool_RestrictedFilesystemCommands_RefuseBeforeAccess(string commandName, string argumentsJson) + { + var history = ShellInterpreter.Instance.History.ToArray(); + var arguments = JsonSerializer.Deserialize>(argumentsJson); + var result = await CreateToolOperations().CallToolHandler( + CallContext(commandName, arguments), TestContext.Current.CancellationToken); + + var (isError, root, document) = ReadResult(result); + using (document) + { + Assert.True(isError); + Assert.Contains($"Command '{commandName}' is restricted for MCP", root.GetProperty("error").GetString()); + Assert.DoesNotContain("needs your confirmation", root.GetProperty("error").GetString()); + } + + Assert.Equal(history, ShellInterpreter.Instance.History); + } + + [Theory] + [InlineData("import", "{\"file\":\"missing-file.json\"}")] + [InlineData("import", "{\"file\":\"missing-file.json\",\"dry-run\":true}")] + [InlineData("export", "{\"file\":\"missing-file.json\"}")] + [InlineData("export", "{\"file\":\"missing-file.json\",\"force\":true}")] + public async Task CallTool_FileTransfersWithoutConfirmation_RefuseBeforeAccess(string commandName, string argumentsJson) { var history = ShellInterpreter.Instance.History.ToArray(); var arguments = JsonSerializer.Deserialize>(argumentsJson); @@ -238,87 +262,60 @@ public async Task CallTool_LocalFilesystemReadsWithoutConfirmation_RefuseBeforeA } [Theory] - [InlineData("dir", "accept")] - [InlineData("cat", "accept")] - [InlineData("dir", "decline")] - [InlineData("cat", "decline")] - [InlineData("dir", "cancel")] - [InlineData("cat", "cancel")] - [InlineData("dir", "throw")] - [InlineData("cat", "throw")] - public async Task ExecuteTool_LocalFilesystemReads_OnlyAccessFilesAfterApproval(string commandName, string action) + [InlineData("import", "accept")] + [InlineData("export", "accept")] + [InlineData("import", "decline")] + [InlineData("export", "decline")] + [InlineData("import", "cancel")] + [InlineData("export", "cancel")] + [InlineData("import", "throw")] + [InlineData("export", "throw")] + public async Task ExecuteTool_FileTransfers_OnlyExecuteAfterApproval(string commandName, string action) { - var directory = Path.Join(Path.GetTempPath(), $"cosmos-mcp-read-{Guid.NewGuid():N}"); - Directory.CreateDirectory(directory); - var file = Path.Join(directory, "sample.txt"); - const string content = "local file confirmation test"; - await File.WriteAllTextAsync(file, content, TestContext.Current.CancellationToken); var shell = ShellInterpreter.Instance; - CosmosCommand command = commandName == "dir" - ? new DirCommand { Directory = directory, Filter = "*.txt", Recursive = true, ListOnly = true } - : new CatCommand { FilePath = file }; - var commandLine = commandName == "dir" - ? $"dir \"*.txt\" --directory \"{directory}\" --recursive --list" - : $"cat \"{file}\""; + var command = new TrackingCommand(); + var commandLine = $"{commandName} \"sample.json\""; var history = shell.History.ToArray(); - try - { - var result = await CreateToolOperations().ExecuteToolAsync( - shell.App.Commands[commandName], command, commandLine, - (request, _, _, confirmationCommandLine) => - { - Assert.Contains("Confirm local filesystem access", request.Message); - Assert.Contains(commandLine, request.Message); - Assert.Contains(Directory.GetCurrentDirectory(), request.Message); - Assert.Contains("returned to the MCP client", request.Message); - Assert.DoesNotContain("permanently change or delete", request.Message); - Assert.Equal( - new[] { commandLine, Directory.GetCurrentDirectory() }, - JsonSerializer.Deserialize(confirmationCommandLine)); - if (action == "throw") - { - throw new InvalidOperationException("prompt failed"); - } - - return new ValueTask(new ElicitResult { Action = action }); - }, TestContext.Current.CancellationToken); - - var (isError, root, document) = ReadResult(result); - using (document) + var result = await CreateToolOperations().ExecuteToolAsync( + shell.App.Commands[commandName], command, commandLine, + (request, _, _, confirmationCommandLine) => { - Assert.Equal(action != "accept", isError); - if (action == "accept") - { - if (commandName == "cat") - { - Assert.Equal(content, root.GetProperty("result").GetString()); - } - else - { - var entry = Assert.Single(root.GetProperty("result").GetProperty("values").EnumerateArray()); - Assert.Equal("sample.txt", entry.GetProperty("name").GetString()); - Assert.Equal(file, entry.GetProperty("path").GetString()); - } - } - else + Assert.Contains("Confirm local filesystem access", request.Message); + Assert.Contains(commandLine, request.Message); + Assert.Contains(Directory.GetCurrentDirectory(), request.Message); + Assert.Contains("Account:", request.Message); + Assert.Contains("Current location:", request.Message); + Assert.Contains(commandName == "import" ? "upload its contents" : "overwrite an existing file", request.Message); + Assert.DoesNotContain("permanently change or delete", request.Message); + Assert.Equal( + new[] { commandLine, Directory.GetCurrentDirectory() }, + JsonSerializer.Deserialize(confirmationCommandLine)); + if (action == "throw") { - Assert.Equal(history, shell.History); - Assert.False(root.TryGetProperty("result", out _)); + throw new InvalidOperationException("prompt failed"); } - } - } - finally + + return new ValueTask(new ElicitResult { Action = action }); + }, TestContext.Current.CancellationToken); + + var (isError, root, document) = ReadResult(result); + using (document) { - File.Delete(file); - Directory.Delete(directory); + Assert.Equal(action != "accept", isError); + Assert.Equal(action == "accept", command.Executed); + if (action != "accept") + { + Assert.Equal(history, shell.History); + Assert.False(root.TryGetProperty("result", out _)); + } } } [Theory] - [InlineData("dir", false)] - [InlineData("cat", false)] - [InlineData("dir", true)] - [InlineData("cat", true)] + [InlineData("import", false)] + [InlineData("export", false)] + [InlineData("import", true)] + [InlineData("export", true)] public async Task ExecuteTool_LocalFilesystemConfirmationRetry_BindsWorkingDirectory(string commandName, bool differentDirectory) { var shell = ShellInterpreter.Instance; diff --git a/CosmosDBShell.Tests/ToolOperationsTests.cs b/CosmosDBShell.Tests/ToolOperationsTests.cs index 3e14f3d7..50e8d765 100644 --- a/CosmosDBShell.Tests/ToolOperationsTests.cs +++ b/CosmosDBShell.Tests/ToolOperationsTests.cs @@ -331,7 +331,26 @@ public void GetTool_MarksStoredProceduresRestrictedForMcp() [Theory] [InlineData("dir")] [InlineData("cat")] - public void GetTool_LocalFilesystemReads_RequireConfirmationWithoutDestructiveHints(string commandName) + [InlineData("jq")] + public void GetTool_LocalFilesystemCommands_AreRestricted(string commandName) + { + var factory = new CommandRunner().Commands[commandName]; + var tool = ToolOperations.GetTool(factory); + + Assert.True(factory.McpRestricted); + Assert.False(factory.McpAnnotation!.Confirmable); + Assert.Contains("cannot be invoked through MCP", tool.Description); + Assert.DoesNotContain("requires explicit user confirmation", tool.Description); + + var help = HelpCommand.PrintCommandHelp(commandName, new CommandRunner(), plain: true); + var helpJson = Assert.IsType(help.Result).Value; + Assert.Contains("can't be run via MCP", helpJson.GetProperty("isRestricted").GetString()); + } + + [Theory] + [InlineData("import")] + [InlineData("export")] + public void GetTool_FileTransfers_RequireConfirmationWithoutDestructiveHints(string commandName) { var factory = new CommandRunner().Commands[commandName]; var tool = ToolOperations.GetTool(factory); @@ -339,11 +358,11 @@ public void GetTool_LocalFilesystemReads_RequireConfirmationWithoutDestructiveHi Assert.True(factory.McpRestricted); Assert.True(factory.McpAnnotation!.Confirmable); Assert.False(factory.McpAnnotation.Destructive); - Assert.Contains("local filesystem", tool.Description); + Assert.Contains("local files", tool.Description); Assert.Contains("requires explicit user confirmation", tool.Description); Assert.DoesNotContain("cannot be invoked through MCP", tool.Description); Assert.NotNull(tool.Annotations); - Assert.True(tool.Annotations.ReadOnlyHint); + Assert.NotEqual(true, tool.Annotations.ReadOnlyHint); Assert.NotEqual(true, tool.Annotations.DestructiveHint); var help = HelpCommand.PrintCommandHelp(commandName, new CommandRunner(), plain: true); diff --git a/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/CatCommand.cs b/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/CatCommand.cs index 3137596e..2d1a8f56 100644 --- a/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/CatCommand.cs +++ b/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/CatCommand.cs @@ -13,7 +13,7 @@ namespace Azure.Data.Cosmos.Shell.Commands; [CosmosCommand("cat")] [CosmosExample("cat config.json", DescriptionKey = "command-cat-example-1")] [CosmosExample("cat data.txt", DescriptionKey = "command-cat-example-2")] -[McpAnnotation(Restricted = true, Confirmable = true, ReadOnly = true, Idempotent = true)] +[McpAnnotation(Restricted = true, ReadOnly = true, Idempotent = true)] internal class CatCommand : CosmosCommand, IStateVisitor { [CosmosParameter("path", IsRequired = false, ParameterType = ParameterType.File)] diff --git a/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/DirCommand.cs b/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/DirCommand.cs index 1cf2c094..7776e7b8 100644 --- a/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/DirCommand.cs +++ b/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/DirCommand.cs @@ -24,7 +24,7 @@ namespace Azure.Data.Cosmos.Shell.Commands; [CosmosExample("dir *.cs --directory=src", DescriptionKey = "command-dir-example-5")] [CosmosExample("dir -r", DescriptionKey = "command-dir-example-6")] [CosmosExample("dir -l", DescriptionKey = "command-dir-example-7")] -[McpAnnotation(Restricted = true, Confirmable = true, ReadOnly = true, Idempotent = true)] +[McpAnnotation(Restricted = true, ReadOnly = true, Idempotent = true)] internal class DirCommand : CosmosCommand { [CosmosParameter("filter", IsRequired = false)] diff --git a/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/ExportCommand.cs b/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/ExportCommand.cs index 80abbc7c..e261f310 100644 --- a/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/ExportCommand.cs +++ b/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/ExportCommand.cs @@ -28,6 +28,8 @@ internal enum ExportFormat [CosmosExample("export items.json --db=MyDB --con=Products --max=1000", DescriptionKey = "command-export-example-5")] [McpAnnotation( Title = "Export Container Items", + Restricted = true, + Confirmable = true, ReadOnly = false, Idempotent = false, OpenWorld = true, diff --git a/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/HelpCommand.cs b/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/HelpCommand.cs index a0a29f96..2469f4d5 100644 --- a/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/HelpCommand.cs +++ b/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/HelpCommand.cs @@ -408,7 +408,7 @@ public static CommandState PrintCommandHelp(string cmdStr, CommandRunner app, bo { helpJson["isRestricted"] = cmd.CommandName == "bulk" ? MessageService.GetString("command-bulk-mcp-help") - : cmd.CommandName is "dir" or "cat" + : cmd.CommandName is "import" or "export" ? "Local filesystem access through MCP requires explicit user confirmation." : "This tool can't be run via MCP. User only."; } diff --git a/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/ImportCommand.cs b/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/ImportCommand.cs index 1f7b6162..f1ceba27 100644 --- a/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/ImportCommand.cs +++ b/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/ImportCommand.cs @@ -41,6 +41,8 @@ internal enum ImportMode [CosmosExample("import items.json --concurrency=32", DescriptionKey = "command-import-example-8")] [McpAnnotation( Title = "Import Container Items", + Restricted = true, + Confirmable = true, ReadOnly = false, Idempotent = false, OpenWorld = true, diff --git a/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/JqCommand.cs b/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/JqCommand.cs index 005ae34c..7eec76ac 100644 --- a/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/JqCommand.cs +++ b/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/JqCommand.cs @@ -5,6 +5,7 @@ namespace Azure.Data.Cosmos.Shell.Commands; using System.Diagnostics; +using Azure.Data.Cosmos.Shell.Mcp; using Azure.Data.Cosmos.Shell.Util; using global::Azure.Data.Cosmos.Shell.Core; @@ -12,6 +13,7 @@ namespace Azure.Data.Cosmos.Shell.Commands; [CosmosExample("echo '{\"a\":1}' | jq", DescriptionKey = "command-jq-example-1")] [CosmosExample("query \"SELECT * FROM c\" | jq '.items[0]'", DescriptionKey = "command-jq-example-2")] [CosmosExample("ls | jq 'length'", DescriptionKey = "command-jq-example-3")] +[McpAnnotation(Restricted = true)] internal class JqCommand : CosmosCommand { [CosmosParameter("args", IsRequired = false)] diff --git a/CosmosDBShell/Azure.Data.Cosmos.Shell.Mcp/ToolOperations.cs b/CosmosDBShell/Azure.Data.Cosmos.Shell.Mcp/ToolOperations.cs index 240a7106..45e4ba9c 100644 --- a/CosmosDBShell/Azure.Data.Cosmos.Shell.Mcp/ToolOperations.cs +++ b/CosmosDBShell/Azure.Data.Cosmos.Shell.Mcp/ToolOperations.cs @@ -91,8 +91,8 @@ internal static Tool GetTool(CommandFactory command) if (RequiresConfirmation(command)) { - description += command.CommandName is "dir" or "cat" - ? "Warning: This command accesses the local filesystem and requires explicit user confirmation before it runs. File contents, names, and paths may contain sensitive information. If the client cannot confirm, the command is refused." + description += command.CommandName is "import" or "export" + ? "Warning: This command transfers data between local files and Cosmos DB and requires explicit user confirmation before it runs, including import dry runs and forced exports. Imports can upload sensitive file contents and exports can overwrite local files. If the client cannot confirm, the command is refused." : command.CommandName == "bulk" ? "Warning: Bulk writes and dry-run selections that save a plan require explicit user confirmation, even with yes=true. Only dry runs without save skip confirmation and issue no database writes. Bulk operations are not transactions." : "Warning: This command is destructive. When invoked through MCP it always requires explicit user confirmation before it runs — even when a force or no-prompt argument is supplied. If the client cannot confirm, the command is refused."; @@ -773,10 +773,12 @@ internal async Task ExecuteToolAsync( var snapshot = await shell.RunSerializedAsync( () => { - var workingDirectory = command.CommandName is "dir" or "cat" ? Directory.GetCurrentDirectory() : null; - var context = workingDirectory is null - ? DescribeContext(shell.State) - : $"Local working directory: {workingDirectory}"; + var workingDirectory = command.CommandName is "import" or "export" ? Directory.GetCurrentDirectory() : null; + var context = DescribeContext(shell.State); + if (workingDirectory is not null) + { + context += $"\nLocal working directory: {workingDirectory}"; + } return Task.FromResult((Version: shell.StateVersion, Context: context, WorkingDirectory: workingDirectory)); }, cancellationToken); @@ -936,7 +938,9 @@ private static string GetConfirmationCommandLine(string commandLine, string? wor (context is null ? string.Empty : context + "\n") + (workingDirectory is null ? "This can permanently change or delete data in the connected Azure Cosmos DB account and cannot be undone. Approve this operation?" - : "This reads local file contents or lists local files and directories. The results will be returned to the MCP client and may contain sensitive information. Approve this operation?"), + : commandName == "import" + ? "This reads a local data file and can upload its contents to the connected Azure Cosmos DB account. Dry runs still read and validate the file but do not upload it. The file may contain sensitive information. Approve this operation?" + : "This exports data from the connected Azure Cosmos DB account into a local file and can overwrite an existing file when force is supplied. The exported data may contain sensitive information. Approve this operation?"), RequestedSchema = new ElicitRequestParams.RequestSchema(), }; diff --git a/docs/mcp.md b/docs/mcp.md index 8c5e02bf..a844a360 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -121,14 +121,18 @@ Confirmation includes the connected account endpoint and current navigation loca 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. -### Local Filesystem Read Confirmation +### Local Filesystem Restrictions and Transfer Confirmation -The `dir` and `cat` tools also require explicit user confirmation before accessing -the local filesystem. `dir` lists local files and directories; `cat` reads local -file contents. Their results are returned to the MCP client and may expose -sensitive information. These tools remain read-only, not destructive. +The `cat`, `dir`, and `jq` commands cannot be invoked through MCP, even by clients +that support confirmation. Run them manually in the interactive shell. -The prompt shows the exact command, including filters and options, and the local +The `import` and `export` tools require explicit user confirmation before execution. +Imports read local data files and can upload their contents to Cosmos DB; exports +write database data to local files and can overwrite existing files with `force`. +Import dry runs also require confirmation because they still read local files. +The `force` argument does not bypass MCP confirmation. + +The prompt shows the exact command, including file paths and options, and the local working directory used for relative paths. Approval is bound to both that command and working directory, using the same single-use, expiring confirmation as destructive commands. Declined, cancelled, invalid, or unavailable confirmation @@ -136,7 +140,9 @@ prevents execution. A changed working directory or shell context requires a new confirmation. Interactive shell use is unchanged. Cosmos DB navigation with `cd` and listing -with `ls` do not require this filesystem confirmation. +with `ls` do not require this filesystem confirmation. These restrictions are not +a filesystem sandbox: other commands, including `bulk` file inputs and theme +operations, can still access local files. Use only trusted MCP clients. 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. From 2609f54a9a30745414567abf00799c1baec44fc8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mike=20Kr=C3=BCger?= Date: Mon, 23 Nov 2026 10:31:33 +0100 Subject: [PATCH 5/6] Fix MCP confirmation context formatting Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- CosmosDBShell/Azure.Data.Cosmos.Shell.Mcp/ToolOperations.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/CosmosDBShell/Azure.Data.Cosmos.Shell.Mcp/ToolOperations.cs b/CosmosDBShell/Azure.Data.Cosmos.Shell.Mcp/ToolOperations.cs index 45e4ba9c..17e0086f 100644 --- a/CosmosDBShell/Azure.Data.Cosmos.Shell.Mcp/ToolOperations.cs +++ b/CosmosDBShell/Azure.Data.Cosmos.Shell.Mcp/ToolOperations.cs @@ -779,6 +779,7 @@ internal async Task ExecuteToolAsync( { context += $"\nLocal working directory: {workingDirectory}"; } + return Task.FromResult((Version: shell.StateVersion, Context: context, WorkingDirectory: workingDirectory)); }, cancellationToken); From 222edc90c6c0c5d876b3884288211bf67094ab2d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mike=20Kr=C3=BCger?= Date: Mon, 23 Nov 2026 12:58:17 +0100 Subject: [PATCH 6/6] Pin passing emulator image for integration tests (#305) Avoid the rolling preview regression that returns HTTP 500 instead of 409 for duplicate creates. Keep all emulator assertions enabled. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .github/workflows/integration-tests.yml | 3 ++- CONTRIBUTING.md | 3 +++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/.github/workflows/integration-tests.yml b/.github/workflows/integration-tests.yml index 22a67862..532a9534 100644 --- a/.github/workflows/integration-tests.yml +++ b/.github/workflows/integration-tests.yml @@ -46,7 +46,8 @@ jobs: runs-on: ubuntu-latest services: cosmosdb: - image: mcr.microsoft.com/cosmosdb/linux/azure-cosmos-emulator:vnext-preview + # Pin the last passing preview image; newer previews return 500 for create conflicts. + image: mcr.microsoft.com/cosmosdb/linux/azure-cosmos-emulator@sha256:db53613dae19d0a3d5ad50688d14aa6e957af082dafea56b52e1bd3a6b3f1406 # Prevent startup package updates from replacing modules under running PostgreSQL. # Remove when Azure/azure-cosmos-db-emulator-docker#390 is fixed in this image. options: --add-host packages.microsoft.com:127.0.0.1 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 8134149a..baff521f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -169,6 +169,9 @@ Repository administrators should keep that check required, or require ### Running Against the Emulator +CI pins the Linux preview emulator image by digest to avoid rolling-tag regressions. +Update the pin only after the full Linux emulator suite passes with the replacement. + You can develop and test without an Azure subscription by using the [Azure Cosmos DB Emulator](https://learn.microsoft.com/azure/cosmos-db/emulator): ```bash