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
2 changes: 1 addition & 1 deletion CosmosDBShell.Tests/CommandTests/BulkCommandTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2195,7 +2195,7 @@ public void McpSchemaExposesSafeBoundsAndDescribesSubcommands()
Assert.Contains("subcommand", tool.InputSchema.GetProperty("required").EnumerateArray().Select(value => value.GetString()));
Assert.Contains("patch --where", tool.Description);
Assert.Contains("saving a plan creates a server-local file and requires confirmation", tool.Description);
Assert.Contains("Only dry runs without save skip confirmation", tool.Description);
Assert.Contains("Only dry runs without --save skip confirmation", tool.Description);
Assert.True(factory.McpAnnotation!.Confirmable);
}

Expand Down
32 changes: 32 additions & 0 deletions CosmosDBShell.Tests/HelpCommandVerificationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,44 @@ namespace CosmosShell.Tests;
using System.Text;
using Azure.Data.Cosmos.Shell.Commands;
using Azure.Data.Cosmos.Shell.Core;
using Azure.Data.Cosmos.Shell.Mcp;
using Azure.Data.Cosmos.Shell.Parser;
using Spectre.Console;
using Xunit;

[Collection(ConsoleOutputTestCollection.Name)]
public class HelpCommandVerificationTests
{
[Theory]
[InlineData("rmcon", true, "requires explicit user confirmation")]
[InlineData("import", true, "including import dry runs and forced exports")]
[InlineData("export", true, "including import dry runs and forced exports")]
[InlineData("edit", false, "cannot be invoked through MCP")]
[InlineData("bulk", true, "Only dry runs without --save skip confirmation")]
public async Task HelpAndMcpToolDescribeTheSameRestriction(string commandName, bool confirmable, string expected)
{
using var shell = ShellInterpreter.CreateInstance();
var app = shell.App;
var command = new HelpCommand { Command = commandName, Plain = true };
var token = TestContext.Current.CancellationToken;
var state = await command.ExecuteAsync(shell, new CommandState(), "help", token);
var json = Assert.IsType<ShellJson>(state.Result).Value;
var restriction = json.GetProperty("isRestricted").GetString()!;
Assert.Contains(expected, restriction);
Assert.Equal(confirmable, json.GetProperty("mcpConfirmable").GetBoolean());
Assert.Contains(restriction, ToolOperations.GetTool(app.Commands[commandName]).Description);
Assert.Contains(restriction, await RenderAsync(shell, command));
Assert.Contains(restriction, await RenderAsync(shell, new HelpCommand { Command = commandName }));

var overview = await new HelpCommand().ExecuteAsync(shell, new CommandState(), "help", token);
var commands = Assert.IsType<ShellJson>(overview.Result).Value.GetProperty("commands");
var entry = Assert.Single(commands.EnumerateArray(), entry => entry.GetProperty("command").GetString() == commandName);
Assert.True(entry.GetProperty("mcpRestricted").GetBoolean());
Assert.Equal(confirmable, entry.GetProperty("mcpConfirmable").GetBoolean());
var unrestricted = Assert.Single(commands.EnumerateArray(), entry => entry.GetProperty("command").GetString() == "query");
Assert.False(unrestricted.TryGetProperty("mcpConfirmable", out _));
}

[Theory]
[InlineData(false, false)]
[InlineData(true, false)]
Expand Down
10 changes: 8 additions & 2 deletions CosmosDBShell.Tests/ToolOperationsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -344,7 +344,10 @@ public void GetTool_LocalFilesystemCommands_AreRestricted(string commandName)

var help = HelpCommand.PrintCommandHelp(commandName, new CommandRunner(), plain: true);
var helpJson = Assert.IsType<ShellJson>(help.Result).Value;
Assert.Contains("can't be run via MCP", helpJson.GetProperty("isRestricted").GetString());
var restriction = helpJson.GetProperty("isRestricted").GetString()!;
Assert.Contains("cannot be invoked through MCP", restriction);
Assert.Contains(restriction, tool.Description);
Assert.False(helpJson.GetProperty("mcpConfirmable").GetBoolean());
}

