Skip to content
Merged
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
6 changes: 5 additions & 1 deletion .github/workflows/integration-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
10 changes: 10 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
132 changes: 132 additions & 0 deletions CosmosDBShell.Tests/McpConfirmationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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<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 = (request, _) =>
{
prompts.Add(request?.Message);
return ValueTask.FromResult(new ElicitResult { Action = action });
},
},
},
cancellationToken: timeout.Token);
var arguments = commandName == "import"
? new Dictionary<string, object?> { ["file"] = file, ["dry-run"] = true }
: new Dictionary<string, object?> { ["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<TextContentBlock>(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<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 = (_, _) =>
{
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<TextContentBlock>(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")]
Expand Down
Loading