diff --git a/CosmosDBShell.Tests/CommandTests/BulkCommandTests.cs b/CosmosDBShell.Tests/CommandTests/BulkCommandTests.cs index 2f06e108..02b955e2 100644 --- a/CosmosDBShell.Tests/CommandTests/BulkCommandTests.cs +++ b/CosmosDBShell.Tests/CommandTests/BulkCommandTests.cs @@ -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); } diff --git a/CosmosDBShell.Tests/HelpCommandVerificationTests.cs b/CosmosDBShell.Tests/HelpCommandVerificationTests.cs index d1fd9aa6..262c495f 100644 --- a/CosmosDBShell.Tests/HelpCommandVerificationTests.cs +++ b/CosmosDBShell.Tests/HelpCommandVerificationTests.cs @@ -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(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(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)] diff --git a/CosmosDBShell.Tests/ToolOperationsTests.cs b/CosmosDBShell.Tests/ToolOperationsTests.cs index 50e8d765..0796b9b4 100644 --- a/CosmosDBShell.Tests/ToolOperationsTests.cs +++ b/CosmosDBShell.Tests/ToolOperationsTests.cs @@ -344,7 +344,10 @@ public void GetTool_LocalFilesystemCommands_AreRestricted(string commandName) 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()); + 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] @@ -367,7 +370,10 @@ public void GetTool_FileTransfers_RequireConfirmationWithoutDestructiveHints(str 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()); + 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] diff --git a/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/CommandFactory.cs b/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/CommandFactory.cs index e19cf538..38296628 100644 --- a/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/CommandFactory.cs +++ b/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/CommandFactory.cs @@ -44,6 +44,20 @@ public McpAnnotationAttribute? McpAnnotation /// 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, + }; + /// /// Gets a value indicating whether the command returns bounded, resumable pages over MCP. /// diff --git a/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/HelpCommand.cs b/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/HelpCommand.cs index 2469f4d5..5c7eafe8 100644 --- a/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/HelpCommand.cs +++ b/CosmosDBShell/Azure.Data.Cosmos.Shell.Commands/HelpCommand.cs @@ -98,6 +98,7 @@ public static CommandState PrintCommandHelp(string cmdStr, CommandRunner app, bo return new CommandState(); } + var mcpRestriction = cmd.McpRestrictionDescription; Action renderUser = () => { if (plain) @@ -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(); @@ -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) @@ -467,6 +471,7 @@ public override Task 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(); diff --git a/CosmosDBShell/Azure.Data.Cosmos.Shell.Mcp/ToolOperations.cs b/CosmosDBShell/Azure.Data.Cosmos.Shell.Mcp/ToolOperations.cs index 94fd96ec..4de52100 100644 --- a/CosmosDBShell/Azure.Data.Cosmos.Shell.Mcp/ToolOperations.cs +++ b/CosmosDBShell/Azure.Data.Cosmos.Shell.Mcp/ToolOperations.cs @@ -78,31 +78,10 @@ private ValueTask UnsubscribeFromResourcesAsync(RequestContext !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, @@ -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; @@ -571,7 +542,7 @@ private async ValueTask 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( @@ -768,7 +739,7 @@ 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 }) + if (command.McpConfirmable && cmd is not BulkCommand { DryRun: true, Save: null }) { var snapshot = await shell.RunSerializedAsync( () => diff --git a/CosmosDBShell/lang/en.ftl b/CosmosDBShell/lang/en.ftl index 4c7bbe73..14d87380 100644 --- a/CosmosDBShell/lang/en.ftl +++ b/CosmosDBShell/lang/en.ftl @@ -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 @@ -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. @@ -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 } @@ -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) @@ -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. @@ -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. diff --git a/docs/commands.md b/docs/commands.md index 7c10ac44..9790187c 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -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 @@ -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 diff --git a/docs/mcp.md b/docs/mcp.md index 5f8f523c..dac48aa4 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -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: diff --git a/l10n/CosmosDBShell.json b/l10n/CosmosDBShell.json index 2fa29dc8..c482cf51 100644 --- a/l10n/CosmosDBShell.json +++ b/l10n/CosmosDBShell.json @@ -163,7 +163,7 @@ "command-bulk-example-5": "Start a stateful bulk job with a default partition key", "command-bulk-example-6": "Queue an operation onto the active bulk job", "command-bulk-example-7": "Execute the queued operations", - "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-progress": "Bulk: {0} of {1} operations processed, {2} succeeded, {3} failed; elapsed {4} s, {5} operations/s (observed RU charge: {6})", "command-bulk-progress-compact": "Bulk: {0}/{1}, {2} failed, {3} s, {4}/s, {5} RU", "command-bulk-status-failed": "Failed", @@ -312,7 +312,7 @@ "command-delete-description-container": "The container for deleting items", "command-delete-description-database": "The database for the delete operation", "command-delete-description-dry-run": "Preview the deletion without applying it.", - "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-item": "The object to delete: item, container or database.", "command-delete-description-pattern": "The items/container/database to delete.", "command-delete-error-invalid_item_type": "You need to specify an item type: \u0027item\u0027, \u0027database\u0027 or \u0027container\u0027 as first parameter.", @@ -815,7 +815,7 @@ "command-rm-description-database": "The database containing the items to remove", "command-rm-description-dry-run": "Preview how many items would be deleted without deleting them.", "command-rm-description-etag": "Delete only if the item\u0027s current ETag matches. Requires an exact id with --key=id and --partition-key.", - "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-key": "The property name to match the pattern against (defaults to partition key)", "command-rm-description-partition-key": "Restrict removal to one complete logical partition key. Use {} for an undefined value or a JSON array for hierarchical partition keys.", "command-rm-description-pattern": "The pattern for the items to remove.", @@ -851,7 +851,7 @@ "command-rmcon-description": "Removes container", "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-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-name": "The database or container to remove.", "command-rmcon-dry-run-plan": "Dry run: Would delete container {0}. No changes were made.", "command-rmcon-error-container_not_found": "Container {0} not found.", @@ -863,7 +863,7 @@ "command-rmdb-deleted_db": "Deleted database {0}.", "command-rmdb-description": "Removes database", "command-rmdb-description-dry-run": "Preview the deletion without deleting the database.", - "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-name": "The database to remove.", "command-rmdb-dry-run-plan": "Dry run: Would delete database {0}. No changes were made.", "command-rmdb-error-database_not_found": "Database {0} not found.", @@ -1516,6 +1516,9 @@ "help-keyboard-shortcuts": "Keyboard Shortcuts", "help-keyboard-start-of-line": "Move cursor to start of line", "help-list-of-available-commands": "List of available commands", + "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-mcp-interactive-only": "This command is restricted to interactive use and cannot be invoked through MCP. Run it manually in the shell.", "help-optional": "(Optional)", "help-options": "Options:", "help-options-heading": "Options",