[Theory]
Expand All @@ -367,7 +370,10 @@ public void GetTool_FileTransfers_RequireConfirmationWithoutDestructiveHints(str

var help = HelpCommand.PrintCommandHelp(commandName, new CommandRunner(), plain: true);
var helpJson = Assert.IsType<ShellJson>(help.Result).Value;
Assert.Contains("requires explicit user confirmation", helpJson.GetProperty("isRestricted").GetString());
var restriction = helpJson.GetProperty("isRestricted").GetString()!;
Assert.Contains("requires explicit user confirmation", restriction);
Assert.Contains(restriction, tool.Description);
Assert.True(helpJson.GetProperty("mcpConfirmable").GetBoolean());
}

[Fact]
Expand Down
14 changes: 14 additions & 0 deletions CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/CommandFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,20 @@ public McpAnnotationAttribute? McpAnnotation
/// </summary>
public bool McpRestricted { get => this.McpAnnotation?.Restricted ?? false; }

internal bool McpConfirmable => this.McpAnnotation is { Restricted: true, Confirmable: true };

internal string? McpRestrictionDescription => this.McpAnnotation switch
{
{ Restricted: true, Confirmable: true } => MessageService.GetString(this.CommandName switch
{
"bulk" => "command-bulk-mcp-help",
"import" or "export" => "help-mcp-file-transfer",
_ => "help-mcp-confirmable",
}),
{ Restricted: true } => MessageService.GetString("help-mcp-interactive-only"),
_ => null,
};

/// <summary>
/// Gets a value indicating whether the command returns bounded, resumable pages over MCP.
/// </summary>
Expand Down
17 changes: 11 additions & 6 deletions CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/HelpCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ public static CommandState PrintCommandHelp(string cmdStr, CommandRunner app, bo
return new CommandState();
}

var mcpRestriction = cmd.McpRestrictionDescription;
Action renderUser = () =>
{
if (plain)
Expand Down Expand Up @@ -359,6 +360,12 @@ public static CommandState PrintCommandHelp(string cmdStr, CommandRunner app, bo
}
}
}

if (mcpRestriction is not null)
{
ShellInterpreter.Instance.Output.WriteLine(ShellMessageKind.Result);
ShellInterpreter.Instance.Output.WriteLine(ShellMessageKind.Result, INDENT + mcpRestriction);
}
};

