Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
117 changes: 117 additions & 0 deletions CosmosDBShell.Tests/McpConfirmationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<CosmosClient>();
cosmos.Endpoint.Returns(new Uri("https://example.invalid"));
var database = Substitute.For<Database>();
var container = Substitute.For<Container>();
cosmos.GetDatabase(databaseName).Returns(database);
cosmos.GetDatabaseQueryIterator<DatabaseProperties>()
.Returns(_ => ScriptMocks.SinglePage<DatabaseProperties>([new DatabaseProperties { Id = databaseName }]));
var databaseRead = Substitute.For<DatabaseResponse>();
databaseRead.StatusCode.Returns(HttpStatusCode.OK);
database.ReadAsync(cancellationToken: Arg.Any<CancellationToken>()).Returns(databaseRead);
database.GetContainer(containerName).Returns(container);
database.GetContainerQueryIterator<ContainerProperties>()
.Returns(_ => ScriptMocks.SinglePage<ContainerProperties>([new ContainerProperties(containerName, "/id")]));
database.DeleteAsync(cancellationToken: Arg.Any<CancellationToken>()).Returns(Substitute.For<DatabaseResponse>());
container.DeleteContainerAsync(cancellationToken: Arg.Any<CancellationToken>()).Returns(Substitute.For<ContainerResponse>());

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<string?>();
var address = host.Services.GetRequiredService<IServer>().Features.Get<IServerAddressesFeature>()!.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<string, object?> { ["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<TextContentBlock>(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<CancellationToken>());
await container.Received(approved && isContainer ? 1 : 0).DeleteContainerAsync(cancellationToken: Arg.Any<CancellationToken>());
}
finally
{
await host.StopAsync(TestContext.Current.CancellationToken);
shell.State = originalState;
}
}

[Theory]
[InlineData("import", "accept", null)]
[InlineData("export", "accept", null)]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,9 @@ private async Task<ExitCode> 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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,9 @@ private async Task<ExitCode> 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);
Expand Down
3 changes: 3 additions & 0 deletions CosmosDBShell/Azure.Data.Cosmos.Shell.Core/CommandState.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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; }

Expand Down
2 changes: 2 additions & 0 deletions CosmosDBShell/Azure.Data.Cosmos.Shell.Mcp/ToolOperations.cs
Original file line number Diff line number Diff line change
Expand Up @@ -820,6 +820,7 @@ internal async Task<CallToolResult> ExecuteToolAsync(
try
{
shell.PrintCommand(commandLine);
commandState.McpApprovedCommand = confirmedVersion.HasValue ? cmd : null;
if (cmd is BulkCommand bulk)
{
bulk.ConfirmationApproved = confirmedVersion.HasValue;
Expand All @@ -844,6 +845,7 @@ internal async Task<CallToolResult> ExecuteToolAsync(
}
finally
{
commandState.McpApprovedCommand = null;
shell.IsMcpInvocation = previousMcpInvocation;
shell.RefreshPrompt();
}
Expand Down
2 changes: 2 additions & 0 deletions docs/mcp.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down