diff --git a/README.md b/README.md index 342b8c4..1c7296d 100644 --- a/README.md +++ b/README.md @@ -74,7 +74,8 @@ The one deliberate break from Clean Architecture is that the Presentation projec ## Features - MCP server using the [MCP C# SDK](https://github.com/modelcontextprotocol/csharp-sdk), stateless Streamable HTTP at `/mcp` -- Tools named by resource (`movies_list`, `reviews_create`) with titles, read-only, destructive and idempotent hints, and descriptions written for agents +- 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 +- 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 diff --git a/src/Presentation/Errors/ToolErrorFilter.cs b/src/Presentation/Errors/ToolErrorFilter.cs index de302f8..9933fc9 100644 --- a/src/Presentation/Errors/ToolErrorFilter.cs +++ b/src/Presentation/Errors/ToolErrorFilter.cs @@ -20,19 +20,19 @@ public static McpRequestHandler Filter(Mc } catch (Exception exception) when (exception is not OperationCanceledException) { - return ToResult(exception, request?.Params?.Name); + return ToResult(exception); } }; } - public static CallToolResult ToResult(Exception exception, string toolName = null) + public static CallToolResult ToResult(Exception exception) { var message = exception switch { ValidationException validationException => "Validation Failed: " + string.Join(" ", validationException.Errors .Select(e => $"{e.PropertyName}: {e.ErrorMessage}") .Distinct()) + " Correct the arguments and call the tool again.", - NotFoundException => $"Not Found: {exception.Message}{ListToolHint(toolName)}", + NotFoundException => $"Not Found: {exception.Message} Check the ids: movies_search, authors_search and reviews_list return valid ones.", _ => "Error: An error occurred while processing your request." }; @@ -42,18 +42,4 @@ public static CallToolResult ToResult(Exception exception, string toolName = nul Content = [new TextContentBlock { Text = message }] }; } - - private static string ListToolHint(string toolName) - { - if (toolName is null) - { - return string.Empty; - } - - var separator = toolName.IndexOf('_'); - - return separator > 0 - ? $" Check the ids, using {toolName[..separator]}_list or the other list tools to find valid ones." - : string.Empty; - } } diff --git a/src/Presentation/Extensions/WebApplicationBuilderExtensions.cs b/src/Presentation/Extensions/WebApplicationBuilderExtensions.cs index 5e3a61b..b9e208e 100644 --- a/src/Presentation/Extensions/WebApplicationBuilderExtensions.cs +++ b/src/Presentation/Extensions/WebApplicationBuilderExtensions.cs @@ -75,9 +75,10 @@ public static WebApplicationBuilder ConfigureApplicationBuilder(this WebApplicat options.ServerInstructions = """ This server holds a catalogue of movies, the authors who review them, and their reviews. A review links one author to one movie with a star rating from 1 (worst) to 5 (best). - Every movie, author and review is identified by a GUID id. Ids are never guessable, so look them up - with movies_list, authors_list or reviews_list before calling a tool that needs one. - To change a review use reviews_update, which overwrites the author, movie and stars together. + Find things by name first: movies_search and authors_search return ids, review counts and average + stars, and reviews_list filters reviews by movie or author. Every search returns one page at a time, + 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. """; }) diff --git a/src/Presentation/Models/AuthorResult.cs b/src/Presentation/Models/AuthorResult.cs new file mode 100644 index 0000000..b675d1c --- /dev/null +++ b/src/Presentation/Models/AuthorResult.cs @@ -0,0 +1,18 @@ +namespace CleanModelContextProtocol.Presentation.Models; + +using System.ComponentModel; + +/// +/// An author with a summary of the reviews they have written. +/// +/// The author's id. +/// The author's full name. +/// How many reviews the author has written. +/// The average star rating the author gives, from 1 to 5, or null when they have no reviews. +/// Every review the author has written, when they were asked for. +public record AuthorResult( + [property: Description("The author's id.")] Guid Id, + [property: Description("The author's full name.")] string Name, + [property: Description("How many reviews the author has written.")] int ReviewCount, + [property: Description("The average star rating the author gives, from 1 to 5, or null when they have no reviews.")] double? AverageStars, + [property: Description("Every review the author has written, when they were asked for.")] List Reviews = null); diff --git a/src/Presentation/Models/MovieResult.cs b/src/Presentation/Models/MovieResult.cs new file mode 100644 index 0000000..c857ba1 --- /dev/null +++ b/src/Presentation/Models/MovieResult.cs @@ -0,0 +1,18 @@ +namespace CleanModelContextProtocol.Presentation.Models; + +using System.ComponentModel; + +/// +/// A movie with a summary of how it was reviewed. +/// +/// The movie's id. +/// The movie's title. +/// How many reviews the movie has. +/// The average star rating, from 1 to 5, or null when there are no reviews. +/// Every review of the movie, when they were asked for. +public record MovieResult( + [property: Description("The movie's id.")] Guid Id, + [property: Description("The movie's title.")] string Title, + [property: Description("How many reviews the movie has.")] int ReviewCount, + [property: Description("The average star rating, from 1 to 5, or null when there are no reviews.")] double? AverageStars, + [property: Description("Every review of the movie, when they were asked for.")] List Reviews = null); diff --git a/src/Presentation/Models/ResultMapper.cs b/src/Presentation/Models/ResultMapper.cs new file mode 100644 index 0000000..cd7c3dd --- /dev/null +++ b/src/Presentation/Models/ResultMapper.cs @@ -0,0 +1,65 @@ +namespace CleanModelContextProtocol.Presentation.Models; + +using Application.Authors.Entities; +using Application.Common.Paging; +using Application.Movies.Entities; +using Application.Reviews.Entities; + +/// +/// Maps Application entities onto the results the tools return. +/// +public static class ResultMapper +{ + public static MovieResult ToResult(this Movie movie, bool includeReviews) + { + var reviews = movie.Reviews ?? []; + + return new MovieResult( + movie.Id, + movie.Title, + reviews.Count, + Average(reviews), + includeReviews ? [.. reviews.Select(r => r.ToResult(movie: new ReviewedMovie(movie.Id, movie.Title)))] : null); + } + + public static AuthorResult ToResult(this Author author, bool includeReviews) + { + var reviews = author.Reviews ?? []; + + return new AuthorResult( + author.Id, + FullName(author.FirstName, author.LastName), + reviews.Count, + Average(reviews), + includeReviews ? [.. reviews.Select(r => r.ToResult(author: new ReviewAuthor(author.Id, author.FirstName, author.LastName)))] : null); + } + + public static ReviewResult ToResult(this Review review, ReviewedMovie movie = null, ReviewAuthor author = null) + { + movie = review.ReviewedMovie ?? movie; + author = review.ReviewAuthor ?? author; + + return new ReviewResult( + review.Id, + review.Stars, + movie?.Id, + movie?.Title, + author?.Id, + author is null ? null : FullName(author.FirstName, author.LastName)); + } + + public static ResultPage ToResult(this Page page, Func map) + { + return new ResultPage([.. page.Items.Select(map)], page.TotalCount, page.NextCursor); + } + + private static string FullName(string firstName, string lastName) + { + return $"{firstName} {lastName}".Trim(); + } + + private static double? Average(ICollection reviews) + { + return reviews.Count == 0 ? null : Math.Round(reviews.Average(r => r.Stars), 1); + } +} diff --git a/src/Presentation/Models/ResultPage.cs b/src/Presentation/Models/ResultPage.cs new file mode 100644 index 0000000..1fddd91 --- /dev/null +++ b/src/Presentation/Models/ResultPage.cs @@ -0,0 +1,15 @@ +namespace CleanModelContextProtocol.Presentation.Models; + +using System.ComponentModel; + +/// +/// One page of results from a search tool. +/// +/// The type of the results. +/// The results on this page. +/// The number of results across every page. +/// Pass this as the cursor to get the next page. Null when this is the last page. +public record ResultPage( + [property: Description("The results on this page.")] List Items, + [property: Description("The number of results across every page.")] int TotalCount, + [property: Description("Pass this as the cursor to get the next page. Null when this is the last page.")] string NextCursor); diff --git a/src/Presentation/Models/ReviewResult.cs b/src/Presentation/Models/ReviewResult.cs new file mode 100644 index 0000000..8864490 --- /dev/null +++ b/src/Presentation/Models/ReviewResult.cs @@ -0,0 +1,20 @@ +namespace CleanModelContextProtocol.Presentation.Models; + +using System.ComponentModel; + +/// +/// A review, with the names of the movie and author next to their ids. +/// +/// The review's id. +/// The star rating, from 1 (worst) to 5 (best). +/// The id of the movie that was reviewed. +/// The title of the movie that was reviewed. +/// The id of the author who wrote the review. +/// The full name of the author who wrote the review. +public record ReviewResult( + [property: Description("The review's id.")] Guid Id, + [property: Description("The star rating, from 1 (worst) to 5 (best).")] int Stars, + [property: Description("The id of the movie that was reviewed.")] Guid? MovieId, + [property: Description("The title of the movie that was reviewed.")] string MovieTitle, + [property: Description("The id of the author who wrote the review.")] Guid? AuthorId, + [property: Description("The full name of the author who wrote the review.")] string AuthorName); diff --git a/src/Presentation/Serialization/AppJsonSerializerContext.cs b/src/Presentation/Serialization/AppJsonSerializerContext.cs index 449d5a0..c9d4ad1 100644 --- a/src/Presentation/Serialization/AppJsonSerializerContext.cs +++ b/src/Presentation/Serialization/AppJsonSerializerContext.cs @@ -28,6 +28,12 @@ namespace CleanModelContextProtocol.Presentation.Serialization; [JsonSerializable(typeof(Version))] [JsonSerializable(typeof(List))] [JsonSerializable(typeof(DeletedReview))] +[JsonSerializable(typeof(MovieResult))] +[JsonSerializable(typeof(AuthorResult))] +[JsonSerializable(typeof(ReviewResult))] +[JsonSerializable(typeof(ResultPage))] +[JsonSerializable(typeof(ResultPage))] +[JsonSerializable(typeof(ResultPage))] public partial class AppJsonSerializerContext : JsonSerializerContext { } diff --git a/src/Presentation/Tools/AuthorTools.cs b/src/Presentation/Tools/AuthorTools.cs index 85bfa04..5865514 100644 --- a/src/Presentation/Tools/AuthorTools.cs +++ b/src/Presentation/Tools/AuthorTools.cs @@ -1,31 +1,32 @@ namespace CleanModelContextProtocol.Presentation.Tools; using System.ComponentModel; +using CleanModelContextProtocol.Presentation.Models; using Mediator; using ModelContextProtocol.Server; -using Entities = Application.Authors.Entities; using Queries = Application.Authors.Queries; [McpServerToolType] public static class AuthorTools { - [McpServerTool(Name = "authors_list", Title = "List authors", ReadOnly = true, Idempotent = true, OpenWorld = false, UseStructuredContent = true)] - [Description("List every author who has written reviews, with their id, first and last name, and the reviews they have written. " + - "Use this to find an author's id before calling authors_get, reviews_create or reviews_update.")] - public static async Task> ListAuthors(ISender sender) - { - return await sender.Send(new Queries.GetAuthors.GetAuthorsQuery()); - } - - [McpServerTool(Name = "authors_get", Title = "Get author", ReadOnly = true, Idempotent = true, OpenWorld = false, UseStructuredContent = true)] - [Description("Get one author by id, including every review they have written and the movie each review is for.")] - public static async Task GetAuthor( + [McpServerTool(Name = "authors_search", Title = "Search authors", ReadOnly = true, Idempotent = true, OpenWorld = false, UseStructuredContent = true)] + [Description("Find the authors who write reviews by first name, last name or full name, ignoring case, in last-name order. " + + "Each result has the author's id, name, review count and the average stars they give. Leave the query empty to browse " + + "every author a page at a time. Use this to find an author's id before calling reviews_list or reviews_write.")] + public static async Task> SearchAuthors( ISender sender, - [Description("The author's id (a GUID). Use authors_list to find it.")] Guid authorId) + [Description("Part of the author's name, such as 'marie' or 'marie hirthe'. Leave empty to list every author.")] string query = null, + [Description("The most results to return, from 1 to 50.")] int limit = 10, + [Description("The nextCursor from a previous call, to get the next page. Leave empty for the first page.")] string cursor = null, + [Description("Also return every review each author has written. Leave false unless you need the individual reviews.")] bool includeReviews = false) { - return await sender.Send(new Queries.GetAuthorById.GetAuthorByIdQuery + var page = await sender.Send(new Queries.SearchAuthors.SearchAuthorsQuery { - Id = authorId + Query = query, + Limit = limit, + Cursor = cursor }); + + return page.ToResult(a => a.ToResult(includeReviews)); } } diff --git a/src/Presentation/Tools/MovieTools.cs b/src/Presentation/Tools/MovieTools.cs index 096e62b..fd53d54 100644 --- a/src/Presentation/Tools/MovieTools.cs +++ b/src/Presentation/Tools/MovieTools.cs @@ -1,31 +1,46 @@ namespace CleanModelContextProtocol.Presentation.Tools; using System.ComponentModel; +using CleanModelContextProtocol.Presentation.Models; using Mediator; using ModelContextProtocol.Server; -using Entities = Application.Movies.Entities; using Queries = Application.Movies.Queries; [McpServerToolType] public static class MovieTools { - [McpServerTool(Name = "movies_list", Title = "List movies", ReadOnly = true, Idempotent = true, OpenWorld = false, UseStructuredContent = true)] - [Description("List every movie with its id, title and reviews. " + - "Use this to find a movie's id before calling movies_get, reviews_create or reviews_update.")] - public static async Task> ListMovies(ISender sender) + [McpServerTool(Name = "movies_search", Title = "Search movies", ReadOnly = true, Idempotent = true, OpenWorld = false, UseStructuredContent = true)] + [Description("Find movies whose title contains a search term, ignoring case, in title order. Each result has the movie's id, " + + "title, review count and average stars. Leave the query empty to browse every movie a page at a time. " + + "Use this to find a movie's id before calling movies_get, reviews_list or reviews_write.")] + public static async Task> SearchMovies( + ISender sender, + [Description("Words to look for in the title, such as 'matrix'. Leave empty to list every movie.")] string query = null, + [Description("The most results to return, from 1 to 50.")] int limit = 10, + [Description("The nextCursor from a previous call, to get the next page. Leave empty for the first page.")] string cursor = null, + [Description("Also return every review of each movie. Leave false unless you need the individual reviews.")] bool includeReviews = false) { - return await sender.Send(new Queries.GetMovies.GetMoviesQuery()); + var page = await sender.Send(new Queries.SearchMovies.SearchMoviesQuery + { + Query = query, + Limit = limit, + Cursor = cursor + }); + + return page.ToResult(m => m.ToResult(includeReviews)); } [McpServerTool(Name = "movies_get", Title = "Get movie", ReadOnly = true, Idempotent = true, OpenWorld = false, UseStructuredContent = true)] - [Description("Get one movie by id, including every review of it with the star rating and the author who wrote it.")] - public static async Task GetMovie( + [Description("Get one 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). Use movies_list to find it.")] Guid movieId) + [Description("The movie's id (a GUID). Use movies_search to find it.")] Guid movieId) { - return await sender.Send(new Queries.GetMovieById.GetMovieByIdQuery + var movie = await sender.Send(new Queries.GetMovieById.GetMovieByIdQuery { Id = movieId }); + + return movie.ToResult(includeReviews: true); } } diff --git a/src/Presentation/Tools/ReviewTools.cs b/src/Presentation/Tools/ReviewTools.cs index 86ac7a6..6c931b1 100644 --- a/src/Presentation/Tools/ReviewTools.cs +++ b/src/Presentation/Tools/ReviewTools.cs @@ -5,70 +5,80 @@ namespace CleanModelContextProtocol.Presentation.Tools; using Mediator; using ModelContextProtocol.Server; using Commands = Application.Reviews.Commands; -using Entities = Application.Reviews.Entities; using Queries = Application.Reviews.Queries; [McpServerToolType] public static class ReviewTools { [McpServerTool(Name = "reviews_list", Title = "List reviews", ReadOnly = true, Idempotent = true, OpenWorld = false, UseStructuredContent = true)] - [Description("List every review with its id, star rating (1 to 5), the movie it is for and the author who wrote it.")] - public static async Task> ListReviews(ISender sender) - { - return await sender.Send(new Queries.GetReviews.GetReviewsQuery()); - } - - [McpServerTool(Name = "reviews_get", Title = "Get review", ReadOnly = true, Idempotent = true, OpenWorld = false, UseStructuredContent = true)] - [Description("Get one review by id, with its star rating, the movie it is for and the author who wrote it.")] - public static async Task GetReview( + [Description("List reviews with their star rating and the title and author of each, in movie-title order. Filter by movie, " + + "by author or both, or pass a reviewId to get exactly one review. With no filters it pages through every review.")] + public static async Task> ListReviews( ISender sender, - [Description("The review's id (a GUID). Use reviews_list to find it.")] Guid reviewId) + [Description("Only reviews of this movie. Use movies_search to find the id.")] Guid? movieId = null, + [Description("Only reviews by this author. Use authors_search to find the id.")] Guid? authorId = null, + [Description("Get this one review instead of searching. The other filters are ignored.")] Guid? reviewId = null, + [Description("The most results to return, from 1 to 50.")] int limit = 10, + [Description("The nextCursor from a previous call, to get the next page. Leave empty for the first page.")] string cursor = null) { - return await sender.Send(new Queries.GetReviewById.GetReviewByIdQuery + if (reviewId.HasValue) { - Id = reviewId - }); - } + var review = await sender.Send(new Queries.GetReviewById.GetReviewByIdQuery + { + Id = reviewId.Value + }); - [McpServerTool(Name = "reviews_create", Title = "Create review", ReadOnly = false, Destructive = false, Idempotent = false, OpenWorld = false, UseStructuredContent = true)] - [Description("Create a review of a movie by an author with a star rating from 1 to 5, and return the new review. " + - "Each call creates another review, so don't retry a call that succeeded.")] - public static async Task CreateReview( - ISender sender, - [Description("The id of the author writing the review. Use authors_list to find it.")] Guid authorId, - [Description("The id of the movie being reviewed. Use movies_list to find it.")] Guid movieId, - [Description("The star rating, a whole number from 1 (worst) to 5 (best).")] int stars) - { - return await sender.Send(new Commands.CreateReview.CreateReviewCommand + return new ResultPage([review.ToResult()], 1, null); + } + + var page = await sender.Send(new Queries.SearchReviews.SearchReviewsQuery { - AuthorId = authorId, MovieId = movieId, - Stars = stars + AuthorId = authorId, + Limit = limit, + Cursor = cursor }); + + return page.ToResult(r => r.ToResult()); } - [McpServerTool(Name = "reviews_update", Title = "Update review", ReadOnly = false, Destructive = true, Idempotent = true, OpenWorld = false, UseStructuredContent = true)] - [Description("Replace an existing review's author, movie and star rating. Every field is overwritten, " + - "so pass the current author and movie ids when you only want to change the stars. Returns the updated review.")] - public static async Task UpdateReview( + [McpServerTool(Name = "reviews_write", Title = "Write review", ReadOnly = false, Destructive = true, Idempotent = false, OpenWorld = false, UseStructuredContent = true)] + [Description("Create a review of a movie by an author with a star rating from 1 to 5, or pass a reviewId to replace that " + + "review's movie, author and stars. Returns the saved review. Without a reviewId every call creates another review, " + + "so don't retry a call that succeeded.")] + public static async Task WriteReview( ISender sender, - [Description("The id of the review to update. Use reviews_list to find it.")] Guid reviewId, - [Description("The id of the author writing the review. Use authors_list to find it.")] Guid authorId, - [Description("The id of the movie being reviewed. Use movies_list to find it.")] Guid movieId, - [Description("The star rating, a whole number from 1 (worst) to 5 (best).")] int stars) + [Description("The id of the movie being reviewed. Use movies_search to find it.")] Guid movieId, + [Description("The id of the author writing the review. Use authors_search to find it.")] Guid authorId, + [Description("The star rating, a whole number from 1 (worst) to 5 (best).")] int stars, + [Description("The id of an existing review to replace. Leave empty to create a new review.")] Guid? reviewId = null) { + if (!reviewId.HasValue) + { + var created = await sender.Send(new Commands.CreateReview.CreateReviewCommand + { + AuthorId = authorId, + MovieId = movieId, + Stars = stars + }); + + return created.ToResult(); + } + _ = await sender.Send(new Commands.UpdateReview.UpdateReviewCommand { - Id = reviewId, + Id = reviewId.Value, AuthorId = authorId, MovieId = movieId, Stars = stars }); - return await sender.Send(new Queries.GetReviewById.GetReviewByIdQuery + var updated = await sender.Send(new Queries.GetReviewById.GetReviewByIdQuery { - Id = reviewId + Id = reviewId.Value }); + + return updated.ToResult(); } [McpServerTool(Name = "reviews_delete", Title = "Delete review", ReadOnly = false, Destructive = true, Idempotent = true, OpenWorld = false, UseStructuredContent = true)] diff --git a/tests/Presentation.Tests.Integration/Tools/AuthorToolTests.cs b/tests/Presentation.Tests.Integration/Tools/AuthorToolTests.cs index 6086f2c..cd08e11 100644 --- a/tests/Presentation.Tests.Integration/Tools/AuthorToolTests.cs +++ b/tests/Presentation.Tests.Integration/Tools/AuthorToolTests.cs @@ -1,127 +1,54 @@ namespace CleanModelContextProtocol.Presentation.Tests.Integration.Tools; -using Extensions; -using ModelContextProtocol; -using ModelContextProtocol.Protocol; +using CleanModelContextProtocol.Presentation.Models; using Shouldly; using Xunit; -using Entities = Application.Authors.Entities; public class AuthorToolTests : BaseToolTests { [Fact] - public async Task GetAllAuthors_ShouldReturn_Authors() + public async Task SearchAuthors_ShouldReturn_EveryAuthor() { // Act - var result = await this.Client.CallToolAsync("authors_list"); - var text = result.Content.OfType().First().Text; - var authors = text.Deserialize>(); + var page = await this.CallAsync>("authors_search", new Dictionary { ["limit"] = 50 }); // Assert - _ = authors.ShouldNotBeNull(); + page.TotalCount.ShouldBe(15); + page.Items.Count.ShouldBe(15); + page.NextCursor.ShouldBeNull(); - authors.ShouldNotBeEmpty(); - authors.Count.ShouldBe(15); - - foreach (var author in authors) + foreach (var author in page.Items) { - _ = author.ShouldNotBeNull(); - _ = author.Id.ShouldBeOfType(); - _ = author.FirstName.ShouldBeOfType(); - author.FirstName.ShouldNotBeNullOrWhiteSpace(); - _ = author.LastName.ShouldBeOfType(); - author.LastName.ShouldNotBeNullOrWhiteSpace(); - - foreach (var review in author.Reviews ?? []) - { - _ = review.Stars.ShouldBeOfType(); - review.Stars.ShouldBeInRange(1, 5); - _ = review.ReviewedMovie.ShouldNotBeNull(); - _ = review.ReviewedMovie.Id.ShouldBeOfType(); - _ = review.ReviewedMovie.Title.ShouldBeOfType(); - review.ReviewedMovie.Title.ShouldNotBeNullOrWhiteSpace(); - } + author.Id.ShouldNotBe(Guid.Empty); + author.Name.ShouldNotBeNullOrWhiteSpace(); + author.Reviews.ShouldBeNull(); } } [Fact] - public async Task GetAuthorById_ShouldReturn_Author() + public async Task SearchAuthors_ShouldFind_AuthorByFullName() { // Arrange - var allResult = await this.Client.CallToolAsync("authors_list"); - var allText = allResult.Content.OfType().First().Text; - var firstAuthor = allText.Deserialize>()[0]; + var first = (await this.CallAsync>("authors_search")).Items[0]; // Act - var result = await this.Client.CallToolAsync("authors_get", - new Dictionary { ["authorId"] = firstAuthor.Id }); - var text = result.Content.OfType().First().Text; - var author = text.Deserialize(); + var page = await this.CallAsync>("authors_search", + new Dictionary { ["query"] = first.Name.ToLowerInvariant(), ["includeReviews"] = true }); // Assert - _ = author.ShouldNotBeNull(); - - author.Id.ShouldBe(firstAuthor.Id); - _ = author.FirstName.ShouldBeOfType(); - author.FirstName.ShouldNotBeNullOrWhiteSpace(); - _ = author.LastName.ShouldBeOfType(); - author.LastName.ShouldNotBeNullOrWhiteSpace(); - author.Reviews.ShouldNotBeEmpty(); - - foreach (var review in author.Reviews ?? []) - { - _ = review.Stars.ShouldBeOfType(); - review.Stars.ShouldBeInRange(1, 5); - _ = review.ReviewedMovie.ShouldNotBeNull(); - _ = review.ReviewedMovie!.Id.ShouldBeOfType(); - _ = review.ReviewedMovie.Title.ShouldBeOfType(); - review.ReviewedMovie.Title.ShouldNotBeNullOrWhiteSpace(); - } + var author = page.Items.ShouldHaveSingleItem(); + author.Id.ShouldBe(first.Id); + author.Reviews.Count.ShouldBe(author.ReviewCount); + author.Reviews.ShouldAllBe(r => r.AuthorId == author.Id && r.AuthorName == author.Name && r.MovieTitle != null); } [Fact] - public async Task GetAuthorById_WithEmptyId_ShouldReturn_ValidationError() + public async Task SearchAuthors_WithLongQuery_ShouldReturn_ValidationError() { // Act - var result = await this.Client.CallToolAsync("authors_get", - new Dictionary { ["authorId"] = Guid.Empty }); - var text = result.Content.OfType().First().Text; + var text = await this.CallForErrorAsync("authors_search", new Dictionary { ["query"] = new string('a', 101) }); // Assert - result.IsError.ShouldBe(true); - text.ShouldBe("Validation Failed: Id: An Author Id was not supplied. Correct the arguments and call the tool again."); - } - - [Fact] - public async Task GetAuthorById_WithUnknownId_ShouldReturn_NotFoundError() - { - // Act - var result = await this.Client.CallToolAsync("authors_get", - new Dictionary { ["authorId"] = Guid.NewGuid() }); - var text = result.Content.OfType().First().Text; - - // Assert - result.IsError.ShouldBe(true); - text.ShouldBe("Not Found: The Author with the supplied id was not found. Check the ids, using authors_list or the other list tools to find valid ones."); - } - - [Theory] - [InlineData("1")] - [InlineData("fake")] - public async Task GetAuthorById_WithInvalidId_ShouldReturn_Error(string input) - { - try - { - // Act - var result = await this.Client.CallToolAsync("authors_get", - new Dictionary { ["authorId"] = input }); - - // Assert - result.IsError.ShouldBe(true); - } - catch (McpException) - { - // Protocol-level error for unparseable inputs - expected - } + text.ShouldBe("Validation Failed: Query: A search term can't be longer than 100 characters. Correct the arguments and call the tool again."); } } diff --git a/tests/Presentation.Tests.Integration/Tools/BaseToolTests.cs b/tests/Presentation.Tests.Integration/Tools/BaseToolTests.cs index e1d54cf..7b14bce 100644 --- a/tests/Presentation.Tests.Integration/Tools/BaseToolTests.cs +++ b/tests/Presentation.Tests.Integration/Tools/BaseToolTests.cs @@ -1,7 +1,9 @@ namespace CleanModelContextProtocol.Presentation.Tests.Integration; +using Extensions; using ModelContextProtocol.Client; using ModelContextProtocol.Protocol; +using Shouldly; using Xunit; public abstract class BaseToolTests : IAsyncLifetime, IAsyncDisposable @@ -13,6 +15,24 @@ public abstract class BaseToolTests : IAsyncLifetime, IAsyncDisposable protected McpClient Client { get; private set; } #pragma warning restore CS8618 + protected async Task CallAsync(string name, Dictionary arguments = null) + { + var result = await this.Client.CallToolAsync(name, arguments); + + result.IsError.ShouldNotBe(true, result.Content.OfType().FirstOrDefault()?.Text); + + return result.Content.OfType().First().Text.Deserialize(); + } + + protected async Task CallForErrorAsync(string name, Dictionary arguments) + { + var result = await this.Client.CallToolAsync(name, arguments); + + result.IsError.ShouldBe(true); + + return result.Content.OfType().First().Text; + } + public async Task InitializeAsync() { this.application = new ModelContextProtocolApplication(); diff --git a/tests/Presentation.Tests.Integration/Tools/MovieToolTests.cs b/tests/Presentation.Tests.Integration/Tools/MovieToolTests.cs index d45bae6..6ee1f8f 100644 --- a/tests/Presentation.Tests.Integration/Tools/MovieToolTests.cs +++ b/tests/Presentation.Tests.Integration/Tools/MovieToolTests.cs @@ -1,116 +1,152 @@ namespace CleanModelContextProtocol.Presentation.Tests.Integration.Tools; -using Extensions; +using CleanModelContextProtocol.Presentation.Models; using ModelContextProtocol; -using ModelContextProtocol.Protocol; using Shouldly; using Xunit; -using Entities = Application.Movies.Entities; public class MovieToolTests : BaseToolTests { [Fact] - public async Task GetAllMovies_ShouldReturn_Movies() + public async Task SearchMovies_ShouldReturn_FirstPage() { // Act - var result = await this.Client.CallToolAsync("movies_list"); - var text = result.Content.OfType().First().Text; - var movies = text.Deserialize>(); + var page = await this.CallAsync>("movies_search"); // Assert - _ = movies.ShouldNotBeNull(); + page.TotalCount.ShouldBe(50); + page.Items.Count.ShouldBe(10); + page.NextCursor.ShouldNotBeNullOrWhiteSpace(); + page.Items.Select(m => m.Title).ShouldBeInOrder(SortDirection.Ascending, StringComparer.CurrentCulture); - movies.ShouldNotBeEmpty(); - movies.Count.ShouldBe(50); - - foreach (var movie in movies) + foreach (var movie in page.Items) { - _ = movie.ShouldNotBeNull(); - _ = movie.Id.ShouldBeOfType(); - _ = movie.Title.ShouldBeOfType(); + movie.Id.ShouldNotBe(Guid.Empty); movie.Title.ShouldNotBeNullOrWhiteSpace(); + movie.Reviews.ShouldBeNull(); + + if (movie.ReviewCount > 0) + { + movie.AverageStars.ShouldNotBeNull().ShouldBeInRange(1, 5); + } + } + } + + [Fact] + public async Task SearchMovies_ShouldPage_ThroughEveryMovie() + { + // Arrange + var titles = new List(); + string cursor = null; - foreach (var review in movie.Reviews ?? []) + // Act + do + { + var arguments = new Dictionary { ["limit"] = 20 }; + + if (cursor is not null) { - _ = review.Stars.ShouldBeOfType(); - review.Stars.ShouldBeInRange(1, 5); - - _ = review.ReviewAuthor.ShouldNotBeNull(); - _ = review.ReviewAuthor.Id.ShouldBeOfType(); - _ = review.ReviewAuthor.FirstName.ShouldBeOfType(); - review.ReviewAuthor.FirstName.ShouldNotBeNullOrWhiteSpace(); - _ = review.ReviewAuthor.LastName.ShouldBeOfType(); - review.ReviewAuthor.LastName.ShouldNotBeNullOrWhiteSpace(); + arguments["cursor"] = cursor; } + + var page = await this.CallAsync>("movies_search", arguments); + + titles.AddRange(page.Items.Select(m => m.Title)); + cursor = page.NextCursor; } + while (cursor is not null); + + // Assert + titles.Count.ShouldBe(50); } [Fact] - public async Task GetMovieById_ShouldReturn_Movie() + public async Task SearchMovies_ShouldFind_MovieByTitle() { // Arrange - var allResult = await this.Client.CallToolAsync("movies_list"); - var allText = allResult.Content.OfType().First().Text; - var firstMovie = allText.Deserialize>().First(m => m.Reviews?.Count > 0); + var first = (await this.CallAsync>("movies_search")).Items[0]; + + // Act + var page = await this.CallAsync>("movies_search", + new Dictionary { ["query"] = first.Title.ToUpperInvariant(), ["includeReviews"] = true }); + + // Assert + page.Items.ShouldContain(m => m.Id == first.Id); + page.Items.ShouldAllBe(m => m.Title.Contains(first.Title, StringComparison.OrdinalIgnoreCase)); + page.Items.ShouldAllBe(m => m.Reviews != null && m.Reviews.Count == m.ReviewCount); + } + + [Fact] + public async Task SearchMovies_WithInvalidLimit_ShouldReturn_ValidationError() + { + // Act + var text = await this.CallForErrorAsync("movies_search", new Dictionary { ["limit"] = 500 }); + // Assert + text.ShouldBe("Validation Failed: Limit: A limit must be between 1 and 50. Correct the arguments and call the tool again."); + } + + [Fact] + public async Task SearchMovies_WithInvalidCursor_ShouldReturn_ValidationError() + { // Act - var result = await this.Client.CallToolAsync("movies_get", - new Dictionary { ["movieId"] = firstMovie.Id }); - var text = result.Content.OfType().First().Text; - var movie = text.Deserialize(); + var text = await this.CallForErrorAsync("movies_search", new Dictionary { ["cursor"] = "nope" }); // Assert - _ = movie.ShouldNotBeNull(); + text.ShouldStartWith("Validation Failed: Cursor: The cursor is not valid."); + } + + [Fact] + public async Task GetMovie_ShouldReturn_MovieWithReviews() + { + // Arrange + var first = (await this.CallAsync>("movies_search", + new Dictionary { ["limit"] = 50 })).Items.First(m => m.ReviewCount > 0); - movie.Id.ShouldBe(firstMovie.Id); - _ = movie.Title.ShouldBeOfType(); - movie.Title.ShouldNotBeNullOrWhiteSpace(); - movie.Reviews.ShouldNotBeEmpty(); + // Act + var movie = await this.CallAsync("movies_get", new Dictionary { ["movieId"] = first.Id }); - foreach (var review in movie.Reviews ?? []) + // Assert + movie.Id.ShouldBe(first.Id); + movie.Title.ShouldBe(first.Title); + movie.ReviewCount.ShouldBe(first.ReviewCount); + movie.AverageStars.ShouldBe(first.AverageStars); + movie.Reviews.Count.ShouldBe(movie.ReviewCount); + + foreach (var review in movie.Reviews) { - _ = review.Stars.ShouldBeOfType(); review.Stars.ShouldBeInRange(1, 5); - - _ = review.ReviewAuthor.ShouldNotBeNull(); - _ = review.ReviewAuthor.Id.ShouldBeOfType(); - _ = review.ReviewAuthor.FirstName.ShouldBeOfType(); - review.ReviewAuthor.FirstName.ShouldNotBeNullOrWhiteSpace(); - _ = review.ReviewAuthor.LastName.ShouldBeOfType(); - review.ReviewAuthor.LastName.ShouldNotBeNullOrWhiteSpace(); + review.MovieId.ShouldBe(movie.Id); + review.MovieTitle.ShouldBe(movie.Title); + review.AuthorId.ShouldNotBeNull(); + review.AuthorName.ShouldNotBeNullOrWhiteSpace(); } } [Fact] - public async Task GetMovieById_WithEmptyId_ShouldReturn_ValidationError() + public async Task GetMovie_WithEmptyId_ShouldReturn_ValidationError() { // Act - var result = await this.Client.CallToolAsync("movies_get", - new Dictionary { ["movieId"] = Guid.Empty }); - var text = result.Content.OfType().First().Text; + var text = await this.CallForErrorAsync("movies_get", new Dictionary { ["movieId"] = Guid.Empty }); // Assert - result.IsError.ShouldBe(true); text.ShouldBe("Validation Failed: Id: A Movie Id was not supplied. Correct the arguments and call the tool again."); } [Fact] - public async Task GetMovieById_WithUnknownId_ShouldReturn_NotFoundError() + public async Task GetMovie_WithUnknownId_ShouldReturn_NotFoundError() { // Act - var result = await this.Client.CallToolAsync("movies_get", - new Dictionary { ["movieId"] = Guid.NewGuid() }); - var text = result.Content.OfType().First().Text; + var text = await this.CallForErrorAsync("movies_get", new Dictionary { ["movieId"] = Guid.NewGuid() }); // Assert - result.IsError.ShouldBe(true); - text.ShouldBe("Not Found: The Movie with the supplied id was not found. Check the ids, using movies_list or the other list tools to find valid ones."); + text.ShouldBe("Not Found: The Movie with the supplied id was not found. Check the ids: movies_search, authors_search and reviews_list return valid ones."); } [Theory] [InlineData("1")] [InlineData("fake")] - public async Task GetMovieById_WithInvalidId_ShouldReturn_Error(string input) + public async Task GetMovie_WithInvalidId_ShouldReturn_Error(string input) { try { diff --git a/tests/Presentation.Tests.Integration/Tools/ReviewToolTests.cs b/tests/Presentation.Tests.Integration/Tools/ReviewToolTests.cs index 860d818..cd3b7f9 100644 --- a/tests/Presentation.Tests.Integration/Tools/ReviewToolTests.cs +++ b/tests/Presentation.Tests.Integration/Tools/ReviewToolTests.cs @@ -1,240 +1,185 @@ namespace CleanModelContextProtocol.Presentation.Tests.Integration.Tools; using CleanModelContextProtocol.Presentation.Models; -using Extensions; -using ModelContextProtocol; -using ModelContextProtocol.Protocol; using Shouldly; using Xunit; -using AuthorEntities = Application.Authors.Entities; -using Entities = Application.Reviews.Entities; -using MovieEntities = Application.Movies.Entities; public class ReviewToolTests : BaseToolTests { + private async Task<(MovieResult Movie, AuthorResult Author)> FirstMovieAndAuthor() + { + var movie = (await this.CallAsync>("movies_search")).Items[0]; + var author = (await this.CallAsync>("authors_search")).Items[0]; + + return (movie, author); + } + [Fact] - public async Task GetAllReviews_ShouldReturn_Reviews() + public async Task ListReviews_ShouldReturn_FirstPage() { // Act - var result = await this.Client.CallToolAsync("reviews_list"); - var text = result.Content.OfType().First().Text; - var reviews = text.Deserialize>(); + var page = await this.CallAsync>("reviews_list"); // Assert - _ = reviews.ShouldNotBeNull(); - - reviews.ShouldNotBeEmpty(); - reviews.Count.ShouldBe(150); + page.TotalCount.ShouldBe(150); + page.Items.Count.ShouldBe(10); + page.NextCursor.ShouldNotBeNull(); - foreach (var review in reviews) + foreach (var review in page.Items) { - _ = review.ShouldNotBeNull(); - _ = review.Id.ShouldBeOfType(); - _ = review.Stars.ShouldBeOfType(); review.Stars.ShouldBeInRange(1, 5); - - _ = review.ReviewAuthor.ShouldNotBeNull(); - _ = review.ReviewAuthor.Id.ShouldBeOfType(); - _ = review.ReviewAuthor.FirstName.ShouldBeOfType(); - review.ReviewAuthor.FirstName.ShouldNotBeNullOrWhiteSpace(); - _ = review.ReviewAuthor.LastName.ShouldBeOfType(); - review.ReviewAuthor.LastName.ShouldNotBeNullOrWhiteSpace(); - - _ = review.ReviewedMovie.ShouldNotBeNull(); - _ = review.ReviewedMovie.Id.ShouldBeOfType(); - _ = review.ReviewedMovie.Title.ShouldBeOfType(); - review.ReviewedMovie.Title.ShouldNotBeNullOrWhiteSpace(); + review.MovieTitle.ShouldNotBeNullOrWhiteSpace(); + review.AuthorName.ShouldNotBeNullOrWhiteSpace(); } } [Fact] - public async Task GetReviewById_ShouldReturn_Review() + public async Task ListReviews_ShouldFilter_ByMovieAndAuthor() { // Arrange - var allResult = await this.Client.CallToolAsync("reviews_list"); - var allText = allResult.Content.OfType().First().Text; - var firstReview = allText.Deserialize>()[0]; + var movie = (await this.CallAsync>("movies_search", + new Dictionary { ["limit"] = 50 })).Items.First(m => m.ReviewCount > 0); + var review = (await this.CallAsync("movies_get", new Dictionary { ["movieId"] = movie.Id })).Reviews[0]; // Act - var result = await this.Client.CallToolAsync("reviews_get", - new Dictionary { ["reviewId"] = firstReview.Id }); - var text = result.Content.OfType().First().Text; - var review = text.Deserialize(); + var byMovie = await this.CallAsync>("reviews_list", + new Dictionary { ["movieId"] = movie.Id, ["limit"] = 50 }); + var byBoth = await this.CallAsync>("reviews_list", + new Dictionary { ["movieId"] = movie.Id, ["authorId"] = review.AuthorId }); // Assert - _ = review.ShouldNotBeNull(); - - _ = review.Id.ShouldBeOfType(); - review.Id.ShouldBe(firstReview.Id); - _ = review.Stars.ShouldBeOfType(); - review.Stars.ShouldBeInRange(1, 5); - - _ = review.ReviewAuthor.ShouldNotBeNull(); - _ = review.ReviewAuthor.Id.ShouldBeOfType(); - _ = review.ReviewAuthor.FirstName.ShouldBeOfType(); - review.ReviewAuthor.FirstName.ShouldNotBeNullOrWhiteSpace(); - _ = review.ReviewAuthor.LastName.ShouldBeOfType(); - review.ReviewAuthor.LastName.ShouldNotBeNullOrWhiteSpace(); - - _ = review.ReviewedMovie.ShouldNotBeNull(); - _ = review.ReviewedMovie.Id.ShouldBeOfType(); - _ = review.ReviewedMovie.Title.ShouldBeOfType(); + byMovie.TotalCount.ShouldBe(movie.ReviewCount); + byMovie.Items.ShouldAllBe(r => r.MovieId == movie.Id); + byBoth.Items.ShouldContain(r => r.Id == review.Id); + byBoth.Items.ShouldAllBe(r => r.MovieId == movie.Id && r.AuthorId == review.AuthorId); } [Fact] - public async Task CreateReview_ShouldReturn_Review() + public async Task ListReviews_ShouldReturn_OneReview() { // Arrange - var authorResult = await this.Client.CallToolAsync("authors_list"); - var authorText = authorResult.Content.OfType().First().Text; - var author = authorText.Deserialize>()[0]; - - var movieResult = await this.Client.CallToolAsync("movies_list"); - var movieText = movieResult.Content.OfType().First().Text; - var movie = movieText.Deserialize>()[0]; + var first = (await this.CallAsync>("reviews_list")).Items[0]; // Act - var result = await this.Client.CallToolAsync("reviews_create", - new Dictionary - { - ["authorId"] = author.Id, - ["movieId"] = movie.Id, - ["stars"] = 5 - }); - var text = result.Content.OfType().First().Text; - var review = text.Deserialize(); + var page = await this.CallAsync>("reviews_list", new Dictionary { ["reviewId"] = first.Id }); // Assert - _ = review.ShouldNotBeNull(); - - _ = review.Id.ShouldBeOfType(); - _ = review.Stars.ShouldBeOfType(); - review.Stars.ShouldBe(5); - - _ = review.ReviewAuthor.ShouldNotBeNull(); - review.ReviewAuthor.Id.ShouldBe(author.Id); - review.ReviewAuthor.FirstName.ShouldBe(author.FirstName); - review.ReviewAuthor.LastName.ShouldBe(author.LastName); - - _ = review.ReviewedMovie.ShouldNotBeNull(); - review.ReviewedMovie.Id.ShouldBe(movie.Id); - review.ReviewedMovie.Title.ShouldBe(movie.Title); + page.TotalCount.ShouldBe(1); + page.Items.ShouldHaveSingleItem().ShouldBe(first); } [Fact] - public async Task UpdateReview_ShouldReturn_Review() + public async Task ListReviews_WithUnknownReviewId_ShouldReturn_NotFoundError() { - // Arrange - var authorResult = await this.Client.CallToolAsync("authors_list"); - var authorText = authorResult.Content.OfType().First().Text; - var author = authorText.Deserialize>()[0]; - - var movieResult = await this.Client.CallToolAsync("movies_list"); - var movieText = movieResult.Content.OfType().First().Text; - var movie = movieText.Deserialize>()[0]; + // Act + var text = await this.CallForErrorAsync("reviews_list", new Dictionary { ["reviewId"] = Guid.NewGuid() }); - var reviewsResult = await this.Client.CallToolAsync("reviews_list"); - var reviewsText = reviewsResult.Content.OfType().First().Text; - var existingReview = reviewsText.Deserialize>()[0]; + // Assert + text.ShouldBe("Not Found: The Review with the supplied id was not found. Check the ids: movies_search, authors_search and reviews_list return valid ones."); + } + [Fact] + public async Task ListReviews_WithEmptyMovieId_ShouldReturn_ValidationError() + { // Act - var result = await this.Client.CallToolAsync("reviews_update", - new Dictionary - { - ["reviewId"] = existingReview.Id, - ["authorId"] = author.Id, - ["movieId"] = movie.Id, - ["stars"] = 5 - }); - var text = result.Content.OfType().First().Text; + var text = await this.CallForErrorAsync("reviews_list", new Dictionary { ["movieId"] = Guid.Empty }); // Assert - var updatedReview = text.Deserialize(); + text.ShouldStartWith("Validation Failed: MovieId: A Movie Id can't be empty."); + } - _ = updatedReview.ShouldNotBeNull(); + [Fact] + public async Task WriteReview_ShouldCreate_Review() + { + // Arrange + var (movie, author) = await this.FirstMovieAndAuthor(); - updatedReview.Id.ShouldBe(existingReview.Id); - updatedReview.Stars.ShouldBe(5); + // Act + var review = await this.CallAsync("reviews_write", + new Dictionary { ["movieId"] = movie.Id, ["authorId"] = author.Id, ["stars"] = 5 }); - _ = updatedReview.ReviewAuthor.ShouldNotBeNull(); - updatedReview.ReviewAuthor.Id.ShouldBe(author.Id); - updatedReview.ReviewAuthor.FirstName.ShouldBe(author.FirstName); - updatedReview.ReviewAuthor.LastName.ShouldBe(author.LastName); + // Assert + review.Id.ShouldNotBe(Guid.Empty); + review.Stars.ShouldBe(5); + review.MovieId.ShouldBe(movie.Id); + review.MovieTitle.ShouldBe(movie.Title); + review.AuthorId.ShouldBe(author.Id); + review.AuthorName.ShouldBe(author.Name); - _ = updatedReview.ReviewedMovie.ShouldNotBeNull(); - updatedReview.ReviewedMovie.Id.ShouldBe(movie.Id); - updatedReview.ReviewedMovie.Title.ShouldBe(movie.Title); + var after = await this.CallAsync("movies_get", new Dictionary { ["movieId"] = movie.Id }); + after.ReviewCount.ShouldBe(movie.ReviewCount + 1); } [Fact] - public async Task DeleteReview_ShouldReturn_Result() + public async Task WriteReview_ShouldUpdate_Review() { // Arrange - var reviewsResult = await this.Client.CallToolAsync("reviews_list"); - var reviewsText = reviewsResult.Content.OfType().First().Text; - var existingReview = reviewsText.Deserialize>()[0]; + var (movie, author) = await this.FirstMovieAndAuthor(); + var existing = (await this.CallAsync>("reviews_list")).Items[0]; // Act - var result = await this.Client.CallToolAsync("reviews_delete", - new Dictionary { ["reviewId"] = existingReview.Id }); - var text = result.Content.OfType().First().Text; + var review = await this.CallAsync("reviews_write", + new Dictionary { ["reviewId"] = existing.Id, ["movieId"] = movie.Id, ["authorId"] = author.Id, ["stars"] = 1 }); // Assert - var deleted = text.Deserialize(); + review.Id.ShouldBe(existing.Id); + review.Stars.ShouldBe(1); + review.MovieId.ShouldBe(movie.Id); + review.AuthorId.ShouldBe(author.Id); + } - deleted.ReviewId.ShouldBe(existingReview.Id); - deleted.Deleted.ShouldBeTrue(); + [Fact] + public async Task WriteReview_WithInvalidStars_ShouldReturn_ValidationError() + { + // Arrange + var (movie, author) = await this.FirstMovieAndAuthor(); - var validateResult = await this.Client.CallToolAsync("reviews_get", - new Dictionary { ["reviewId"] = existingReview.Id }); - var validateText = validateResult.Content.OfType().First().Text; + // Act + var text = await this.CallForErrorAsync("reviews_write", + new Dictionary { ["movieId"] = movie.Id, ["authorId"] = author.Id, ["stars"] = 9 }); - validateText.ShouldStartWith("Not Found:"); + // Assert + text.ShouldBe("Validation Failed: Stars: A star rating must be between 1 and 5. Correct the arguments and call the tool again."); } [Fact] - public async Task GetReviewById_WithEmptyId_ShouldReturn_ValidationError() + public async Task WriteReview_WithUnknownReviewId_ShouldReturn_NotFoundError() { + // Arrange + var (movie, author) = await this.FirstMovieAndAuthor(); + // Act - var result = await this.Client.CallToolAsync("reviews_get", - new Dictionary { ["reviewId"] = Guid.Empty }); - var text = result.Content.OfType().First().Text; + var text = await this.CallForErrorAsync("reviews_write", + new Dictionary { ["reviewId"] = Guid.NewGuid(), ["movieId"] = movie.Id, ["authorId"] = author.Id, ["stars"] = 3 }); // Assert - result.IsError.ShouldBe(true); - text.ShouldBe("Validation Failed: Id: A Review Id was not supplied. Correct the arguments and call the tool again."); + text.ShouldStartWith("Not Found:"); } [Fact] - public async Task GetReviewById_WithUnknownId_ShouldReturn_NotFoundError() + public async Task DeleteReview_ShouldDelete_Review() { + // Arrange + var existing = (await this.CallAsync>("reviews_list")).Items[0]; + // Act - var result = await this.Client.CallToolAsync("reviews_get", - new Dictionary { ["reviewId"] = Guid.NewGuid() }); - var text = result.Content.OfType().First().Text; + var result = await this.CallAsync("reviews_delete", new Dictionary { ["reviewId"] = existing.Id }); // Assert - result.IsError.ShouldBe(true); - text.ShouldBe("Not Found: The Review with the supplied id was not found. Check the ids, using reviews_list or the other list tools to find valid ones."); + result.ReviewId.ShouldBe(existing.Id); + result.Deleted.ShouldBeTrue(); + + var text = await this.CallForErrorAsync("reviews_list", new Dictionary { ["reviewId"] = existing.Id }); + text.ShouldStartWith("Not Found:"); } - [Theory] - [InlineData("1")] - [InlineData("fake")] - public async Task GetReviewById_WithInvalidId_ShouldReturn_Error(string input) + [Fact] + public async Task DeleteReview_WithUnknownId_ShouldReturn_NotFoundError() { - try - { - // Act - var result = await this.Client.CallToolAsync("reviews_get", - new Dictionary { ["reviewId"] = input }); + // Act + var text = await this.CallForErrorAsync("reviews_delete", new Dictionary { ["reviewId"] = Guid.NewGuid() }); - // Assert - result.IsError.ShouldBe(true); - } - catch (McpException) - { - // Protocol-level error for unparseable inputs - expected - } + // Assert + text.ShouldStartWith("Not Found: The Review with the supplied id was not found."); } } diff --git a/tests/Presentation.Tests.Integration/Tools/ToolListTests.cs b/tests/Presentation.Tests.Integration/Tools/ToolListTests.cs index 4a28f69..57bf66e 100644 --- a/tests/Presentation.Tests.Integration/Tools/ToolListTests.cs +++ b/tests/Presentation.Tests.Integration/Tools/ToolListTests.cs @@ -7,14 +7,11 @@ public class ToolListTests : BaseToolTests { public static TheoryData Tools => new() { - { "authors_list", "List authors", true, false, true }, - { "authors_get", "Get author", true, false, true }, - { "movies_list", "List movies", true, false, true }, + { "movies_search", "Search movies", true, false, true }, { "movies_get", "Get movie", true, false, true }, + { "authors_search", "Search authors", true, false, true }, { "reviews_list", "List reviews", true, false, true }, - { "reviews_get", "Get review", true, false, true }, - { "reviews_create", "Create review", false, false, false }, - { "reviews_update", "Update review", false, true, true }, + { "reviews_write", "Write review", false, true, false }, { "reviews_delete", "Delete review", false, true, true }, { "server_get_version", "Get server version", true, false, true } }; diff --git a/tests/Presentation.Tests.Unit/Errors/ToolErrorFilterTests.cs b/tests/Presentation.Tests.Unit/Errors/ToolErrorFilterTests.cs index ed2c61f..0726ccd 100644 --- a/tests/Presentation.Tests.Unit/Errors/ToolErrorFilterTests.cs +++ b/tests/Presentation.Tests.Unit/Errors/ToolErrorFilterTests.cs @@ -35,7 +35,7 @@ public async Task Filter_ShouldReturn_ErrorResult() // Assert result.IsError.ShouldBe(true); - result.Content.OfType().Single().Text.ShouldBe("Not Found: Expected Exception"); + result.Content.OfType().Single().Text.ShouldBe("Not Found: Expected Exception Check the ids: movies_search, authors_search and reviews_list return valid ones."); } [Fact] @@ -65,21 +65,7 @@ public void ToResult_ShouldReturn_NotFoundError() // Assert result.IsError.ShouldBe(true); - result.Content.OfType().Single().Text.ShouldBe("Not Found: Expected Exception"); - } - - [Theory] - [InlineData("movies_get", "Not Found: Expected Exception Check the ids, using movies_list or the other list tools to find valid ones.")] - [InlineData("server", "Not Found: Expected Exception")] - [InlineData("_get", "Not Found: Expected Exception")] - public void ToResult_ShouldReturn_NotFoundErrorWithHint(string toolName, string expected) - { - // Act - var result = ToolErrorFilter.ToResult(new NotFoundException("Expected Exception"), toolName); - - // Assert - result.IsError.ShouldBe(true); - result.Content.OfType().Single().Text.ShouldBe(expected); + result.Content.OfType().Single().Text.ShouldBe("Not Found: Expected Exception Check the ids: movies_search, authors_search and reviews_list return valid ones."); } [Fact] diff --git a/tests/Presentation.Tests.Unit/Tools/AuthorToolTests.cs b/tests/Presentation.Tests.Unit/Tools/AuthorToolTests.cs index 1cd9184..39dd438 100644 --- a/tests/Presentation.Tests.Unit/Tools/AuthorToolTests.cs +++ b/tests/Presentation.Tests.Unit/Tools/AuthorToolTests.cs @@ -1,5 +1,8 @@ namespace CleanModelContextProtocol.Presentation.Tests.Unit.Tools; +using Application.Common.Paging; +using Application.Movies.Entities; +using Application.Reviews.Entities; using CleanModelContextProtocol.Presentation.Tools; using Mediator; using NSubstitute; @@ -11,51 +14,45 @@ namespace CleanModelContextProtocol.Presentation.Tests.Unit.Tools; public class AuthorToolTests { [Fact] - public async Task GetAllAuthors_ShouldReturn_Result() + public async Task SearchAuthors_ShouldReturn_ConcisePage() { // Arrange var sender = Substitute.For(); + var author = new Entities.Author(Guid.Empty, "Lorem", "Ipsum", [new Review(Guid.Empty, 4, new ReviewedMovie(Guid.Empty, "Dolor"))]); _ = sender - .Send(Arg.Any()) - .ReturnsForAnyArgs( - [ - new Entities.Author(Guid.Empty, "Lorem", "Ipsum") - ]); + .Send(Arg.Is(q => q.Query == "lorem" && q.Limit == 10 && q.Cursor == null)) + .Returns(new Page([author], 1)); // Act - var response = await AuthorTools.ListAuthors(sender); + var response = await AuthorTools.SearchAuthors(sender, "lorem"); // Assert - var result = response; - - result.ShouldNotBeNull(); - result[0].Id.ShouldBe(Guid.Empty); - result[0].FirstName.ShouldBe("Lorem"); - result[0].LastName.ShouldBe("Ipsum"); - result[0].Reviews.ShouldBeNull(); + response.TotalCount.ShouldBe(1); + response.NextCursor.ShouldBeNull(); + response.Items[0].Name.ShouldBe("Lorem Ipsum"); + response.Items[0].ReviewCount.ShouldBe(1); + response.Items[0].AverageStars.ShouldBe(4); + response.Items[0].Reviews.ShouldBeNull(); } [Fact] - public async Task GetAuthorById_ShouldReturn_Result() + public async Task SearchAuthors_ShouldReturn_Reviews() { // Arrange var sender = Substitute.For(); + var author = new Entities.Author(Guid.Empty, "Lorem", "Ipsum", [new Review(Guid.Empty, 4, new ReviewedMovie(Guid.Empty, "Dolor"))]); _ = sender - .Send(Arg.Any()) - .ReturnsForAnyArgs(new Entities.Author(Guid.Empty, "Lorem", "Ipsum")); + .Send(Arg.Any()) + .ReturnsForAnyArgs(new Page([author], 1)); // Act - var response = await AuthorTools.GetAuthor(sender, Guid.Empty); + var response = await AuthorTools.SearchAuthors(sender, includeReviews: true); // Assert - var result = response; - - result.ShouldNotBeNull(); - result.Id.ShouldBe(Guid.Empty); - result.FirstName.ShouldBe("Lorem"); - result.LastName.ShouldBe("Ipsum"); - result.Reviews.ShouldBeNull(); + response.Items[0].Reviews.Count.ShouldBe(1); + response.Items[0].Reviews[0].MovieTitle.ShouldBe("Dolor"); + response.Items[0].Reviews[0].AuthorName.ShouldBe("Lorem Ipsum"); } } diff --git a/tests/Presentation.Tests.Unit/Tools/MovieToolTests.cs b/tests/Presentation.Tests.Unit/Tools/MovieToolTests.cs index 68f07f1..e286179 100644 --- a/tests/Presentation.Tests.Unit/Tools/MovieToolTests.cs +++ b/tests/Presentation.Tests.Unit/Tools/MovieToolTests.cs @@ -1,5 +1,8 @@ namespace CleanModelContextProtocol.Presentation.Tests.Unit.Tools; +using Application.Authors.Entities; +using Application.Common.Paging; +using Application.Reviews.Entities; using CleanModelContextProtocol.Presentation.Tools; using Mediator; using NSubstitute; @@ -10,50 +13,82 @@ namespace CleanModelContextProtocol.Presentation.Tests.Unit.Tools; public class MovieToolTests { + private static readonly Guid MovieId = Guid.NewGuid(); + + private static Entities.Movie SampleMovie() + { + return new(MovieId, "Lorem Ipsum", + [ + new Review(Guid.NewGuid(), 5, null, new ReviewAuthor(Guid.NewGuid(), "Dolor", "Sit")), + new Review(Guid.NewGuid(), 2, null, new ReviewAuthor(Guid.NewGuid(), "Amet", "Elit")) + ]); + } + [Fact] - public async Task GetAllMovies_ShouldReturn_Result() + public async Task SearchMovies_ShouldReturn_ConcisePage() { // Arrange var sender = Substitute.For(); _ = sender - .Send(Arg.Any()) - .ReturnsForAnyArgs( - [ - new Entities.Movie(Guid.Empty, "Lorem Ipsum") - ]); + .Send(Arg.Is(q => q.Query == "lorem" && q.Limit == 5 && q.Cursor == "abc")) + .Returns(new Page([SampleMovie()], 7, "next")); // Act - var response = await MovieTools.ListMovies(sender); + var response = await MovieTools.SearchMovies(sender, "lorem", 5, "abc"); // Assert - var result = response; - - result.ShouldNotBeNull(); - result[0].Id.ShouldBe(Guid.Empty); - result[0].Title.ShouldBe("Lorem Ipsum"); - result[0].Reviews.ShouldBeNull(); + response.TotalCount.ShouldBe(7); + response.NextCursor.ShouldBe("next"); + response.Items.Count.ShouldBe(1); + response.Items[0].Id.ShouldBe(MovieId); + response.Items[0].Title.ShouldBe("Lorem Ipsum"); + response.Items[0].ReviewCount.ShouldBe(2); + response.Items[0].AverageStars.ShouldBe(3.5); + response.Items[0].Reviews.ShouldBeNull(); } [Fact] - public async Task GetMovieById_ShouldReturn_Result() + public async Task SearchMovies_ShouldReturn_Reviews() { // Arrange var sender = Substitute.For(); _ = sender - .Send(Arg.Any()) - .ReturnsForAnyArgs(new Entities.Movie(Guid.Empty, "Lorem Ipsum")); + .Send(Arg.Any()) + .ReturnsForAnyArgs(new Page([SampleMovie(), new Entities.Movie(Guid.Empty, "Empty")], 2)); // Act - var response = await MovieTools.GetMovie(sender, Guid.Empty); + var response = await MovieTools.SearchMovies(sender, includeReviews: true); // Assert - var result = response; + response.Items[0].Reviews.Count.ShouldBe(2); + response.Items[0].Reviews[0].MovieTitle.ShouldBe("Lorem Ipsum"); + response.Items[0].Reviews[0].AuthorName.ShouldBe("Dolor Sit"); + response.Items[1].ReviewCount.ShouldBe(0); + response.Items[1].AverageStars.ShouldBeNull(); + response.Items[1].Reviews.ShouldBeEmpty(); + } + + [Fact] + public async Task GetMovie_ShouldReturn_MovieWithReviews() + { + // Arrange + var sender = Substitute.For(); + + _ = sender + .Send(Arg.Is(q => q.Id == MovieId)) + .Returns(SampleMovie()); + + // Act + var response = await MovieTools.GetMovie(sender, MovieId); - result.ShouldNotBeNull(); - result.Id.ShouldBe(Guid.Empty); - result.Title.ShouldBe("Lorem Ipsum"); - result.Reviews.ShouldBeNull(); + // Assert + response.Id.ShouldBe(MovieId); + response.AverageStars.ShouldBe(3.5); + response.Reviews.Count.ShouldBe(2); + response.Reviews[1].Stars.ShouldBe(2); + response.Reviews[1].MovieId.ShouldBe(MovieId); + response.Reviews[1].AuthorName.ShouldBe("Amet Elit"); } } diff --git a/tests/Presentation.Tests.Unit/Tools/ReviewToolTests.cs b/tests/Presentation.Tests.Unit/Tools/ReviewToolTests.cs index d011719..7a94c5b 100644 --- a/tests/Presentation.Tests.Unit/Tools/ReviewToolTests.cs +++ b/tests/Presentation.Tests.Unit/Tools/ReviewToolTests.cs @@ -1,6 +1,7 @@ namespace CleanModelContextProtocol.Presentation.Tests.Unit.Tools; using Application.Authors.Entities; +using Application.Common.Paging; using Application.Movies.Entities; using CleanModelContextProtocol.Presentation.Tools; using Mediator; @@ -13,113 +14,99 @@ namespace CleanModelContextProtocol.Presentation.Tests.Unit.Tools; public class ReviewToolTests { - private static Entities.Review SampleReview() + private static readonly Guid ReviewId = Guid.NewGuid(); + private static readonly Guid MovieId = Guid.NewGuid(); + private static readonly Guid AuthorId = Guid.NewGuid(); + + private static Entities.Review SampleReview(int stars = 5) { - return new( - Guid.Empty, - 5, - new ReviewedMovie(Guid.Empty, "Lorem Ipsum"), - new ReviewAuthor(Guid.Empty, "Lorem", "Ipsum")); + return new(ReviewId, stars, new ReviewedMovie(MovieId, "Lorem Ipsum"), new ReviewAuthor(AuthorId, "Dolor", "Sit")); } [Fact] - public async Task GetAllReviews_ShouldReturn_Result() + public async Task ListReviews_ShouldReturn_Page() { // Arrange var sender = Substitute.For(); _ = sender - .Send(Arg.Any()) - .ReturnsForAnyArgs([SampleReview()]); + .Send(Arg.Is(q => q.MovieId == MovieId && q.AuthorId == AuthorId && q.Limit == 2 && q.Cursor == "abc")) + .Returns(new Page([SampleReview()], 3, "next")); // Act - var response = await ReviewTools.ListReviews(sender); + var response = await ReviewTools.ListReviews(sender, MovieId, AuthorId, null, 2, "abc"); // Assert - var result = response; - - result.ShouldNotBeNull(); - result[0].Id.ShouldBe(Guid.Empty); - result[0].Stars.ShouldBe(5); - result[0].ReviewAuthor.Id.ShouldBe(Guid.Empty); - result[0].ReviewAuthor.FirstName.ShouldBe("Lorem"); - result[0].ReviewAuthor.LastName.ShouldBe("Ipsum"); - result[0].ReviewedMovie.Id.ShouldBe(Guid.Empty); - result[0].ReviewedMovie.Title.ShouldBe("Lorem Ipsum"); + response.TotalCount.ShouldBe(3); + response.NextCursor.ShouldBe("next"); + response.Items[0].Id.ShouldBe(ReviewId); + response.Items[0].Stars.ShouldBe(5); + response.Items[0].MovieId.ShouldBe(MovieId); + response.Items[0].MovieTitle.ShouldBe("Lorem Ipsum"); + response.Items[0].AuthorId.ShouldBe(AuthorId); + response.Items[0].AuthorName.ShouldBe("Dolor Sit"); } [Fact] - public async Task GetReviewById_ShouldReturn_Result() + public async Task ListReviews_ShouldReturn_OneReview() { // Arrange var sender = Substitute.For(); _ = sender - .Send(Arg.Any()) - .ReturnsForAnyArgs(SampleReview()); + .Send(Arg.Is(q => q.Id == ReviewId)) + .Returns(SampleReview()); // Act - var response = await ReviewTools.GetReview(sender, Guid.Empty); + var response = await ReviewTools.ListReviews(sender, reviewId: ReviewId); // Assert - var result = response; - - result.ShouldNotBeNull(); - result.Id.ShouldBe(Guid.Empty); - result.Stars.ShouldBe(5); - result.ReviewAuthor.Id.ShouldBe(Guid.Empty); - result.ReviewAuthor.FirstName.ShouldBe("Lorem"); - result.ReviewAuthor.LastName.ShouldBe("Ipsum"); - result.ReviewedMovie.Id.ShouldBe(Guid.Empty); - result.ReviewedMovie.Title.ShouldBe("Lorem Ipsum"); + response.TotalCount.ShouldBe(1); + response.NextCursor.ShouldBeNull(); + response.Items.Single().Id.ShouldBe(ReviewId); + _ = await sender.DidNotReceive().Send(Arg.Any()); } [Fact] - public async Task CreateReview_ShouldReturn_Result() + public async Task WriteReview_ShouldCreate_Review() { // Arrange var sender = Substitute.For(); _ = sender - .Send(Arg.Any()) - .ReturnsForAnyArgs(SampleReview()); + .Send(Arg.Is(c => c.MovieId == MovieId && c.AuthorId == AuthorId && c.Stars == 4)) + .Returns(SampleReview(4)); // Act - var response = await ReviewTools.CreateReview(sender, Guid.Empty, Guid.Empty, 5); + var response = await ReviewTools.WriteReview(sender, MovieId, AuthorId, 4); // Assert - var result = response; - - result.ShouldNotBeNull(); - result.Id.ShouldBe(Guid.Empty); - result.Stars.ShouldBe(5); - result.ReviewAuthor.Id.ShouldBe(Guid.Empty); - result.ReviewAuthor.FirstName.ShouldBe("Lorem"); - result.ReviewAuthor.LastName.ShouldBe("Ipsum"); - result.ReviewedMovie.Id.ShouldBe(Guid.Empty); - result.ReviewedMovie.Title.ShouldBe("Lorem Ipsum"); + response.Id.ShouldBe(ReviewId); + response.Stars.ShouldBe(4); + _ = await sender.DidNotReceive().Send(Arg.Any()); } [Fact] - public async Task UpdateReview_ShouldReturn_Review() + public async Task WriteReview_ShouldUpdate_Review() { // Arrange var sender = Substitute.For(); _ = sender - .Send(Arg.Any()) - .ReturnsForAnyArgs(true); + .Send(Arg.Is(c => c.Id == ReviewId && c.MovieId == MovieId && c.AuthorId == AuthorId && c.Stars == 2)) + .Returns(true); _ = sender - .Send(Arg.Any()) - .ReturnsForAnyArgs(SampleReview()); + .Send(Arg.Is(q => q.Id == ReviewId)) + .Returns(SampleReview(2)); // Act - var response = await ReviewTools.UpdateReview(sender, Guid.Empty, Guid.Empty, Guid.Empty, 5); + var response = await ReviewTools.WriteReview(sender, MovieId, AuthorId, 2, ReviewId); // Assert - response.Id.ShouldBe(Guid.Empty); - response.Stars.ShouldBe(5); + response.Id.ShouldBe(ReviewId); + response.Stars.ShouldBe(2); + _ = await sender.DidNotReceive().Send(Arg.Any()); } [Fact] @@ -129,14 +116,14 @@ public async Task DeleteReview_ShouldReturn_Result() var sender = Substitute.For(); _ = sender - .Send(Arg.Any()) - .ReturnsForAnyArgs(true); + .Send(Arg.Is(c => c.Id == ReviewId)) + .Returns(true); // Act - var response = await ReviewTools.DeleteReview(sender, Guid.Empty); + var response = await ReviewTools.DeleteReview(sender, ReviewId); // Assert - response.ReviewId.ShouldBe(Guid.Empty); + response.ReviewId.ShouldBe(ReviewId); response.Deleted.ShouldBeTrue(); } }