diff --git a/README.md b/README.md index 1c7296d..78c7383 100644 --- a/README.md +++ b/README.md @@ -75,12 +75,14 @@ The one deliberate break from Clean Architecture is that the Presentation projec - MCP server using the [MCP C# SDK](https://github.com/modelcontextprotocol/csharp-sdk), stateless Streamable HTTP at `/mcp` - Six task-shaped tools (`movies_search`, `movies_get`, `authors_search`, `reviews_list`, `reviews_write`, `reviews_delete`) with titles, read-only, destructive and idempotent hints, and descriptions written for agents +- Resources for each movie, author and review (`movies://{movieId}`, `authors://{authorId}`, `reviews://{reviewId}`) and the server version (`server://version`) +- Prompts for common jobs (`summarise_movie_reception`, `compare_movies`, `review_movie`) that embed the movies they're about, with completions that suggest movie titles and author names as you type - Search with paging and small results by default: every list returns 10 items, a total count and a cursor, with names and average ratings next to ids - Logging using [Serilog](https://github.com/serilog/serilog), with [Seq](https://datalust.co/seq) when running in Docker - Mediator pattern using [Mediator](https://github.com/martinothamar/Mediator) - Validation using [FluentValidation](https://github.com/FluentValidation/FluentValidation) in an Application pipeline behaviour - Typed tool results published with an output schema and returned as structured content as well as JSON text -- Tool errors mapped from Application exceptions by a single call-tool filter, with messages that tell the agent how to recover +- Errors mapped from Application exceptions by request filters: tool errors tell the agent how to recover, and resources and prompts return MCP protocol errors such as resource not found - Object mapping using [Mapperly](https://mapperly.riok.app) - In-memory data using [Entity Framework Core](https://learn.microsoft.com/ef/core/providers/in-memory/) seeded with [Bogus](https://github.com/bchavez/Bogus) - Testing using [xUnit](https://xunit.net), [Shouldly](https://github.com/shouldly/shouldly) and [NSubstitute](https://github.com/nsubstitute/NSubstitute), with coverage from [Coverlet](https://github.com/coverlet-coverage/coverlet) diff --git a/src/Presentation/Completions/CompletionHandler.cs b/src/Presentation/Completions/CompletionHandler.cs new file mode 100644 index 0000000..7d690ec --- /dev/null +++ b/src/Presentation/Completions/CompletionHandler.cs @@ -0,0 +1,78 @@ +namespace CleanModelContextProtocol.Presentation.Completions; + +using Application.Common.Paging; +using Mediator; +using Microsoft.Extensions.DependencyInjection; +using ModelContextProtocol.Protocol; +using ModelContextProtocol.Server; +using AuthorQueries = Application.Authors.Queries; +using MovieQueries = Application.Movies.Queries; + +/// +/// Suggests movie titles and author names as the user types a prompt argument. +/// +public static class CompletionHandler +{ + private const int MaxQueryLength = 100; + + public static async ValueTask Handle(RequestContext context, CancellationToken cancellationToken) + { + return await Complete(context.Services.GetRequiredService(), context.Params, cancellationToken); + } + + public static async Task Complete(ISender sender, CompleteRequestParams request, CancellationToken cancellationToken) + { + var argument = request?.Argument; + + if (request?.Ref is not PromptReference || argument is null || argument.Value?.Length > MaxQueryLength) + { + return Empty(); + } + + switch (argument.Name) + { + case "movieTitle" or "firstMovieTitle" or "secondMovieTitle": + { + var page = await sender.Send(new MovieQueries.SearchMovies.SearchMoviesQuery + { + Query = argument.Value, + Limit = Paging.MaxLimit + }, cancellationToken); + + return Result([.. page.Items.Select(m => m.Title)], page.TotalCount); + } + + case "authorName": + { + var page = await sender.Send(new AuthorQueries.SearchAuthors.SearchAuthorsQuery + { + Query = argument.Value, + Limit = Paging.MaxLimit + }, cancellationToken); + + return Result([.. page.Items.Select(a => $"{a.FirstName} {a.LastName}".Trim())], page.TotalCount); + } + + default: + return Empty(); + } + } + + private static CompleteResult Result(List values, int total) + { + return new CompleteResult + { + Completion = new Completion + { + Values = values, + Total = total, + HasMore = total > values.Count + } + }; + } + + private static CompleteResult Empty() + { + return Result([], 0); + } +} diff --git a/src/Presentation/Errors/ProtocolErrorFilter.cs b/src/Presentation/Errors/ProtocolErrorFilter.cs new file mode 100644 index 0000000..98b6ebd --- /dev/null +++ b/src/Presentation/Errors/ProtocolErrorFilter.cs @@ -0,0 +1,45 @@ +namespace CleanModelContextProtocol.Presentation.Errors; + +using CleanModelContextProtocol.Application.Common.Exceptions; +using FluentValidation; +using ModelContextProtocol; +using ModelContextProtocol.Server; + +/// +/// Maps exceptions raised by the Application layer while reading a resource or getting a prompt to MCP protocol errors. +/// +public static class ProtocolErrorFilter +{ + public static McpRequestHandler Filter(McpRequestHandler next) + { + return async (request, cancellationToken) => + { + try + { + return await next(request, cancellationToken); + } + catch (Exception exception) when (ToProtocolException(exception) is { } protocolException) + { + throw protocolException; + } + }; + } + + public static McpProtocolException ToProtocolException(Exception exception) + { + return exception switch + { + NotFoundException => new McpProtocolException( + $"Not Found: {exception.Message} Check the id: movies_search, authors_search and reviews_list return valid ones.", + exception, + McpErrorCode.ResourceNotFound), + ValidationException validationException => new McpProtocolException( + "Validation Failed: " + string.Join(" ", validationException.Errors + .Select(e => $"{e.PropertyName}: {e.ErrorMessage}") + .Distinct()), + exception, + McpErrorCode.InvalidParams), + _ => null + }; + } +} diff --git a/src/Presentation/Extensions/WebApplicationBuilderExtensions.cs b/src/Presentation/Extensions/WebApplicationBuilderExtensions.cs index b9e208e..1028f15 100644 --- a/src/Presentation/Extensions/WebApplicationBuilderExtensions.cs +++ b/src/Presentation/Extensions/WebApplicationBuilderExtensions.cs @@ -2,15 +2,13 @@ namespace CleanModelContextProtocol.Presentation.Extensions; using System.Diagnostics.CodeAnalysis; using System.Reflection; -using System.Text.Json; -using System.Text.Json.Serialization; using Application; +using CleanModelContextProtocol.Presentation.Completions; using CleanModelContextProtocol.Presentation.Errors; using CleanModelContextProtocol.Presentation.Serialization; using Infrastructure; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; -using ModelContextProtocol; using Serilog; [ExcludeFromCodeCoverage] @@ -32,17 +30,6 @@ public static WebApplicationBuilder ConfigureApplicationBuilder(this WebApplicat #endregion Logging - #region Serialisation - - var serializerOptions = new JsonSerializerOptions(McpJsonUtilities.DefaultOptions) - { - PropertyNamingPolicy = JsonNamingPolicy.CamelCase, - DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull - }; - serializerOptions.TypeInfoResolverChain.Insert(0, AppJsonSerializerContext.Default); - - #endregion Serialisation - #region Project Dependencies _ = builder.Services.AddMediator(options => options.ServiceLifetime = ServiceLifetime.Scoped); @@ -80,11 +67,21 @@ A review links one author to one movie with a star rating from 1 (worst) to 5 (b so pass nextCursor back to continue rather than raising the limit. reviews_write creates a review, or replaces one when you pass its reviewId. reviews_delete can't be undone, so confirm with the user before calling it. + Each movie, author and review can also be read as a resource at movies://{id}, authors://{id} or + reviews://{id}, and server://version gives this server's version. """; }) .WithHttpTransport(options => options.Stateless = true) - .WithToolsFromAssembly(serializerOptions: serializerOptions) - .WithRequestFilters(filters => filters.AddCallToolFilter(ToolErrorFilter.Filter)); + .WithToolsFromAssembly(serializerOptions: McpSerializer.Options) + .WithResourcesFromAssembly() + .WithPromptsFromAssembly(serializerOptions: McpSerializer.Options) + .WithCompleteHandler(CompletionHandler.Handle) + .WithRequestFilters(filters => + { + filters.AddCallToolFilter(ToolErrorFilter.Filter); + filters.AddReadResourceFilter(ProtocolErrorFilter.Filter); + filters.AddGetPromptFilter(ProtocolErrorFilter.Filter); + }); #endregion Model Context Protocol diff --git a/src/Presentation/Prompts/MoviePrompts.cs b/src/Presentation/Prompts/MoviePrompts.cs new file mode 100644 index 0000000..9a3864f --- /dev/null +++ b/src/Presentation/Prompts/MoviePrompts.cs @@ -0,0 +1,130 @@ +namespace CleanModelContextProtocol.Presentation.Prompts; + +using System.ComponentModel; +using CleanModelContextProtocol.Presentation.Models; +using CleanModelContextProtocol.Presentation.Serialization; +using Mediator; +using ModelContextProtocol.Protocol; +using ModelContextProtocol.Server; +using Queries = Application.Movies.Queries; + +[McpServerPromptType] +public static class MoviePrompts +{ + [McpServerPrompt(Name = "summarise_movie_reception", Title = "Summarise a movie's reception")] + [Description("Summarise how reviewers have received a movie: its average stars, how the ratings spread, and who liked it most and least.")] + public static async Task SummariseMovieReception( + ISender sender, + [Description("The movie's title, or part of it.")] string movieTitle) + { + var movie = await FindMovie(sender, movieTitle); + + var messages = new List + { + Text(movie is null + ? $"Summarise how reviewers have received the movie \"{movieTitle}\". Find it with movies_search, get its reviews " + + "with movies_get, then give its average stars, how the ratings spread from 1 to 5, and which authors rated it highest and lowest." + : $"Summarise how reviewers have received \"{movie.Title}\", using the movie below. Give its average stars, " + + "how the ratings spread from 1 to 5, and which authors rated it highest and lowest.") + }; + + if (movie is not null) + { + messages.Add(Embed(movie)); + } + + return new GetPromptResult + { + Description = $"Summarise the reception of {movie?.Title ?? movieTitle}", + Messages = messages + }; + } + + [McpServerPrompt(Name = "compare_movies", Title = "Compare two movies")] + [Description("Compare how reviewers rated two movies, and say which one they preferred and by how much.")] + public static async Task CompareMovies( + ISender sender, + [Description("The first movie's title, or part of it.")] string firstMovieTitle, + [Description("The second movie's title, or part of it.")] string secondMovieTitle) + { + var first = await FindMovie(sender, firstMovieTitle); + var second = await FindMovie(sender, secondMovieTitle); + + var messages = new List + { + Text($"Compare how reviewers rated \"{first?.Title ?? firstMovieTitle}\" and \"{second?.Title ?? secondMovieTitle}\". " + + "Give each movie's average stars and number of reviews, note any authors who reviewed both, and say which movie " + + "reviewers preferred. Find any movie that isn't attached below with movies_search, then get it with movies_get.") + }; + + foreach (var movie in new[] { first, second }.OfType()) + { + messages.Add(Embed(movie)); + } + + return new GetPromptResult + { + Description = $"Compare {first?.Title ?? firstMovieTitle} with {second?.Title ?? secondMovieTitle}", + Messages = messages + }; + } + + [McpServerPrompt(Name = "review_movie", Title = "Review a movie")] + [Description("Write a review of a movie as one of the authors, checking the movie and author before saving it.")] + public static GetPromptResult ReviewMovie( + [Description("The movie's title, or part of it.")] string movieTitle, + [Description("The name of the author writing the review.")] string authorName) + { + return new GetPromptResult + { + Description = $"Review {movieTitle} as {authorName}", + Messages = + [ + Text($"I want to review the movie \"{movieTitle}\" as the author \"{authorName}\". Find the movie with movies_search " + + "and the author with authors_search. If either search doesn't return exactly one clear match, show me the closest " + + "results and ask which one I meant. Ask me for a star rating from 1 to 5, then save the review with reviews_write " + + "and show me the saved review.") + ] + }; + } + + private static async Task FindMovie(ISender sender, string title) + { + var page = await sender.Send(new Queries.SearchMovies.SearchMoviesQuery + { + Query = title, + Limit = 5 + }); + + var movie = page.Items.FirstOrDefault(m => string.Equals(m.Title, title?.Trim(), StringComparison.OrdinalIgnoreCase)) + ?? (page.TotalCount == 1 ? page.Items[0] : null); + + return movie?.ToResult(includeReviews: true); + } + + private static PromptMessage Text(string text) + { + return new PromptMessage + { + Role = Role.User, + Content = new TextContentBlock { Text = text } + }; + } + + private static PromptMessage Embed(MovieResult movie) + { + return new PromptMessage + { + Role = Role.User, + Content = new EmbeddedResourceBlock + { + Resource = new TextResourceContents + { + Uri = $"movies://{movie.Id}", + MimeType = "application/json", + Text = McpSerializer.Serialize(movie) + } + } + }; + } +} diff --git a/src/Presentation/Resources/AuthorResources.cs b/src/Presentation/Resources/AuthorResources.cs new file mode 100644 index 0000000..6cca893 --- /dev/null +++ b/src/Presentation/Resources/AuthorResources.cs @@ -0,0 +1,26 @@ +namespace CleanModelContextProtocol.Presentation.Resources; + +using System.ComponentModel; +using CleanModelContextProtocol.Presentation.Models; +using CleanModelContextProtocol.Presentation.Serialization; +using Mediator; +using ModelContextProtocol.Server; +using Queries = Application.Authors.Queries; + +[McpServerResourceType] +public static class AuthorResources +{ + [McpServerResource(UriTemplate = "authors://{authorId}", Name = "author", Title = "Author", MimeType = "application/json")] + [Description("An author with their review count, average stars and every review they have written, including each movie's title.")] + public static async Task GetAuthor( + ISender sender, + [Description("The author's id (a GUID).")] Guid authorId) + { + var author = await sender.Send(new Queries.GetAuthorById.GetAuthorByIdQuery + { + Id = authorId + }); + + return McpSerializer.Serialize(author.ToResult(includeReviews: true)); + } +} diff --git a/src/Presentation/Resources/MovieResources.cs b/src/Presentation/Resources/MovieResources.cs new file mode 100644 index 0000000..d4887cf --- /dev/null +++ b/src/Presentation/Resources/MovieResources.cs @@ -0,0 +1,26 @@ +namespace CleanModelContextProtocol.Presentation.Resources; + +using System.ComponentModel; +using CleanModelContextProtocol.Presentation.Models; +using CleanModelContextProtocol.Presentation.Serialization; +using Mediator; +using ModelContextProtocol.Server; +using Queries = Application.Movies.Queries; + +[McpServerResourceType] +public static class MovieResources +{ + [McpServerResource(UriTemplate = "movies://{movieId}", Name = "movie", Title = "Movie", MimeType = "application/json")] + [Description("A movie with its review count, average stars and every review, including each author's name.")] + public static async Task GetMovie( + ISender sender, + [Description("The movie's id (a GUID).")] Guid movieId) + { + var movie = await sender.Send(new Queries.GetMovieById.GetMovieByIdQuery + { + Id = movieId + }); + + return McpSerializer.Serialize(movie.ToResult(includeReviews: true)); + } +} diff --git a/src/Presentation/Resources/ReviewResources.cs b/src/Presentation/Resources/ReviewResources.cs new file mode 100644 index 0000000..aa14e9c --- /dev/null +++ b/src/Presentation/Resources/ReviewResources.cs @@ -0,0 +1,26 @@ +namespace CleanModelContextProtocol.Presentation.Resources; + +using System.ComponentModel; +using CleanModelContextProtocol.Presentation.Models; +using CleanModelContextProtocol.Presentation.Serialization; +using Mediator; +using ModelContextProtocol.Server; +using Queries = Application.Reviews.Queries; + +[McpServerResourceType] +public static class ReviewResources +{ + [McpServerResource(UriTemplate = "reviews://{reviewId}", Name = "review", Title = "Review", MimeType = "application/json")] + [Description("A review with its star rating, the movie's title and the author's name.")] + public static async Task GetReview( + ISender sender, + [Description("The review's id (a GUID).")] Guid reviewId) + { + var review = await sender.Send(new Queries.GetReviewById.GetReviewByIdQuery + { + Id = reviewId + }); + + return McpSerializer.Serialize(review.ToResult()); + } +} diff --git a/src/Presentation/Resources/VersionResources.cs b/src/Presentation/Resources/VersionResources.cs new file mode 100644 index 0000000..37fb428 --- /dev/null +++ b/src/Presentation/Resources/VersionResources.cs @@ -0,0 +1,18 @@ +namespace CleanModelContextProtocol.Presentation.Resources; + +using System.ComponentModel; +using CleanModelContextProtocol.Presentation.Serialization; +using Mediator; +using ModelContextProtocol.Server; +using Queries = Application.Versions.Queries; + +[McpServerResourceType] +public static class VersionResources +{ + [McpServerResource(UriTemplate = "server://version", Name = "server_version", Title = "Server version", MimeType = "application/json")] + [Description("The version of this server: the file version and the informational version, which includes the commit it was built from.")] + public static async Task GetVersion(ISender sender) + { + return McpSerializer.Serialize(await sender.Send(new Queries.GetVersion.GetVersionQuery())); + } +} diff --git a/src/Presentation/Serialization/McpSerializer.cs b/src/Presentation/Serialization/McpSerializer.cs new file mode 100644 index 0000000..0d9c713 --- /dev/null +++ b/src/Presentation/Serialization/McpSerializer.cs @@ -0,0 +1,31 @@ +namespace CleanModelContextProtocol.Presentation.Serialization; + +using System.Text.Json; +using System.Text.Json.Serialization; +using ModelContextProtocol; + +/// +/// The JSON settings shared by tool results, resources and prompts. +/// +public static class McpSerializer +{ + public static JsonSerializerOptions Options { get; } = CreateOptions(); + + public static string Serialize(T value) + { + return JsonSerializer.Serialize(value, Options); + } + + private static JsonSerializerOptions CreateOptions() + { + var options = new JsonSerializerOptions(McpJsonUtilities.DefaultOptions) + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull + }; + options.TypeInfoResolverChain.Insert(0, AppJsonSerializerContext.Default); + options.MakeReadOnly(); + + return options; + } +} diff --git a/src/Presentation/Tools/VersionTools.cs b/src/Presentation/Tools/VersionTools.cs deleted file mode 100644 index 2020752..0000000 --- a/src/Presentation/Tools/VersionTools.cs +++ /dev/null @@ -1,18 +0,0 @@ -namespace CleanModelContextProtocol.Presentation.Tools; - -using System.ComponentModel; -using Mediator; -using ModelContextProtocol.Server; -using Entities = Application.Versions.Entities; -using Queries = Application.Versions.Queries; - -[McpServerToolType] -public static class VersionTools -{ - [McpServerTool(Name = "server_get_version", Title = "Get server version", ReadOnly = true, Idempotent = true, OpenWorld = false, UseStructuredContent = true)] - [Description("Get the version of this server: the file version and the informational version, which includes the commit it was built from.")] - public static async Task GetVersion(ISender sender) - { - return await sender.Send(new Queries.GetVersion.GetVersionQuery()); - } -} diff --git a/tests/Presentation.Tests.Integration/Completions/CompletionTests.cs b/tests/Presentation.Tests.Integration/Completions/CompletionTests.cs new file mode 100644 index 0000000..abcba10 --- /dev/null +++ b/tests/Presentation.Tests.Integration/Completions/CompletionTests.cs @@ -0,0 +1,74 @@ +namespace CleanModelContextProtocol.Presentation.Tests.Integration.Completions; + +using CleanModelContextProtocol.Presentation.Models; +using ModelContextProtocol.Protocol; +using Shouldly; +using Xunit; + +public class CompletionTests : BaseToolTests +{ + [Fact] + public async Task CompleteMovieTitle_ShouldReturn_MatchingTitles() + { + // Arrange + var movie = (await this.CallAsync>("movies_search")).Items[0]; + var partial = movie.Title[..Math.Min(3, movie.Title.Length)]; + + // Act + var result = await this.Client.CompleteAsync(new PromptReference { Name = "summarise_movie_reception" }, "movieTitle", partial); + + // Assert + result.Completion.Values.ShouldContain(movie.Title); + result.Completion.Values.ShouldAllBe(v => v.Contains(partial, StringComparison.OrdinalIgnoreCase)); + result.Completion.Total.ShouldBe(result.Completion.Values.Count); + result.Completion.HasMore.ShouldBe(false); + } + + [Fact] + public async Task CompleteMovieTitle_WithEmptyValue_ShouldReturn_FirstPage() + { + // Act + var result = await this.Client.CompleteAsync(new PromptReference { Name = "compare_movies" }, "secondMovieTitle", string.Empty); + + // Assert + result.Completion.Values.Count.ShouldBe(50); + result.Completion.Total.ShouldBe(50); + result.Completion.HasMore.ShouldBe(false); + } + + [Fact] + public async Task CompleteAuthorName_ShouldReturn_MatchingNames() + { + // Arrange + var author = (await this.CallAsync>("authors_search")).Items[0]; + + // Act + var result = await this.Client.CompleteAsync(new PromptReference { Name = "review_movie" }, "authorName", author.Name); + + // Assert + result.Completion.Values.ShouldContain(author.Name); + } + + [Theory] + [InlineData("review_movie", "unknown", "a")] + [InlineData("review_movie", "authorName", "this value is far too long to be a search term because it runs past the one hundred character limit set by the search")] + public async Task Complete_WithUnsupportedArgument_ShouldReturn_Nothing(string prompt, string argument, string value) + { + // Act + var result = await this.Client.CompleteAsync(new PromptReference { Name = prompt }, argument, value); + + // Assert + result.Completion.Values.ShouldBeEmpty(); + result.Completion.HasMore.ShouldBe(false); + } + + [Fact] + public async Task Complete_ResourceTemplate_ShouldReturn_Nothing() + { + // Act + var result = await this.Client.CompleteAsync(new ResourceTemplateReference { Uri = "movies://{movieId}" }, "movieId", "a"); + + // Assert + result.Completion.Values.ShouldBeEmpty(); + } +} diff --git a/tests/Presentation.Tests.Integration/Prompts/PromptTests.cs b/tests/Presentation.Tests.Integration/Prompts/PromptTests.cs new file mode 100644 index 0000000..2de0db4 --- /dev/null +++ b/tests/Presentation.Tests.Integration/Prompts/PromptTests.cs @@ -0,0 +1,123 @@ +namespace CleanModelContextProtocol.Presentation.Tests.Integration.Prompts; + +using CleanModelContextProtocol.Presentation.Models; +using Extensions; +using ModelContextProtocol; +using ModelContextProtocol.Protocol; +using Shouldly; +using Xunit; + +public class PromptTests : BaseToolTests +{ + [Fact] + public async Task ListPrompts_ShouldReturn_EveryPrompt() + { + // Act + var prompts = await this.Client.ListPromptsAsync(); + + // Assert + prompts.Select(p => p.Name).ShouldBe(["summarise_movie_reception", "compare_movies", "review_movie"], ignoreOrder: true); + + foreach (var prompt in prompts) + { + prompt.Title.ShouldNotBeNullOrWhiteSpace(); + prompt.Description.ShouldNotBeNullOrWhiteSpace(); + prompt.ProtocolPrompt.Arguments.ShouldNotBeEmpty(); + prompt.ProtocolPrompt.Arguments.ShouldAllBe(a => a.Required == true && !string.IsNullOrWhiteSpace(a.Description)); + } + } + + [Fact] + public async Task SummariseMovieReception_ShouldEmbed_Movie() + { + // Arrange + var movie = await this.FirstMovieAsync(); + + // Act + var result = await this.Client.GetPromptAsync("summarise_movie_reception", + new Dictionary { ["movieTitle"] = movie.Title.ToUpperInvariant() }); + + // Assert + result.Messages.Count.ShouldBe(2); + result.Messages.ShouldAllBe(m => m.Role == Role.User); + result.Messages[0].Content.ShouldBeOfType().Text.ShouldContain(movie.Title); + ShouldEmbed(result.Messages[1], movie); + } + + [Fact] + public async Task SummariseMovieReception_WithUnknownTitle_ShouldAsk_ToSearch() + { + // Act + var result = await this.Client.GetPromptAsync("summarise_movie_reception", + new Dictionary { ["movieTitle"] = "No Such Movie" }); + + // Assert + var message = result.Messages.ShouldHaveSingleItem(); + message.Content.ShouldBeOfType().Text.ShouldContain("Find it with movies_search"); + } + + [Fact] + public async Task SummariseMovieReception_WithLongTitle_ShouldThrow_InvalidParams() + { + // Act + var exception = await Should.ThrowAsync(() => this.Client.GetPromptAsync("summarise_movie_reception", + new Dictionary { ["movieTitle"] = new string('a', 101) }).AsTask()); + + // Assert + exception.ErrorCode.ShouldBe(McpErrorCode.InvalidParams); + } + + [Fact] + public async Task CompareMovies_ShouldEmbed_BothMovies() + { + // Arrange + var movies = (await this.CallAsync>("movies_search", + new Dictionary { ["limit"] = 2 })).Items; + + // Act + var result = await this.Client.GetPromptAsync("compare_movies", new Dictionary + { + ["firstMovieTitle"] = movies[0].Title, + ["secondMovieTitle"] = movies[1].Title + }); + + // Assert + result.Messages.Count.ShouldBe(3); + ShouldEmbed(result.Messages[1], movies[0]); + ShouldEmbed(result.Messages[2], movies[1]); + } + + [Fact] + public async Task ReviewMovie_ShouldReturn_Instructions() + { + // Act + var result = await this.Client.GetPromptAsync("review_movie", new Dictionary + { + ["movieTitle"] = "Some Movie", + ["authorName"] = "Some Author" + }); + + // Assert + var text = result.Messages.ShouldHaveSingleItem().Content.ShouldBeOfType().Text; + text.ShouldContain("\"Some Movie\""); + text.ShouldContain("\"Some Author\""); + text.ShouldContain("reviews_write"); + } + + private async Task FirstMovieAsync() + { + return (await this.CallAsync>("movies_search", new Dictionary { ["limit"] = 50 })) + .Items.First(m => m.ReviewCount > 0); + } + + private static void ShouldEmbed(PromptMessage message, MovieResult movie) + { + var resource = message.Content.ShouldBeOfType().Resource.ShouldBeOfType(); + resource.Uri.ShouldBe($"movies://{movie.Id}"); + resource.MimeType.ShouldBe("application/json"); + + var embedded = resource.Text.Deserialize(); + embedded.Id.ShouldBe(movie.Id); + embedded.Reviews.Count.ShouldBe(movie.ReviewCount); + } +} diff --git a/tests/Presentation.Tests.Integration/Resources/ResourceTests.cs b/tests/Presentation.Tests.Integration/Resources/ResourceTests.cs new file mode 100644 index 0000000..ceb1a5d --- /dev/null +++ b/tests/Presentation.Tests.Integration/Resources/ResourceTests.cs @@ -0,0 +1,123 @@ +namespace CleanModelContextProtocol.Presentation.Tests.Integration.Resources; + +using CleanModelContextProtocol.Presentation.Models; +using Extensions; +using ModelContextProtocol; +using ModelContextProtocol.Protocol; +using Shouldly; +using Xunit; +using Entities = Application.Versions.Entities; + +public class ResourceTests : BaseToolTests +{ + [Fact] + public async Task ListResourceTemplates_ShouldReturn_EveryTemplate() + { + // Act + var templates = await this.Client.ListResourceTemplatesAsync(); + + // Assert + templates.Select(t => t.UriTemplate).ShouldBe(["movies://{movieId}", "authors://{authorId}", "reviews://{reviewId}"], ignoreOrder: true); + templates.ShouldAllBe(t => t.MimeType == "application/json" && !string.IsNullOrWhiteSpace(t.Title) && !string.IsNullOrWhiteSpace(t.Description)); + } + + [Fact] + public async Task ListResources_ShouldReturn_ServerVersion() + { + // Act + var resources = await this.Client.ListResourcesAsync(); + + // Assert + var resource = resources.ShouldHaveSingleItem(); + resource.Uri.ShouldBe("server://version"); + resource.MimeType.ShouldBe("application/json"); + } + + [Fact] + public async Task ReadVersion_ShouldReturn_Version() + { + // Act + var version = await this.ReadAsync("server://version"); + + // Assert + version.FileVersion.ShouldNotBeNullOrWhiteSpace(); + version.InformationalVersion.ShouldNotBeNullOrWhiteSpace(); + } + + [Fact] + public async Task ReadMovie_ShouldReturn_MovieWithReviews() + { + // Arrange + var first = (await this.CallAsync>("movies_search", + new Dictionary { ["limit"] = 50 })).Items.First(m => m.ReviewCount > 0); + + // Act + var movie = await this.ReadAsync($"movies://{first.Id}"); + + // Assert + movie.Id.ShouldBe(first.Id); + movie.Title.ShouldBe(first.Title); + movie.Reviews.Count.ShouldBe(first.ReviewCount); + } + + [Fact] + public async Task ReadAuthor_ShouldReturn_AuthorWithReviews() + { + // Arrange + var first = (await this.CallAsync>("authors_search")).Items[0]; + + // Act + var author = await this.ReadAsync($"authors://{first.Id}"); + + // Assert + author.Id.ShouldBe(first.Id); + author.Name.ShouldBe(first.Name); + author.Reviews.Count.ShouldBe(first.ReviewCount); + } + + [Fact] + public async Task ReadReview_ShouldReturn_Review() + { + // Arrange + var first = (await this.CallAsync>("reviews_list")).Items[0]; + + // Act + var review = await this.ReadAsync($"reviews://{first.Id}"); + + // Assert + review.ShouldBe(first); + } + + [Fact] + public async Task ReadMovie_WithUnknownId_ShouldThrow_ResourceNotFound() + { + // Act + var exception = await Should.ThrowAsync(() => this.Client.ReadResourceAsync($"movies://{Guid.NewGuid()}").AsTask()); + + // Assert + exception.ErrorCode.ShouldBe(McpErrorCode.ResourceNotFound); + exception.Message.ShouldContain("The Movie with the supplied id was not found."); + } + + [Fact] + public async Task ReadAuthor_WithEmptyId_ShouldThrow_InvalidParams() + { + // Act + var exception = await Should.ThrowAsync(() => this.Client.ReadResourceAsync($"authors://{Guid.Empty}").AsTask()); + + // Assert + exception.ErrorCode.ShouldBe(McpErrorCode.InvalidParams); + exception.Message.ShouldContain("An Author Id was not supplied."); + } + + private async Task ReadAsync(string uri) + { + var result = await this.Client.ReadResourceAsync(uri); + + var contents = result.Contents.ShouldHaveSingleItem().ShouldBeOfType(); + contents.Uri.ShouldBe(uri); + contents.MimeType.ShouldBe("application/json"); + + return contents.Text.Deserialize(); + } +} diff --git a/tests/Presentation.Tests.Integration/Tools/ToolListTests.cs b/tests/Presentation.Tests.Integration/Tools/ToolListTests.cs index 57bf66e..8db359b 100644 --- a/tests/Presentation.Tests.Integration/Tools/ToolListTests.cs +++ b/tests/Presentation.Tests.Integration/Tools/ToolListTests.cs @@ -13,7 +13,6 @@ public class ToolListTests : BaseToolTests { "reviews_list", "List reviews", true, false, true }, { "reviews_write", "Write review", false, true, false }, { "reviews_delete", "Delete review", false, true, true }, - { "server_get_version", "Get server version", true, false, true } }; [Fact] diff --git a/tests/Presentation.Tests.Integration/Tools/VersionToolTests.cs b/tests/Presentation.Tests.Integration/Tools/VersionToolTests.cs deleted file mode 100644 index db4e21a..0000000 --- a/tests/Presentation.Tests.Integration/Tools/VersionToolTests.cs +++ /dev/null @@ -1,28 +0,0 @@ -namespace CleanModelContextProtocol.Presentation.Tests.Integration.Tools; - -using Extensions; -using ModelContextProtocol.Protocol; -using Shouldly; -using Xunit; - -public class VersionToolTests : BaseToolTests -{ - [Fact] - public async Task GetVersion_ShouldReturn_Version() - { - // Act - var result = await this.Client.CallToolAsync("server_get_version"); - var text = result.Content.OfType().First().Text; - - var version = text.Deserialize(); - - // Assert - _ = version.ShouldNotBeNull(); - - version.FileVersion.ShouldNotBeNullOrWhiteSpace(); - version.InformationalVersion.ShouldNotBeNullOrWhiteSpace(); - - _ = result.StructuredContent.ShouldNotBeNull(); - result.StructuredContent.Value.GetProperty("fileVersion").GetString().ShouldBe(version.FileVersion); - } -} diff --git a/tests/Presentation.Tests.Unit/Errors/ProtocolErrorFilterTests.cs b/tests/Presentation.Tests.Unit/Errors/ProtocolErrorFilterTests.cs new file mode 100644 index 0000000..08837c4 --- /dev/null +++ b/tests/Presentation.Tests.Unit/Errors/ProtocolErrorFilterTests.cs @@ -0,0 +1,66 @@ +namespace CleanModelContextProtocol.Presentation.Tests.Unit.Errors; + +using CleanModelContextProtocol.Application.Common.Exceptions; +using CleanModelContextProtocol.Presentation.Errors; +using FluentValidation; +using FluentValidation.Results; +using ModelContextProtocol; +using ModelContextProtocol.Protocol; +using Shouldly; +using Xunit; + +public class ProtocolErrorFilterTests +{ + [Fact] + public async Task Filter_ShouldReturn_Result() + { + // Arrange + var expected = new ReadResourceResult(); + var handler = ProtocolErrorFilter.Filter((request, cancellationToken) => ValueTask.FromResult(expected)); + + // Act + var result = await handler(null!, CancellationToken.None); + + // Assert + result.ShouldBe(expected); + } + + [Fact] + public async Task Filter_ShouldThrow_ResourceNotFound() + { + // Arrange + var handler = ProtocolErrorFilter.Filter((request, cancellationToken) => throw new NotFoundException("Expected Exception")); + + // Act + var exception = await Should.ThrowAsync(() => handler(null!, CancellationToken.None).AsTask()); + + // Assert + exception.ErrorCode.ShouldBe(McpErrorCode.ResourceNotFound); + exception.Message.ShouldBe("Not Found: Expected Exception Check the id: movies_search, authors_search and reviews_list return valid ones."); + } + + [Fact] + public async Task Filter_ShouldThrow_InvalidParams() + { + // Arrange + var handler = ProtocolErrorFilter.Filter((request, cancellationToken) => + throw new ValidationException([new ValidationFailure("Query", "Too long."), new ValidationFailure("Query", "Too long.")])); + + // Act + var exception = await Should.ThrowAsync(() => handler(null!, CancellationToken.None).AsTask()); + + // Assert + exception.ErrorCode.ShouldBe(McpErrorCode.InvalidParams); + exception.Message.ShouldBe("Validation Failed: Query: Too long."); + } + + [Fact] + public async Task Filter_ShouldRethrow_OtherExceptions() + { + // Arrange + var handler = ProtocolErrorFilter.Filter((request, cancellationToken) => throw new InvalidOperationException("Expected Exception")); + + // Act & Assert + _ = await Should.ThrowAsync(() => handler(null!, CancellationToken.None).AsTask()); + } +} diff --git a/tests/Presentation.Tests.Unit/Tools/VersionToolTests.cs b/tests/Presentation.Tests.Unit/Tools/VersionToolTests.cs deleted file mode 100644 index 8c759cc..0000000 --- a/tests/Presentation.Tests.Unit/Tools/VersionToolTests.cs +++ /dev/null @@ -1,34 +0,0 @@ -namespace CleanModelContextProtocol.Presentation.Tests.Unit.Tools; - -using CleanModelContextProtocol.Presentation.Tools; -using Mediator; -using NSubstitute; -using Shouldly; -using Xunit; -using Entities = Application.Versions.Entities; -using Queries = Application.Versions.Queries; - -public class VersionToolTests -{ - [Fact] - public async Task GetVersion_ShouldReturn_Version() - { - // Arrange - var sender = Substitute.For(); - - _ = sender - .Send(Arg.Any()) - .ReturnsForAnyArgs(new Entities.Version - { - FileVersion = "1.2.3.4", - InformationalVersion = "5.6.7.8" - }); - - // Act - var response = await VersionTools.GetVersion(sender); - - // Assert - response.FileVersion.ShouldBe("1.2.3.4"); - response.InformationalVersion.ShouldBe("5.6.7.8"); - } -}