var commandState = new CommandState();
Expand Down Expand Up @@ -404,13 +411,10 @@ public static CommandState PrintCommandHelp(string cmdStr, CommandRunner app, bo

helpJson["options"] = options;

if (cmd is { McpAnnotation.Restricted: true })
if (mcpRestriction is not null)
{
helpJson["isRestricted"] = cmd.CommandName == "bulk"
? MessageService.GetString("command-bulk-mcp-help")
: 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.";
helpJson["isRestricted"] = mcpRestriction;
helpJson["mcpConfirmable"] = cmd!.McpConfirmable;
}

// Add statements JSON (for parity)
Expand Down Expand Up @@ -467,6 +471,7 @@ public override Task<CommandState> ExecuteAsync(ShellInterpreter shell, CommandS
if (cmd.McpRestricted)
{
cmdInfo["mcpRestricted"] = true;
cmdInfo["mcpConfirmable"] = cmd.McpConfirmable;
}

var parameterNames = cmd.Parameters.Select(p => p.Name.FirstOrDefault() ?? string.Empty).Where(n => !string.IsNullOrEmpty(n)).ToList();
Expand Down
35 changes: 3 additions & 32 deletions CosmosDBShell/Azure.Data.Cosmos.Shell.Mcp/ToolOperations.cs
Original file line number Diff line number Diff line change
Expand Up @@ -78,31 +78,10 @@ private ValueTask<EmptyResult> UnsubscribeFromResourcesAsync(RequestContext<Unsu

internal static Tool GetTool(CommandFactory command)
{
var descriptionParts = new[] { command.Description, command.McpDescription }
var descriptionParts = new[] { command.Description, command.McpDescription, command.McpRestrictionDescription }
.Where(part => !string.IsNullOrWhiteSpace(part));
var description = string.Join("\n", descriptionParts);

if (command.McpRestricted)
{
if (description.Length > 0)
{
description += "\n";
}

if (RequiresConfirmation(command))
{
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
{
description += "Warning: This command is restricted to interactive use and cannot be invoked through MCP. Run it manually in the shell, or call 'help' for this command.";
}
}

var tool = new Tool
{
Name = command.CommandName,
Expand Down Expand Up @@ -464,14 +443,6 @@ private static string GetJsonSchemaType(Type targetType)
return "string";
}

private static bool RequiresConfirmation(CommandFactory command)
{
var annotation = command.McpAnnotation;
return command.McpRestricted
&& annotation is not null
&& annotation.Confirmable;
}

private static bool IsExplicitJsonNull(JsonElement value)
{
return value.ValueKind is JsonValueKind.Null;
Expand Down Expand Up @@ -571,7 +542,7 @@ private async ValueTask<CallToolResult> OnCallToolsAsync(
return McpResponseFactory.CreateError(errorMessage, ShellInterpreter.Instance.State);
}

if (command.McpRestricted && !RequiresConfirmation(command))
if (command.McpRestricted && !command.McpConfirmable)
{
this.logger?.LogWarning($"Command '{command.CommandName}' is restricted for MCP.");
return McpResponseFactory.CreateError(
Expand Down Expand Up @@ -768,7 +739,7 @@ internal async Task<CallToolResult> ExecuteToolAsync(
var shell = ShellInterpreter.Instance;
long? confirmedVersion = null;
string? confirmedWorkingDirectory = null;
if (RequiresConfirmation(command) && cmd is not BulkCommand { DryRun: true, Save: null })
if (command.McpConfirmable && cmd is not BulkCommand { DryRun: true, Save: null })
{
var snapshot = await shell.RunSerializedAsync(
() =>
Expand Down
13 changes: 8 additions & 5 deletions CosmosDBShell/lang/en.ftl
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,9 @@ help-commands = Commands:
help-examples = Examples:
help-examples-heading = Examples
help-aliases = Aliases:
help-mcp-interactive-only = This command is restricted to interactive use and cannot be invoked through MCP. Run it manually in the shell.
help-mcp-confirmable = This command can run through MCP but requires explicit user confirmation, even when a force or no-prompt argument is supplied. If the client cannot confirm, the command is refused.
help-mcp-file-transfer = Through MCP, 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.
help-OutputFormat = The output format to use (user, json, table, csv).
help-Quiet = Suppress informational messages, progress, banners, and command echoes. Preserve results, warnings, errors, and required authentication instructions.
help-topics = Help Topics
Expand Down Expand Up @@ -251,7 +254,7 @@ command-help-description-plain = Disable styling and colors for script or limite

command-rmdb-description = Removes database
command-rmdb-description-name = The database to remove.
command-rmdb-description-force = Force to remove the database without confirmation.
command-rmdb-description-force = Skip the interactive shell prompt. MCP still requires explicit user confirmation.
command-rmdb-description-dry-run = Preview the deletion without deleting the database.
command-rmdb-error-not_allowed_in_container = { error-not_allowed_in_container }
command-rmdb-error-database_not_found = Database { $db } not found.
Expand All @@ -261,7 +264,7 @@ command-rmdb-confirm_db_deletion = Are you sure you want to delete this database

command-rmcon-description = Removes container
command-rmcon-description-name = The database or container to remove.
command-rmcon-description-force = Force to remove the container without confirmation.
command-rmcon-description-force = Skip the interactive shell prompt. MCP still requires explicit user confirmation.
command-rmcon-description-database = The database containing the container to remove
command-rmcon-description-dry-run = Preview the deletion without deleting the container.
command-rmcon-deleted_container = Deleted container { $container }
Expand All @@ -271,7 +274,7 @@ command-rmcon-confirm_container_deletion = Are you sure you want to delete this

command-rm-description = Removes item from container
command-rm-description-pattern = The pattern for the items to remove.
command-rm-description-force = Force to remove items without confirmation.
command-rm-description-force = Skip the interactive shell prompt. MCP still requires explicit user confirmation.
command-rm-description-database = The database containing the items to remove
command-rm-description-container = The container containing the items to remove
command-rm-description-key = The property name to match the pattern against (defaults to partition key)
Expand Down Expand Up @@ -492,7 +495,7 @@ command-batch-error-not_active = No batch is in progress. Start one with 'batch
command-batch-error-failed = Batch failed with status { $status } and was rolled back (RU charge: { $charge })
command-batch-error-execution_failed = Failed to execute batch: { $status } - { $message }
command-bulk-description = Executes many independent write operations across partition keys with bounded concurrency, either in a single call (run, patch, delete) or as a stateful bulk job (begin, add, execute, cancel, status, show). Bulk jobs are not transactional: successful writes are not rolled back when others fail.
command-bulk-mcp-help = Available through MCP for the stateless run, patch, and delete subcommands. Writes and dry runs that save a plan require user confirmation; dry runs without --save skip confirmation and send no writes.
command-bulk-mcp-help = Available through MCP for the stateless run, patch, and delete subcommands. Writes and dry runs that save a plan require explicit user confirmation, even with yes=true. Only dry runs without --save skip confirmation and send no database writes. Bulk operations are not transactions.
command-bulk-description-subcommand = The action to perform: run, patch, delete, begin, add, execute, cancel, status, or show.
command-bulk-description-data = For run and add: operations as a JSON array or object (the batch schema plus optional partitionKey and ifMatch), or a path to a JSON array or JSON Lines file. Stateful jobs are limited to 10,000 operations and 64 MiB of canonical JSON; use bulk run for larger files.
command-bulk-description-where = For patch and delete: Cosmos SQL predicate over alias c that selects the target items.
Expand Down Expand Up @@ -992,7 +995,7 @@ command-disconnect-not_connected = Not connected to any account.
command-delete-description = Delete items/container or databases.
command-delete-description-item = The object to delete: item, container or database.
command-delete-description-pattern = The items/container/database to delete.
command-delete-description-force = Force to delete without confirmation.
command-delete-description-force = Skip the interactive shell prompt. MCP still requires explicit user confirmation.
command-delete-description-database = The database for the delete operation
command-delete-description-container = The container for deleting items
command-delete-description-dry-run = Preview the deletion without applying it.
Expand Down
4 changes: 2 additions & 2 deletions docs/commands.md
Original file line number Diff line number Diff line change
Expand Up @@ -1120,7 +1120,7 @@ Usage: rmdb name [force] [options]

Arguments:
name The database to remove
[force] Skip the confirmation prompt when `true` (Optional)
[force] Skip the interactive shell prompt when `true`. MCP still requires explicit user confirmation. (Optional)

Options:
--dry-run Preview the deletion without deleting the database
Expand All @@ -1135,7 +1135,7 @@ Usage: rmcon name [force] [options]

Arguments:
name The container to remove
[force] Skip the confirmation prompt when `true` (Optional)
[force] Skip the interactive shell prompt when `true`. MCP still requires explicit user confirmation. (Optional)

Options:
--database, --db
Expand Down
7 changes: 7 additions & 0 deletions docs/mcp.md
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,13 @@ Server-side programming commands — stored procedures (`sproc`), user-defined f

Transactional batches invoked through MCP must use the one-shot `batch run` subcommand. Stateful batch subcommands (`begin`, `add`, `execute`, `cancel`, `status`, and `show`, including their aliases) are restricted to the interactive shell because MCP tool calls share no client-specific batch state.

Command help and MCP tool descriptions explain whether a restricted command is
interactive-only or can run through MCP with confirmation. For restricted
commands, structured `help` includes `mcpConfirmable`: `false` means interactive
only; `true` means MCP can request confirmation. Per-command help retains the
`isRestricted` explanation, including any exceptions such as `bulk` dry runs
without `--save`. The command list retains `mcpRestricted`.

### Destructive Command Confirmation

Destructive commands (`delete`, `rm`, `rmcon`, `rmdb`) are gated behind an explicit user confirmation. When a client invokes one, the server sends the client an elicitation prompt describing the exact command line and waits for the user's answer before anything runs:
Expand Down
Loading