diff --git a/.github/workflows/integration-tests.yml b/.github/workflows/integration-tests.yml index e2e0dc9e..532a9534 100644 --- a/.github/workflows/integration-tests.yml +++ b/.github/workflows/integration-tests.yml @@ -46,7 +46,11 @@ 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 ports: - 8081:8081 env: diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 843fddf4..baff521f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -169,12 +169,22 @@ 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 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. diff --git a/CosmosDBShell.Tests/McpConfirmationTests.cs b/CosmosDBShell.Tests/McpConfirmationTests.cs index 158f2cd4..45326934 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,137 @@ namespace CosmosShell.Tests; [Collection(CosmosShell.Tests.Shell.ThemeStateTestCollection.Name)] public class McpConfirmationTests { + [Theory] + [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.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); + 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('/') + "/") }); + 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 == "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(file), prompt); + Assert.Contains(Directory.GetCurrentDirectory(), prompt); + Assert.Contains("Account:", prompt); + Assert.Contains("Current location:", prompt); + Assert.DoesNotContain("destructive", prompt); + 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 == "import") + { + Assert.Equal(1, document.RootElement.GetProperty("result").GetProperty("validated").GetInt32()); + } + else + { + Assert.Contains("not connected", document.RootElement.GetProperty("error").GetString(), StringComparison.OrdinalIgnoreCase); + } + } + else + { + 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 f36870ae..d266711f 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; @@ -193,7 +194,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 +211,141 @@ 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\"}")] + [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); + + 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("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 shell = ShellInterpreter.Instance; + var command = new TrackingCommand(); + var commandLine = $"{commandName} \"sample.json\""; + var history = shell.History.ToArray(); + 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("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") + { + 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); + Assert.Equal(action == "accept", command.Executed); + if (action != "accept") + { + Assert.Equal(history, shell.History); + Assert.False(root.TryGetProperty("result", out _)); + } + } + } + + [Theory] + [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; + 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.Join(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 +428,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 +471,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 +490,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 +594,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 +620,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 +643,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 +665,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); @@ -631,6 +767,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() { @@ -1111,9 +1263,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..50e8d765 100644 --- a/CosmosDBShell.Tests/ToolOperationsTests.cs +++ b/CosmosDBShell.Tests/ToolOperationsTests.cs @@ -328,6 +328,48 @@ public void GetTool_MarksStoredProceduresRestrictedForMcp() Assert.True(tool.Annotations.OpenWorldHint); } + [Theory] + [InlineData("dir")] + [InlineData("cat")] + [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); + + Assert.True(factory.McpRestricted); + Assert.True(factory.McpAnnotation!.Confirmable); + Assert.False(factory.McpAnnotation.Destructive); + 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.NotEqual(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..2d1a8f56 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, 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..7776e7b8 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, 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 a1b4f66e..2469f4d5 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 "import" or "export" + ? "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.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/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..17e0086f 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 "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."; } else { @@ -260,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))}"; } @@ -461,8 +469,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 +746,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 +767,28 @@ 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 "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); + 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 +796,7 @@ internal async Task ExecuteToolAsync( } confirmedVersion = snapshot.Version; + confirmedWorkingDirectory = snapshot.WorkingDirectory; } this.logger?.LogTrace($"Requested '{command.CommandName}'."); @@ -786,7 +807,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 +902,53 @@ 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?" + : 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(), }; 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 +960,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 +975,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 +983,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..a844a360 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -121,6 +121,29 @@ 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 Restrictions and Transfer Confirmation + +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 `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 +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. 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. 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).