From bbba61f4fd3d2fb793f11a28a8bd6cecabed0599 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mike=20Kr=C3=BCger?= Date: Mon, 30 Nov 2026 13:35:36 +0100 Subject: [PATCH] Avoid a second console prompt after MCP deletion approval Refs #311 --- CosmosDBShell.Tests/McpConfirmationTests.cs | 117 ++++++++++++++++++ .../RmContainerCommand.cs | 4 +- .../RmDbCommand.cs | 4 +- .../CommandState.cs | 3 + .../ToolOperations.cs | 2 + docs/mcp.md | 2 + 6 files changed, 130 insertions(+), 2 deletions(-) diff --git a/CosmosDBShell.Tests/McpConfirmationTests.cs b/CosmosDBShell.Tests/McpConfirmationTests.cs index 45326934..58ec4e97 100644 --- a/CosmosDBShell.Tests/McpConfirmationTests.cs +++ b/CosmosDBShell.Tests/McpConfirmationTests.cs @@ -4,19 +4,136 @@ namespace CosmosShell.Tests; +using System.Net; using System.Text.Json; +using Azure.Data.Cosmos.Shell.Core; using Azure.Data.Cosmos.Shell.Mcp; +using Azure.Data.Cosmos.Shell.States; using Azure.Data.Cosmos.Shell.Util; +using CosmosShell.Tests.CommandTests; using Microsoft.AspNetCore.Hosting.Server; using Microsoft.AspNetCore.Hosting.Server.Features; +using Microsoft.Azure.Cosmos; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using ModelContextProtocol.Client; using ModelContextProtocol.Protocol; +using NSubstitute; [Collection(CosmosShell.Tests.Shell.ThemeStateTestCollection.Name)] public class McpConfirmationTests { + [Theory] + [InlineData("rmcon", "accept", null)] + [InlineData("rmdb", "accept", null)] + [InlineData("rmcon", "accept", "2025-11-25")] + [InlineData("rmdb", "accept", "2025-11-25")] + [InlineData("rmcon", "decline", null)] + [InlineData("rmdb", "decline", null)] + [InlineData("rmcon", null, null)] + [InlineData("rmdb", null, null)] + public async Task ResourceDeletion_OverHttp_RequiresOnlyMcpApproval(string commandName, string? action, string? requestedVersion) + { + const string databaseName = "ExampleShop"; + const string containerName = "ScratchProducts"; + var cosmos = Substitute.For(); + cosmos.Endpoint.Returns(new Uri("https://example.invalid")); + var database = Substitute.For(); + var container = Substitute.For(); + cosmos.GetDatabase(databaseName).Returns(database); + cosmos.GetDatabaseQueryIterator() + .Returns(_ => ScriptMocks.SinglePage([new DatabaseProperties { Id = databaseName }])); + var databaseRead = Substitute.For(); + databaseRead.StatusCode.Returns(HttpStatusCode.OK); + database.ReadAsync(cancellationToken: Arg.Any()).Returns(databaseRead); + database.GetContainer(containerName).Returns(container); + database.GetContainerQueryIterator() + .Returns(_ => ScriptMocks.SinglePage([new ContainerProperties(containerName, "/id")])); + database.DeleteAsync(cancellationToken: Arg.Any()).Returns(Substitute.For()); + container.DeleteContainerAsync(cancellationToken: Arg.Any()).Returns(Substitute.For()); + + 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 shell = ShellInterpreter.Instance; + var originalState = shell.State; + try + { + shell.State = new ConnectedState(cosmos); + 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 = action is null ? null : (request, _) => + { + prompts.Add(request?.Message); + return ValueTask.FromResult(new ElicitResult { Action = action }); + }, + }, + }, + cancellationToken: timeout.Token); + + var isContainer = commandName == "rmcon"; + var target = isContainer ? containerName : databaseName; + var arguments = new Dictionary { ["name"] = target }; + if (isContainer) + { + arguments["database"] = databaseName; + } + + var approved = action == "accept"; + if (!approved) + { + arguments["force"] = true; + } + + // The test host has no interactive console; accepted calls omit force. + var result = await client.CallToolAsync(commandName, arguments, cancellationToken: timeout.Token); + + if (action is null) + { + Assert.Empty(prompts); + } + else + { + var prompt = Assert.Single(prompts); + Assert.Contains(target, prompt); + Assert.Contains(databaseName, prompt); + Assert.Contains("example.invalid", prompt); + } + + Assert.Equal(!approved, result.IsError == true); + using var document = JsonDocument.Parse(Assert.IsType(Assert.Single(result.Content)).Text); + if (approved) + { + var payload = document.RootElement.GetProperty("result"); + Assert.True(payload.GetProperty("deleted").GetBoolean()); + Assert.False(payload.GetProperty("dryRun").GetBoolean()); + Assert.Equal(target, payload.GetProperty("id").GetString()); + Assert.Equal(isContainer ? "container" : "database", payload.GetProperty("type").GetString()); + } + else + { + Assert.False(document.RootElement.TryGetProperty("result", out _)); + } + + await database.Received(approved && !isContainer ? 1 : 0).DeleteAsync(cancellationToken: Arg.Any()); + await container.Received(approved && isContainer ? 1 : 0).DeleteContainerAsync(cancellationToken: Arg.Any()); + } + finally + { + await host.StopAsync(TestContext.Current.CancellationToken); + shell.State = originalState; + } + } + [Theory] [InlineData("import", "accept", null)] [InlineData("export", "accept", null)] diff --git a/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/RmContainerCommand.cs b/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/RmContainerCommand.cs index 5c07228b..6aa01004 100644 --- a/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/RmContainerCommand.cs +++ b/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/RmContainerCommand.cs @@ -98,7 +98,9 @@ private async Task RemoveContainerAsync(ConnectedState state, ShellInt return 0; } - if (this.Force == true || ShellInterpreter.Confirm("command-rmcon-confirm_container_deletion", shell)) + if (this.Force == true + || ReferenceEquals(this.Outcome?.McpApprovedCommand, this) + || ShellInterpreter.Confirm("command-rmcon-confirm_container_deletion", shell)) { await CosmosResourceFacade.DeleteContainerAsync(state, databaseName, containerName, token); CosmosCompleteCommand.ClearContainers(); diff --git a/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/RmDbCommand.cs b/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/RmDbCommand.cs index f7c698c7..b4c760e8 100644 --- a/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/RmDbCommand.cs +++ b/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/RmDbCommand.cs @@ -92,7 +92,9 @@ private async Task RemoveDatabaseAsync(ConnectedState state, ShellInte return 0; } - if (this.Force is true || ShellInterpreter.Confirm("command-rmdb-confirm_db_deletion", shell)) + if (this.Force is true + || ReferenceEquals(this.Outcome?.McpApprovedCommand, this) + || ShellInterpreter.Confirm("command-rmdb-confirm_db_deletion", shell)) { await CosmosResourceFacade.DeleteDatabaseAsync(state, databaseName, token); UpdateStateAfterDelete(shell, state.Client, state.ArmContext, databaseName); diff --git a/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/CommandState.cs b/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/CommandState.cs index a10ee540..e185affe 100644 --- a/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/CommandState.cs +++ b/CosmosDBShell/Azure.Data.Cosmos.Shell.Core/CommandState.cs @@ -78,6 +78,9 @@ internal ShellObject? Result internal long ResultVersion { get; private set; } + // Bind approval to the exact command, even if an execution path reuses this state. + internal CosmosCommand? McpApprovedCommand { get; set; } + // Set only by a pipe stage and consumed by the receiving command. internal bool HasPipelineInput { get; set; } diff --git a/CosmosDBShell/Azure.Data.Cosmos.Shell.Mcp/ToolOperations.cs b/CosmosDBShell/Azure.Data.Cosmos.Shell.Mcp/ToolOperations.cs index 94fd96ec..e16e93a3 100644 --- a/CosmosDBShell/Azure.Data.Cosmos.Shell.Mcp/ToolOperations.cs +++ b/CosmosDBShell/Azure.Data.Cosmos.Shell.Mcp/ToolOperations.cs @@ -820,6 +820,7 @@ internal async Task ExecuteToolAsync( try { shell.PrintCommand(commandLine); + commandState.McpApprovedCommand = confirmedVersion.HasValue ? cmd : null; if (cmd is BulkCommand bulk) { bulk.ConfirmationApproved = confirmedVersion.HasValue; @@ -844,6 +845,7 @@ internal async Task ExecuteToolAsync( } finally { + commandState.McpApprovedCommand = null; shell.IsMcpInvocation = previousMcpInvocation; shell.RefreshPrompt(); } diff --git a/docs/mcp.md b/docs/mcp.md index 5f8f523c..e7edd778 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -146,6 +146,8 @@ 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. +After MCP approval is validated, `rmcon` and `rmdb` run without a second terminal prompt, even on a headless server. Commands entered directly in the shell still prompt unless `force` is set or the command is a dry run. + 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). Database and container resource actions are executed through Azure Resource Manager when an ARM context is attached (Entra ID connections). MCP sessions connected with account keys, emulator credentials, or static data-plane tokens fall back to the Cosmos DB data plane for these actions.