-
Notifications
You must be signed in to change notification settings - Fork 7
Notify MCP clients about shell location changes #223
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Mike Krüger (mkrueger)
wants to merge
2
commits into
main
Choose a base branch
from
dev/mkrueger/mcp-location-notifications
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,77 @@ | ||
| // ------------------------------------------------------------ | ||
| // Copyright (c) Microsoft Corporation. All rights reserved. | ||
| // ------------------------------------------------------------ | ||
|
|
||
| namespace CosmosShell.Tests; | ||
|
|
||
| using System.Net; | ||
| using System.Net.Sockets; | ||
| using System.Text.Json; | ||
| using Azure.Data.Cosmos.Shell.Core; | ||
| using Azure.Data.Cosmos.Shell.Mcp; | ||
| using Azure.Data.Cosmos.Shell.States; | ||
| using ModelContextProtocol; | ||
| using ModelContextProtocol.Client; | ||
|
|
||
| [Collection(CosmosShell.Tests.Shell.ThemeStateTestCollection.Name)] | ||
| public class McpLocationSubscriptionTests | ||
| { | ||
| [Fact] | ||
| public async Task SubscribedClient_ReceivesInteractiveLocationChange() | ||
| { | ||
| using var timeout = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken); | ||
| timeout.CancelAfter(TimeSpan.FromSeconds(10)); | ||
| using var listener = new TcpListener(IPAddress.Loopback, 0); | ||
| listener.Start(); | ||
| var port = ((IPEndPoint)listener.LocalEndpoint).Port; | ||
| listener.Stop(); | ||
|
|
||
| using var host = McpServer.CreateHost(new Program.CosmosShellOptions { McpPort = port }); | ||
| await host.StartAsync(timeout.Token); | ||
| try | ||
| { | ||
| var transport = new HttpClientTransport(new HttpClientTransportOptions | ||
| { | ||
| Endpoint = new Uri($"http://127.0.0.1:{port}/"), | ||
| }); | ||
| await using var client = await McpClient.CreateAsync(transport, cancellationToken: timeout.Token); | ||
| var resources = await client.ListResourcesAsync(cancellationToken: timeout.Token); | ||
| Assert.Contains(resources, resource => resource.Uri == ResourceOperations.CurrentLocationUri); | ||
|
|
||
| var invalid = await Assert.ThrowsAsync<McpProtocolException>( | ||
| () => client.SubscribeToResourceAsync("cosmos://docs/scripting", cancellationToken: timeout.Token)); | ||
| Assert.Equal(McpErrorCode.InvalidParams, invalid.ErrorCode); | ||
| Assert.Contains(ResourceOperations.CurrentLocationUri, invalid.Message); | ||
|
|
||
| var updated = new TaskCompletionSource<string>(TaskCreationOptions.RunContinuationsAsynchronously); | ||
| await using var subscription = await client.SubscribeToResourceAsync( | ||
| ResourceOperations.CurrentLocationUri, | ||
| (notification, _) => | ||
| { | ||
| updated.TrySetResult(notification.Uri); | ||
| return ValueTask.CompletedTask; | ||
| }, | ||
| cancellationToken: timeout.Token); | ||
|
|
||
| var originalState = ShellInterpreter.Instance.State; | ||
| try | ||
| { | ||
| ShellInterpreter.Instance.State = new DatabaseState("McpNotificationTest", null!); | ||
| Assert.Equal(ResourceOperations.CurrentLocationUri, await updated.Task.WaitAsync(timeout.Token)); | ||
|
|
||
| var resource = await client.ReadResourceAsync(ResourceOperations.CurrentLocationUri, cancellationToken: timeout.Token); | ||
| var content = Assert.Single(resource.Contents); | ||
| using var json = JsonDocument.Parse(Assert.IsType<ModelContextProtocol.Protocol.TextResourceContents>(content).Text); | ||
| Assert.Equal("/McpNotificationTest", json.RootElement.GetProperty("currentLocation").GetString()); | ||
| } | ||
| finally | ||
| { | ||
| ShellInterpreter.Instance.State = originalState; | ||
| } | ||
| } | ||
| finally | ||
| { | ||
| await host.StopAsync(TestContext.Current.CancellationToken); | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,79 @@ | ||
| // ------------------------------------------------------------ | ||
| // Copyright (c) Microsoft Corporation. All rights reserved. | ||
| // ------------------------------------------------------------ | ||
|
|
||
| namespace CosmosShell.Tests; | ||
|
|
||
| using System.Runtime.CompilerServices; | ||
| using Azure.Data.Cosmos.Shell.Core; | ||
| using Azure.Data.Cosmos.Shell.States; | ||
| using Microsoft.Azure.Cosmos; | ||
|
|
||
| public class ShellLocationChangedTests | ||
| { | ||
| [Fact] | ||
| public void State_NotifiesOnlyWhenLocationChanges() | ||
| { | ||
| using var shell = new ShellInterpreter(); | ||
| var changes = 0; | ||
| shell.LocationChanged += () => changes++; | ||
|
|
||
| shell.State = new DisconnectedState(); | ||
| Assert.Equal(0, changes); | ||
|
|
||
| shell.State = new ConnectedState(null!); | ||
| Assert.Equal(1, changes); | ||
|
|
||
| shell.State = new DatabaseState("db", null!); | ||
| Assert.Equal(2, changes); | ||
|
|
||
| shell.State = new DatabaseState("db", null!); | ||
| Assert.Equal(2, changes); | ||
|
|
||
| shell.State = new ContainerState("container", "db", null!); | ||
| Assert.Equal(3, changes); | ||
|
|
||
| shell.State = new DisconnectedState(); | ||
| Assert.Equal(4, changes); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void State_NotifiesWhenClientChangesAtSameLocation() | ||
| { | ||
| using var shell = new ShellInterpreter(); | ||
| using var firstClient = CreateTestClient(); | ||
| using var secondClient = CreateTestClient(); | ||
| shell.State = new DatabaseState("db", firstClient); | ||
| var changes = 0; | ||
| shell.LocationChanged += () => changes++; | ||
|
|
||
| shell.State = new DatabaseState("db", secondClient); | ||
| Assert.Equal(1, changes); | ||
|
|
||
| shell.State = new DisconnectedState(); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void State_DoesNotNotifyWhenOnlyArmContextChanges() | ||
| { | ||
| using var shell = new ShellInterpreter(); | ||
| using var client = CreateTestClient(); | ||
| shell.State = new ConnectedState(client); | ||
| var changes = 0; | ||
| shell.LocationChanged += () => changes++; | ||
|
|
||
| var armContext = (ArmCosmosContext)RuntimeHelpers.GetUninitializedObject(typeof(ArmCosmosContext)); | ||
| shell.State = new ConnectedState(client, armContext); | ||
| Assert.Equal(0, changes); | ||
|
|
||
| shell.State = new DisconnectedState(); | ||
| } | ||
|
|
||
| private static CosmosClient CreateTestClient() | ||
| { | ||
| return new CosmosClient( | ||
| "https://localhost:8081", | ||
| Convert.ToBase64String(new byte[64]), | ||
| new CosmosClientOptions { ConnectionMode = ConnectionMode.Gateway }); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
119 changes: 119 additions & 0 deletions
119
CosmosDBShell/Azure.Data.Cosmos.Shell.Mcp/LocationResourceSubscriptions.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,119 @@ | ||
| // ------------------------------------------------------------ | ||
| // Copyright (c) Microsoft Corporation. All rights reserved. | ||
| // ------------------------------------------------------------ | ||
|
|
||
| namespace Azure.Data.Cosmos.Shell.Mcp; | ||
|
|
||
| using System.Threading.Channels; | ||
| using Azure.Data.Cosmos.Shell.Core; | ||
| using Microsoft.Extensions.Hosting; | ||
| using Microsoft.Extensions.Logging; | ||
| using ModelContextProtocol; | ||
| using ModelContextProtocol.Protocol; | ||
| using ModelContextProtocol.Server; | ||
|
|
||
| internal sealed class LocationResourceSubscriptions : BackgroundService | ||
| { | ||
| private readonly object sync = new(); | ||
|
|
||
| private readonly List<WeakReference<ModelContextProtocol.Server.McpServer>> subscribers = []; | ||
|
|
||
| // Notifications carry only the URI, so pending changes are coalesced into one. | ||
| private readonly Channel<bool> changes = Channel.CreateBounded<bool>( | ||
| new BoundedChannelOptions(1) { FullMode = BoundedChannelFullMode.DropWrite, SingleReader = true }); | ||
|
|
||
| private readonly ILogger<LocationResourceSubscriptions> logger; | ||
|
|
||
| public LocationResourceSubscriptions(ILogger<LocationResourceSubscriptions> logger) | ||
| { | ||
| this.logger = logger; | ||
| ShellInterpreter.Instance.LocationChanged += this.OnLocationChanged; | ||
| } | ||
|
|
||
| public void Subscribe(ModelContextProtocol.Server.McpServer server, string uri) | ||
| { | ||
| ValidateUri(uri); | ||
| lock (this.sync) | ||
| { | ||
| this.PruneSubscribers(); | ||
| if (!this.subscribers.Any(reference => reference.TryGetTarget(out var target) && ReferenceEquals(target, server))) | ||
| { | ||
| this.subscribers.Add(new WeakReference<ModelContextProtocol.Server.McpServer>(server)); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| public void Unsubscribe(ModelContextProtocol.Server.McpServer server, string uri) | ||
| { | ||
| ValidateUri(uri); | ||
| lock (this.sync) | ||
| { | ||
| this.subscribers.RemoveAll(reference => !reference.TryGetTarget(out var target) || ReferenceEquals(target, server)); | ||
| } | ||
| } | ||
|
|
||
| protected override async Task ExecuteAsync(CancellationToken stoppingToken) | ||
| { | ||
| await foreach (var change in this.changes.Reader.ReadAllAsync(stoppingToken)) | ||
| { | ||
| ModelContextProtocol.Server.McpServer[] servers; | ||
| lock (this.sync) | ||
| { | ||
| this.PruneSubscribers(); | ||
| servers = this.subscribers | ||
| .Select(reference => reference.TryGetTarget(out var server) ? server : null) | ||
| .OfType<ModelContextProtocol.Server.McpServer>() | ||
| .ToArray(); | ||
| } | ||
|
|
||
| foreach (var server in servers) | ||
| { | ||
| try | ||
| { | ||
| await server.SendNotificationAsync( | ||
| NotificationMethods.ResourceUpdatedNotification, | ||
| new ResourceUpdatedNotificationParams { Uri = ResourceOperations.CurrentLocationUri }, | ||
| cancellationToken: stoppingToken); | ||
| } | ||
| catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) | ||
| { | ||
| return; | ||
| } | ||
| catch (Exception ex) when (!stoppingToken.IsCancellationRequested) | ||
| { | ||
| this.logger.LogWarning(ex, "Could not notify an MCP client about the shell location change."); | ||
| lock (this.sync) | ||
| { | ||
| this.subscribers.RemoveAll(reference => !reference.TryGetTarget(out var target) || ReferenceEquals(target, server)); | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| public override void Dispose() | ||
| { | ||
| ShellInterpreter.Instance.LocationChanged -= this.OnLocationChanged; | ||
| base.Dispose(); | ||
| } | ||
|
|
||
| internal static void ValidateUri(string uri) | ||
| { | ||
| if (!string.Equals(uri, ResourceOperations.CurrentLocationUri, StringComparison.Ordinal)) | ||
| { | ||
| throw new McpProtocolException( | ||
| $"Resource '{uri}' does not support subscriptions. Only '{ResourceOperations.CurrentLocationUri}' can be subscribed to.", | ||
| McpErrorCode.InvalidParams); | ||
| } | ||
| } | ||
|
|
||
| private void OnLocationChanged() | ||
| { | ||
| this.changes.Writer.TryWrite(true); | ||
| } | ||
|
|
||
| private void PruneSubscribers() | ||
| { | ||
| this.subscribers.RemoveAll(reference => !reference.TryGetTarget(out _)); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.