From 7f7306fc41dfff339b03bd162872a28f64f0356c Mon Sep 17 00:00:00 2001 From: Stephen Walsh Date: Wed, 28 Oct 2026 14:00:57 +0000 Subject: [PATCH 1/9] Run the MCP Inspector in Docker Compose, pointed at the server docker compose up now also starts the official MCP Inspector on localhost:6274, already configured for the server over Streamable HTTP, so the tools, their descriptions and input schemas can be browsed and run without installing anything. --- README.md | 2 +- docker-compose.yml | 9 +++++++++ docs/RUN.md | 5 +++-- 3 files changed, 13 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index f4fc306..8798de2 100644 --- a/README.md +++ b/README.md @@ -49,7 +49,7 @@ dotnet new cleanmodelcontextprotocol --name {YOUR_SOLUTION_NAMESPACE} --author " docker compose up -d ``` -Then open the MCP endpoint (connect with an MCP client such as the [MCP Inspector](https://github.com/modelcontextprotocol/inspector)) at . See [docs/RUN.md](docs/RUN.md) for every way to run it. +Then open the [MCP Inspector](https://github.com/modelcontextprotocol/inspector) at . It's already pointed at the MCP endpoint (), so connect and open **Tools** to browse and run them. See [docs/RUN.md](docs/RUN.md) for every way to run it. The `Dockerfile` has stages for testing, publishing and running, so you can build just the part you need. You can also stamp a version into the assembly. diff --git a/docker-compose.yml b/docker-compose.yml index 14946d5..ca1bb02 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -14,6 +14,15 @@ services: - cleanmodelcontextprotocol_network depends_on: - seq + inspector: + image: ghcr.io/modelcontextprotocol/inspector:2.12.0 + command: ["--web", "--transport", "http", "--server-url", "http://api:8080"] + ports: + - "127.0.0.1:6274:6274" + networks: + - cleanmodelcontextprotocol_network + depends_on: + - api seq: image: datalust/seq:latest ports: diff --git a/docs/RUN.md b/docs/RUN.md index bece1f6..69edcad 100644 --- a/docs/RUN.md +++ b/docs/RUN.md @@ -12,13 +12,14 @@ dotnet run --project ./src/Presentation ## Docker Compose -`docker-compose.yml` starts the app and a Seq container for logs. +`docker-compose.yml` starts the app, the [MCP Inspector](https://github.com/modelcontextprotocol/inspector) already pointed at it, and a Seq container for logs. ``` bash docker compose up -d --build ``` -- App: (MCP endpoint (connect with an MCP client such as the [MCP Inspector](https://github.com/modelcontextprotocol/inspector))) +- App: (MCP endpoint, Streamable HTTP) +- MCP Inspector: . Flip the switch on the server card to connect, then open **Tools** to see every tool with its description and input schema and run it. - Seq: To shut the containers down: From 0231b12b115efe2474cbb051fa14257935e896b1 Mon Sep 17 00:00:00 2001 From: Stephen Walsh Date: Wed, 28 Oct 2026 15:38:30 +0000 Subject: [PATCH 2/9] feat: give every MCP tool agent-ready metadata Rename the tools by resource (authors_list, movies_get, reviews_create and so on), add titles and the read-only, destructive, idempotent and open-world hints, and rewrite the descriptions and parameter names for agents. The server instructions now describe the domain instead of output formatting, the server info has a proper title and an absolute icon URL, and not-found and validation errors tell the agent how to recover. The server now runs stateless at /mcp, and a tools/list test pins the names, titles and hints. --- README.md | 7 +- docker-compose.yml | 2 +- docs/RUN.md | 2 +- src/Presentation/Errors/ToolErrorFilter.cs | 17 +++-- .../WebApplicationBuilderExtensions.cs | 24 ++++--- .../Extensions/WebApplicationExtensions.cs | 2 +- .../Properties/launchSettings.json | 3 +- src/Presentation/Tools/AuthorTools.cs | 17 +++-- src/Presentation/Tools/MovieTools.cs | 17 +++-- src/Presentation/Tools/ReviewTools.cs | 53 +++++++------- src/Presentation/Tools/VersionTools.cs | 4 +- .../Tools/AuthorToolTests.cs | 24 +++---- .../Tools/BaseToolTests.cs | 2 +- .../Tools/MovieToolTests.cs | 24 +++---- .../Tools/ReviewToolTests.cs | 54 +++++++------- .../Tools/ToolListTests.cs | 71 +++++++++++++++++++ .../Tools/VersionToolTests.cs | 2 +- .../Errors/ToolErrorFilterTests.cs | 16 ++++- .../Tools/AuthorToolTests.cs | 4 +- .../Tools/MovieToolTests.cs | 4 +- .../Tools/ReviewToolTests.cs | 4 +- 21 files changed, 230 insertions(+), 123 deletions(-) create mode 100644 tests/Presentation.Tests.Integration/Tools/ToolListTests.cs diff --git a/README.md b/README.md index 8798de2..b522130 100644 --- a/README.md +++ b/README.md @@ -49,7 +49,7 @@ dotnet new cleanmodelcontextprotocol --name {YOUR_SOLUTION_NAMESPACE} --author " docker compose up -d ``` -Then open the [MCP Inspector](https://github.com/modelcontextprotocol/inspector) at . It's already pointed at the MCP endpoint (), so connect and open **Tools** to browse and run them. See [docs/RUN.md](docs/RUN.md) for every way to run it. +Then open the [MCP Inspector](https://github.com/modelcontextprotocol/inspector) at . It's already pointed at the MCP endpoint (), so connect and open **Tools** to browse and run them. See [docs/RUN.md](docs/RUN.md) for every way to run it. The `Dockerfile` has stages for testing, publishing and running, so you can build just the part you need. You can also stamp a version into the assembly. @@ -79,11 +79,12 @@ 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) +- 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 - 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 -- Tool errors mapped from Application exceptions by a single call-tool filter +- Tool errors mapped from Application exceptions by a single call-tool filter, with messages that tell the agent how to recover - 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/docker-compose.yml b/docker-compose.yml index ca1bb02..7f5267a 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -16,7 +16,7 @@ services: - seq inspector: image: ghcr.io/modelcontextprotocol/inspector:2.12.0 - command: ["--web", "--transport", "http", "--server-url", "http://api:8080"] + command: ["--web", "--transport", "http", "--server-url", "http://api:8080/mcp"] ports: - "127.0.0.1:6274:6274" networks: diff --git a/docs/RUN.md b/docs/RUN.md index 69edcad..9ee7f48 100644 --- a/docs/RUN.md +++ b/docs/RUN.md @@ -18,7 +18,7 @@ dotnet run --project ./src/Presentation docker compose up -d --build ``` -- App: (MCP endpoint, Streamable HTTP) +- App: (MCP endpoint, Streamable HTTP) - MCP Inspector: . Flip the switch on the server card to connect, then open **Tools** to see every tool with its description and input schema and run it. - Seq: diff --git a/src/Presentation/Errors/ToolErrorFilter.cs b/src/Presentation/Errors/ToolErrorFilter.cs index c46e932..16516cf 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); + return ToResult(exception, request?.Params?.Name); } }; } - public static CallToolResult ToResult(Exception exception) + public static CallToolResult ToResult(Exception exception, string toolName = null) { var message = exception switch { ValidationException validationException => "Validation Failed: " + string.Join(" ", validationException.Errors .Select(e => $"{e.PropertyName}: {e.ErrorMessage}") - .Distinct()), - NotFoundException => $"Not Found: {exception.Message}", + .Distinct()) + " Correct the arguments and call the tool again.", + NotFoundException => $"Not Found: {exception.Message}{ListToolHint(toolName)}", _ => "Error: An error occurred while processing your request." }; @@ -42,4 +42,13 @@ public static CallToolResult ToResult(Exception exception) Content = [new TextContentBlock { Text = message }] }; } + + private static string ListToolHint(string toolName) + { + var separator = toolName?.IndexOf('_') ?? -1; + + 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 28c0ee0..3e4bf3d 100644 --- a/src/Presentation/Extensions/WebApplicationBuilderExtensions.cs +++ b/src/Presentation/Extensions/WebApplicationBuilderExtensions.cs @@ -61,28 +61,30 @@ public static WebApplicationBuilder ConfigureApplicationBuilder(this WebApplicat { options.ServerInfo = new() { - Name = "Clean Model Context Protocol", - Description = "A demonstration of the Clean Model Context Protocol in a .NET application", - Title = "Clean Model Context Protocol - Presentation Layer", + Name = "clean-model-context-protocol", + Title = "Clean Model Context Protocol", + Description = "Movies, the authors who review them, and their star ratings, served by a Clean Architecture .NET MCP server.", Version = assembly?.GetCustomAttribute()?.InformationalVersion ?? string.Empty, WebsiteUrl = "https://github.com/stphnwlsh/CleanModelContextProtocol", Icons = [ new() { - Source = "images/Icon.png", + Source = "https://raw.githubusercontent.com/stphnwlsh/CleanModelContextProtocol/main/icon.png", MimeType = "image/png" } ], }; - options.ServerInstructions = "You are a helpful assistant for handling requests related to movies, " + - "authors, and reviews. Use the available tools to retrieve information about movies, authors, and " + - "reviews based on the queries you receive. Always ensure that your responses are accurate and relevant " + - "to the user's request. Return the full sets of data anc convert them into tabulated markdown formats " + - "for display where sensible. Some datasets involve a number of sub objects, please calculate a count of " + - "that data for better formatting."; + 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. + reviews_delete can't be undone, so confirm with the user before calling it. + """; }) - .WithHttpTransport() + .WithHttpTransport(options => options.Stateless = true) .WithToolsFromAssembly() .WithRequestFilters(filters => filters.AddCallToolFilter(ToolErrorFilter.Filter)); diff --git a/src/Presentation/Extensions/WebApplicationExtensions.cs b/src/Presentation/Extensions/WebApplicationExtensions.cs index 75f2544..d6c3709 100644 --- a/src/Presentation/Extensions/WebApplicationExtensions.cs +++ b/src/Presentation/Extensions/WebApplicationExtensions.cs @@ -17,7 +17,7 @@ public static WebApplication ConfigureApplication(this WebApplication app) #region Model Context Protocol - _ = app.MapMcp(); + _ = app.MapMcp("/mcp"); #endregion Model Context Protocol diff --git a/src/Presentation/Properties/launchSettings.json b/src/Presentation/Properties/launchSettings.json index 82ac895..227f1a5 100644 --- a/src/Presentation/Properties/launchSettings.json +++ b/src/Presentation/Properties/launchSettings.json @@ -3,8 +3,7 @@ "profiles": { "CleanModelContextProtocol": { "commandName": "Project", - "launchBrowser": true, - "launchUrl": "swagger", + "launchBrowser": false, "applicationUrl": "https://localhost:7032;http://localhost:5032", "environmentVariables": { "DOTNET_ENVIRONMENT": "local" diff --git a/src/Presentation/Tools/AuthorTools.cs b/src/Presentation/Tools/AuthorTools.cs index 26fd2bd..bbfa88e 100644 --- a/src/Presentation/Tools/AuthorTools.cs +++ b/src/Presentation/Tools/AuthorTools.cs @@ -9,22 +9,25 @@ namespace CleanModelContextProtocol.Presentation.Tools; [McpServerToolType] public static class AuthorTools { - [McpServerTool(Name = "GetAllAuthors", ReadOnly = true)] - [Description("Get all authors in the system")] - public static async Task GetAllAuthors(ISender sender) + [McpServerTool(Name = "authors_list", Title = "List authors", ReadOnly = true, Idempotent = true, OpenWorld = false)] + [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) { var result = await sender.Send(new Queries.GetAuthors.GetAuthorsQuery()); return JsonSerializer.Serialize(result); } - [McpServerTool(Name = "GetAuthorById", ReadOnly = true)] - [Description("Get a specific author by their unique ID")] - public static async Task GetAuthorById(ISender sender, [Description("The GUID of the author")] Guid id) + [McpServerTool(Name = "authors_get", Title = "Get author", ReadOnly = true, Idempotent = true, OpenWorld = false)] + [Description("Get one author by id, including every review they have written and the movie each review is for.")] + public static async Task GetAuthor( + ISender sender, + [Description("The author's id (a GUID). Use authors_list to find it.")] Guid authorId) { return JsonSerializer.Serialize(await sender.Send(new Queries.GetAuthorById.GetAuthorByIdQuery { - Id = id + Id = authorId })); } } diff --git a/src/Presentation/Tools/MovieTools.cs b/src/Presentation/Tools/MovieTools.cs index 30546e7..bc84866 100644 --- a/src/Presentation/Tools/MovieTools.cs +++ b/src/Presentation/Tools/MovieTools.cs @@ -9,22 +9,25 @@ namespace CleanModelContextProtocol.Presentation.Tools; [McpServerToolType] public static class MovieTools { - [McpServerTool(Name = "GetAllMovies", ReadOnly = true)] - [Description("Get all movies in the system")] - public static async Task GetAllMovies(ISender sender) + [McpServerTool(Name = "movies_list", Title = "List movies", ReadOnly = true, Idempotent = true, OpenWorld = false)] + [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) { var result = await sender.Send(new Queries.GetMovies.GetMoviesQuery()); return JsonSerializer.Serialize(result); } - [McpServerTool(Name = "GetMovieById", ReadOnly = true)] - [Description("Get a specific movie by its unique ID")] - public static async Task GetMovieById(ISender sender, [Description("The GUID of the movie")] Guid id) + [McpServerTool(Name = "movies_get", Title = "Get movie", ReadOnly = true, Idempotent = true, OpenWorld = false)] + [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( + ISender sender, + [Description("The movie's id (a GUID). Use movies_list to find it.")] Guid movieId) { return JsonSerializer.Serialize(await sender.Send(new Queries.GetMovieById.GetMovieByIdQuery { - Id = id + Id = movieId })); } } diff --git a/src/Presentation/Tools/ReviewTools.cs b/src/Presentation/Tools/ReviewTools.cs index 14470f4..d8d7bfc 100644 --- a/src/Presentation/Tools/ReviewTools.cs +++ b/src/Presentation/Tools/ReviewTools.cs @@ -10,33 +10,35 @@ namespace CleanModelContextProtocol.Presentation.Tools; [McpServerToolType] public static class ReviewTools { - [McpServerTool(Name = "GetAllReviews", ReadOnly = true)] - [Description("Get all reviews in the system")] - public static async Task GetAllReviews(ISender sender) + [McpServerTool(Name = "reviews_list", Title = "List reviews", ReadOnly = true, Idempotent = true, OpenWorld = false)] + [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) { var result = await sender.Send(new Queries.GetReviews.GetReviewsQuery()); return JsonSerializer.Serialize(result); } - [McpServerTool(Name = "GetReviewById", ReadOnly = true)] - [DisplayName("GetReviewById2")] - [Description("Get a specific review by its unique ID")] - public static async Task GetReviewById(ISender sender, [Description("The GUID of the review")] Guid id) + [McpServerTool(Name = "reviews_get", Title = "Get review", ReadOnly = true, Idempotent = true, OpenWorld = false)] + [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( + ISender sender, + [Description("The review's id (a GUID). Use reviews_list to find it.")] Guid reviewId) { return JsonSerializer.Serialize(await sender.Send(new Queries.GetReviewById.GetReviewByIdQuery { - Id = id + Id = reviewId })); } - [McpServerTool(Name = "CreateReview")] - [Description("Create a new review linking an author and a movie")] + [McpServerTool(Name = "reviews_create", Title = "Create review", ReadOnly = false, Destructive = false, Idempotent = false, OpenWorld = false)] + [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 GUID of the author writing the review")] Guid authorId, - [Description("The GUID of the movie being reviewed")] Guid movieId, - [Description("Star rating for the movie (e.g. 1-5)")] int stars) + [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) { var result = await sender.Send(new Commands.CreateReview.CreateReviewCommand { @@ -48,18 +50,19 @@ public static async Task CreateReview( return JsonSerializer.Serialize(result); } - [McpServerTool(Name = "UpdateReview")] - [Description("Update an existing review")] + [McpServerTool(Name = "reviews_update", Title = "Update review", ReadOnly = false, Destructive = true, Idempotent = true, OpenWorld = false)] + [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.")] public static async Task UpdateReview( ISender sender, - [Description("The GUID of the review to update")] Guid id, - [Description("The GUID of the author writing the review")] Guid authorId, - [Description("The GUID of the movie being reviewed")] Guid movieId, - [Description("Star rating for the movie (e.g. 1-5)")] int stars) + [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) { _ = await sender.Send(new Commands.UpdateReview.UpdateReviewCommand { - Id = id, + Id = reviewId, AuthorId = authorId, MovieId = movieId, Stars = stars @@ -68,13 +71,15 @@ public static async Task UpdateReview( return "Review updated successfully"; } - [McpServerTool(Name = "DeleteReview")] - [Description("Delete a review by its unique ID")] - public static async Task DeleteReview(ISender sender, [Description("The GUID of the review to delete")] Guid id) + [McpServerTool(Name = "reviews_delete", Title = "Delete review", ReadOnly = false, Destructive = true, Idempotent = true, OpenWorld = false)] + [Description("Permanently delete a review. This can't be undone, so confirm with the user first.")] + public static async Task DeleteReview( + ISender sender, + [Description("The id of the review to delete. Use reviews_list to find it.")] Guid reviewId) { _ = await sender.Send(new Commands.DeleteReview.DeleteReviewCommand { - Id = id + Id = reviewId }); return "Review deleted successfully"; diff --git a/src/Presentation/Tools/VersionTools.cs b/src/Presentation/Tools/VersionTools.cs index 1e86066..53baf03 100644 --- a/src/Presentation/Tools/VersionTools.cs +++ b/src/Presentation/Tools/VersionTools.cs @@ -8,8 +8,8 @@ namespace CleanModelContextProtocol.Presentation.Tools; [McpServerToolType] public static class VersionTools { - [McpServerTool(Name = "GetVersion", ReadOnly = true)] - [Description("Get the current application version details")] + [McpServerTool(Name = "server_get_version", Title = "Get server version", ReadOnly = true, Idempotent = true, OpenWorld = false)] + [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) { var result = await sender.Send(new Queries.GetVersion.GetVersionQuery()); diff --git a/tests/Presentation.Tests.Integration/Tools/AuthorToolTests.cs b/tests/Presentation.Tests.Integration/Tools/AuthorToolTests.cs index 77c0dff..6086f2c 100644 --- a/tests/Presentation.Tests.Integration/Tools/AuthorToolTests.cs +++ b/tests/Presentation.Tests.Integration/Tools/AuthorToolTests.cs @@ -13,7 +13,7 @@ public class AuthorToolTests : BaseToolTests public async Task GetAllAuthors_ShouldReturn_Authors() { // Act - var result = await this.Client.CallToolAsync("GetAllAuthors"); + var result = await this.Client.CallToolAsync("authors_list"); var text = result.Content.OfType().First().Text; var authors = text.Deserialize>(); @@ -48,13 +48,13 @@ public async Task GetAllAuthors_ShouldReturn_Authors() public async Task GetAuthorById_ShouldReturn_Author() { // Arrange - var allResult = await this.Client.CallToolAsync("GetAllAuthors"); + var allResult = await this.Client.CallToolAsync("authors_list"); var allText = allResult.Content.OfType().First().Text; var firstAuthor = allText.Deserialize>()[0]; // Act - var result = await this.Client.CallToolAsync("GetAuthorById", - new Dictionary { ["id"] = firstAuthor.Id }); + var result = await this.Client.CallToolAsync("authors_get", + new Dictionary { ["authorId"] = firstAuthor.Id }); var text = result.Content.OfType().First().Text; var author = text.Deserialize(); @@ -83,26 +83,26 @@ public async Task GetAuthorById_ShouldReturn_Author() public async Task GetAuthorById_WithEmptyId_ShouldReturn_ValidationError() { // Act - var result = await this.Client.CallToolAsync("GetAuthorById", - new Dictionary { ["id"] = Guid.Empty }); + var result = await this.Client.CallToolAsync("authors_get", + new Dictionary { ["authorId"] = Guid.Empty }); var text = result.Content.OfType().First().Text; // Assert result.IsError.ShouldBe(true); - text.ShouldBe("Validation Failed: Id: An Author Id was not supplied."); + 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("GetAuthorById", - new Dictionary { ["id"] = Guid.NewGuid() }); + 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."); + 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] @@ -113,8 +113,8 @@ public async Task GetAuthorById_WithInvalidId_ShouldReturn_Error(string input) try { // Act - var result = await this.Client.CallToolAsync("GetAuthorById", - new Dictionary { ["id"] = input }); + var result = await this.Client.CallToolAsync("authors_get", + new Dictionary { ["authorId"] = input }); // Assert result.IsError.ShouldBe(true); diff --git a/tests/Presentation.Tests.Integration/Tools/BaseToolTests.cs b/tests/Presentation.Tests.Integration/Tools/BaseToolTests.cs index 9e9633e..bcebd96 100644 --- a/tests/Presentation.Tests.Integration/Tools/BaseToolTests.cs +++ b/tests/Presentation.Tests.Integration/Tools/BaseToolTests.cs @@ -18,7 +18,7 @@ public async Task InitializeAsync() this.application = new CleanModelContextProtocolApplication(); this.Client = await McpClient.CreateAsync( new HttpClientTransport( - new HttpClientTransportOptions { Endpoint = new Uri("http://localhost") }, + new HttpClientTransportOptions { Endpoint = new Uri("http://localhost/mcp") }, this.application.CreateClient(), null, false), diff --git a/tests/Presentation.Tests.Integration/Tools/MovieToolTests.cs b/tests/Presentation.Tests.Integration/Tools/MovieToolTests.cs index 5314d61..d45bae6 100644 --- a/tests/Presentation.Tests.Integration/Tools/MovieToolTests.cs +++ b/tests/Presentation.Tests.Integration/Tools/MovieToolTests.cs @@ -13,7 +13,7 @@ public class MovieToolTests : BaseToolTests public async Task GetAllMovies_ShouldReturn_Movies() { // Act - var result = await this.Client.CallToolAsync("GetAllMovies"); + var result = await this.Client.CallToolAsync("movies_list"); var text = result.Content.OfType().First().Text; var movies = text.Deserialize>(); @@ -49,13 +49,13 @@ public async Task GetAllMovies_ShouldReturn_Movies() public async Task GetMovieById_ShouldReturn_Movie() { // Arrange - var allResult = await this.Client.CallToolAsync("GetAllMovies"); + 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); // Act - var result = await this.Client.CallToolAsync("GetMovieById", - new Dictionary { ["id"] = firstMovie.Id }); + var result = await this.Client.CallToolAsync("movies_get", + new Dictionary { ["movieId"] = firstMovie.Id }); var text = result.Content.OfType().First().Text; var movie = text.Deserialize(); @@ -85,26 +85,26 @@ public async Task GetMovieById_ShouldReturn_Movie() public async Task GetMovieById_WithEmptyId_ShouldReturn_ValidationError() { // Act - var result = await this.Client.CallToolAsync("GetMovieById", - new Dictionary { ["id"] = Guid.Empty }); + var result = await this.Client.CallToolAsync("movies_get", + new Dictionary { ["movieId"] = Guid.Empty }); var text = result.Content.OfType().First().Text; // Assert result.IsError.ShouldBe(true); - text.ShouldBe("Validation Failed: Id: A Movie Id was not supplied."); + 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() { // Act - var result = await this.Client.CallToolAsync("GetMovieById", - new Dictionary { ["id"] = Guid.NewGuid() }); + var result = await this.Client.CallToolAsync("movies_get", + new Dictionary { ["movieId"] = Guid.NewGuid() }); var text = result.Content.OfType().First().Text; // Assert result.IsError.ShouldBe(true); - text.ShouldBe("Not Found: The Movie with the supplied id was not found."); + 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."); } [Theory] @@ -115,8 +115,8 @@ public async Task GetMovieById_WithInvalidId_ShouldReturn_Error(string input) try { // Act - var result = await this.Client.CallToolAsync("GetMovieById", - new Dictionary { ["id"] = input }); + var result = await this.Client.CallToolAsync("movies_get", + new Dictionary { ["movieId"] = input }); // Assert result.IsError.ShouldBe(true); diff --git a/tests/Presentation.Tests.Integration/Tools/ReviewToolTests.cs b/tests/Presentation.Tests.Integration/Tools/ReviewToolTests.cs index 41c984d..c8b9541 100644 --- a/tests/Presentation.Tests.Integration/Tools/ReviewToolTests.cs +++ b/tests/Presentation.Tests.Integration/Tools/ReviewToolTests.cs @@ -15,7 +15,7 @@ public class ReviewToolTests : BaseToolTests public async Task GetAllReviews_ShouldReturn_Reviews() { // Act - var result = await this.Client.CallToolAsync("GetAllReviews"); + var result = await this.Client.CallToolAsync("reviews_list"); var text = result.Content.OfType().First().Text; var reviews = text.Deserialize>(); @@ -50,13 +50,13 @@ public async Task GetAllReviews_ShouldReturn_Reviews() public async Task GetReviewById_ShouldReturn_Review() { // Arrange - var allResult = await this.Client.CallToolAsync("GetAllReviews"); + var allResult = await this.Client.CallToolAsync("reviews_list"); var allText = allResult.Content.OfType().First().Text; var firstReview = allText.Deserialize>()[0]; // Act - var result = await this.Client.CallToolAsync("GetReviewById", - new Dictionary { ["id"] = firstReview.Id }); + var result = await this.Client.CallToolAsync("reviews_get", + new Dictionary { ["reviewId"] = firstReview.Id }); var text = result.Content.OfType().First().Text; var review = text.Deserialize(); @@ -84,16 +84,16 @@ public async Task GetReviewById_ShouldReturn_Review() public async Task CreateReview_ShouldReturn_Review() { // Arrange - var authorResult = await this.Client.CallToolAsync("GetAllAuthors"); + 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("GetAllMovies"); + var movieResult = await this.Client.CallToolAsync("movies_list"); var movieText = movieResult.Content.OfType().First().Text; var movie = movieText.Deserialize>()[0]; // Act - var result = await this.Client.CallToolAsync("CreateReview", + var result = await this.Client.CallToolAsync("reviews_create", new Dictionary { ["authorId"] = author.Id, @@ -124,23 +124,23 @@ public async Task CreateReview_ShouldReturn_Review() public async Task UpdateReview_ShouldReturn_Success() { // Arrange - var authorResult = await this.Client.CallToolAsync("GetAllAuthors"); + 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("GetAllMovies"); + var movieResult = await this.Client.CallToolAsync("movies_list"); var movieText = movieResult.Content.OfType().First().Text; var movie = movieText.Deserialize>()[0]; - var reviewsResult = await this.Client.CallToolAsync("GetAllReviews"); + var reviewsResult = await this.Client.CallToolAsync("reviews_list"); var reviewsText = reviewsResult.Content.OfType().First().Text; var existingReview = reviewsText.Deserialize>()[0]; // Act - var result = await this.Client.CallToolAsync("UpdateReview", + var result = await this.Client.CallToolAsync("reviews_update", new Dictionary { - ["id"] = existingReview.Id, + ["reviewId"] = existingReview.Id, ["authorId"] = author.Id, ["movieId"] = movie.Id, ["stars"] = 5 @@ -150,8 +150,8 @@ public async Task UpdateReview_ShouldReturn_Success() // Assert text.ShouldBe("Review updated successfully"); - var validateResult = await this.Client.CallToolAsync("GetReviewById", - new Dictionary { ["id"] = existingReview.Id }); + var validateResult = await this.Client.CallToolAsync("reviews_get", + new Dictionary { ["reviewId"] = existingReview.Id }); var validateText = validateResult.Content.OfType().First().Text; var updatedReview = validateText.Deserialize(); @@ -174,20 +174,20 @@ public async Task UpdateReview_ShouldReturn_Success() public async Task DeleteReview_ShouldReturn_Success() { // Arrange - var reviewsResult = await this.Client.CallToolAsync("GetAllReviews"); + var reviewsResult = await this.Client.CallToolAsync("reviews_list"); var reviewsText = reviewsResult.Content.OfType().First().Text; var existingReview = reviewsText.Deserialize>()[0]; // Act - var result = await this.Client.CallToolAsync("DeleteReview", - new Dictionary { ["id"] = existingReview.Id }); + var result = await this.Client.CallToolAsync("reviews_delete", + new Dictionary { ["reviewId"] = existingReview.Id }); var text = result.Content.OfType().First().Text; // Assert text.ShouldBe("Review deleted successfully"); - var validateResult = await this.Client.CallToolAsync("GetReviewById", - new Dictionary { ["id"] = existingReview.Id }); + var validateResult = await this.Client.CallToolAsync("reviews_get", + new Dictionary { ["reviewId"] = existingReview.Id }); var validateText = validateResult.Content.OfType().First().Text; validateText.ShouldStartWith("Not Found:"); @@ -197,26 +197,26 @@ public async Task DeleteReview_ShouldReturn_Success() public async Task GetReviewById_WithEmptyId_ShouldReturn_ValidationError() { // Act - var result = await this.Client.CallToolAsync("GetReviewById", - new Dictionary { ["id"] = Guid.Empty }); + var result = await this.Client.CallToolAsync("reviews_get", + new Dictionary { ["reviewId"] = Guid.Empty }); var text = result.Content.OfType().First().Text; // Assert result.IsError.ShouldBe(true); - text.ShouldBe("Validation Failed: Id: A Review Id was not supplied."); + text.ShouldBe("Validation Failed: Id: A Review Id was not supplied. Correct the arguments and call the tool again."); } [Fact] public async Task GetReviewById_WithUnknownId_ShouldReturn_NotFoundError() { // Act - var result = await this.Client.CallToolAsync("GetReviewById", - new Dictionary { ["id"] = Guid.NewGuid() }); + var result = await this.Client.CallToolAsync("reviews_get", + new Dictionary { ["reviewId"] = Guid.NewGuid() }); var text = result.Content.OfType().First().Text; // Assert result.IsError.ShouldBe(true); - text.ShouldBe("Not Found: The Review with the supplied id was not found."); + 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."); } [Theory] @@ -227,8 +227,8 @@ public async Task GetReviewById_WithInvalidId_ShouldReturn_Error(string input) try { // Act - var result = await this.Client.CallToolAsync("GetReviewById", - new Dictionary { ["id"] = input }); + var result = await this.Client.CallToolAsync("reviews_get", + new Dictionary { ["reviewId"] = input }); // Assert result.IsError.ShouldBe(true); diff --git a/tests/Presentation.Tests.Integration/Tools/ToolListTests.cs b/tests/Presentation.Tests.Integration/Tools/ToolListTests.cs new file mode 100644 index 0000000..0849c36 --- /dev/null +++ b/tests/Presentation.Tests.Integration/Tools/ToolListTests.cs @@ -0,0 +1,71 @@ +namespace CleanModelContextProtocol.Presentation.Tests.Integration.Tools; + +using Shouldly; +using Xunit; + +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_get", "Get movie", 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_delete", "Delete review", false, true, true }, + { "server_get_version", "Get server version", true, false, true } + }; + + [Fact] + public async Task ListTools_ShouldReturn_EveryTool() + { + // Act + var tools = await this.Client.ListToolsAsync(); + + // Assert + tools.Select(t => t.Name).ShouldBe(Tools.Select(t => (string)t[0]), ignoreOrder: true); + } + + [Theory] + [MemberData(nameof(Tools))] + public async Task ListTools_ShouldDescribe_Tool(string name, string title, bool readOnly, bool destructive, bool idempotent) + { + // Act + var tool = (await this.Client.ListToolsAsync()).Single(t => t.Name == name).ProtocolTool; + + // Assert + tool.Title.ShouldBe(title); + tool.Description.ShouldNotBeNullOrWhiteSpace(); + + _ = tool.Annotations.ShouldNotBeNull(); + tool.Annotations.ReadOnlyHint.ShouldBe(readOnly); + tool.Annotations.OpenWorldHint.ShouldBe(false); + tool.Annotations.IdempotentHint.ShouldBe(idempotent); + + if (!readOnly) + { + tool.Annotations.DestructiveHint.ShouldBe(destructive); + } + + foreach (var property in tool.InputSchema.GetProperty("properties").EnumerateObject()) + { + property.Value.GetProperty("description").GetString().ShouldNotBeNullOrWhiteSpace(); + } + } + + [Fact] + public async Task ServerInfo_ShouldDescribe_Server() + { + // Assert + var serverInfo = this.Client.ServerInfo; + + serverInfo.Name.ShouldBe("clean-model-context-protocol"); + serverInfo.Title.ShouldBe("Clean Model Context Protocol"); + this.Client.ServerInstructions.ShouldNotBeNullOrWhiteSpace(); + + await Task.CompletedTask; + } +} diff --git a/tests/Presentation.Tests.Integration/Tools/VersionToolTests.cs b/tests/Presentation.Tests.Integration/Tools/VersionToolTests.cs index 32bd661..41b038d 100644 --- a/tests/Presentation.Tests.Integration/Tools/VersionToolTests.cs +++ b/tests/Presentation.Tests.Integration/Tools/VersionToolTests.cs @@ -10,7 +10,7 @@ public class VersionToolTests : BaseToolTests public async Task GetVersion_ShouldReturn_Version() { // Act - var result = await this.Client.CallToolAsync("GetVersion"); + var result = await this.Client.CallToolAsync("server_get_version"); var text = result.Content.OfType().First().Text; // Assert diff --git a/tests/Presentation.Tests.Unit/Errors/ToolErrorFilterTests.cs b/tests/Presentation.Tests.Unit/Errors/ToolErrorFilterTests.cs index b94e727..ed2c61f 100644 --- a/tests/Presentation.Tests.Unit/Errors/ToolErrorFilterTests.cs +++ b/tests/Presentation.Tests.Unit/Errors/ToolErrorFilterTests.cs @@ -54,7 +54,7 @@ public void ToResult_ShouldReturn_ValidationError() // Assert result.IsError.ShouldBe(true); result.Content.OfType().Single().Text - .ShouldBe("Validation Failed: AuthorId: An author id was not supplied to create the review. Stars: A star rating must be between 1 and 5."); + .ShouldBe("Validation Failed: AuthorId: An author id was not supplied to create the review. Stars: A star rating must be between 1 and 5. Correct the arguments and call the tool again."); } [Fact] @@ -68,6 +68,20 @@ public void ToResult_ShouldReturn_NotFoundError() 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); + } + [Fact] public void ToResult_ShouldReturn_Error() { diff --git a/tests/Presentation.Tests.Unit/Tools/AuthorToolTests.cs b/tests/Presentation.Tests.Unit/Tools/AuthorToolTests.cs index e98855a..197dbce 100644 --- a/tests/Presentation.Tests.Unit/Tools/AuthorToolTests.cs +++ b/tests/Presentation.Tests.Unit/Tools/AuthorToolTests.cs @@ -27,7 +27,7 @@ public async Task GetAllAuthors_ShouldReturn_JsonResult() ]); // Act - var response = await AuthorTools.GetAllAuthors(sender); + var response = await AuthorTools.ListAuthors(sender); // Assert var result = JsonSerializer.Deserialize>(response, JsonOptions); @@ -50,7 +50,7 @@ public async Task GetAuthorById_ShouldReturn_JsonResult() .ReturnsForAnyArgs(new Entities.Author(Guid.Empty, "Lorem", "Ipsum")); // Act - var response = await AuthorTools.GetAuthorById(sender, Guid.Empty); + var response = await AuthorTools.GetAuthor(sender, Guid.Empty); // Assert var result = JsonSerializer.Deserialize(response, JsonOptions); diff --git a/tests/Presentation.Tests.Unit/Tools/MovieToolTests.cs b/tests/Presentation.Tests.Unit/Tools/MovieToolTests.cs index a939450..bfd5e01 100644 --- a/tests/Presentation.Tests.Unit/Tools/MovieToolTests.cs +++ b/tests/Presentation.Tests.Unit/Tools/MovieToolTests.cs @@ -27,7 +27,7 @@ public async Task GetAllMovies_ShouldReturn_JsonResult() ]); // Act - var response = await MovieTools.GetAllMovies(sender); + var response = await MovieTools.ListMovies(sender); // Assert var result = JsonSerializer.Deserialize>(response, JsonOptions); @@ -49,7 +49,7 @@ public async Task GetMovieById_ShouldReturn_JsonResult() .ReturnsForAnyArgs(new Entities.Movie(Guid.Empty, "Lorem Ipsum")); // Act - var response = await MovieTools.GetMovieById(sender, Guid.Empty); + var response = await MovieTools.GetMovie(sender, Guid.Empty); // Assert var result = JsonSerializer.Deserialize(response, JsonOptions); diff --git a/tests/Presentation.Tests.Unit/Tools/ReviewToolTests.cs b/tests/Presentation.Tests.Unit/Tools/ReviewToolTests.cs index abb1aa7..f096ed8 100644 --- a/tests/Presentation.Tests.Unit/Tools/ReviewToolTests.cs +++ b/tests/Presentation.Tests.Unit/Tools/ReviewToolTests.cs @@ -36,7 +36,7 @@ public async Task GetAllReviews_ShouldReturn_JsonResult() .ReturnsForAnyArgs([SampleReview()]); // Act - var response = await ReviewTools.GetAllReviews(sender); + var response = await ReviewTools.ListReviews(sender); // Assert var result = JsonSerializer.Deserialize>(response, JsonOptions); @@ -62,7 +62,7 @@ public async Task GetReviewById_ShouldReturn_JsonResult() .ReturnsForAnyArgs(SampleReview()); // Act - var response = await ReviewTools.GetReviewById(sender, Guid.Empty); + var response = await ReviewTools.GetReview(sender, Guid.Empty); // Assert var result = JsonSerializer.Deserialize(response, JsonOptions); From b294ae31e1e4c91efa64bcc6b8f57170dc0a2e56 Mon Sep 17 00:00:00 2001 From: Stephen Walsh Date: Wed, 28 Oct 2026 15:41:46 +0000 Subject: [PATCH 3/9] feat: return typed, structured results from every MCP tool Tools now return Application entities instead of JSON strings, with UseStructuredContent so the SDK publishes an output schema and returns structuredContent alongside the JSON text. The tool serializer uses camelCase and the source-generated context, which was registered but never used. reviews_update returns the updated review, reviews_delete returns a small result object, and server_get_version returns an object instead of a markdown table. --- README.md | 1 + .../WebApplicationBuilderExtensions.cs | 17 +++---- src/Presentation/Models/DeletedReview.cs | 12 +++++ .../Serialization/AppJsonSerializerContext.cs | 2 + src/Presentation/Tools/AuthorTools.cs | 18 ++++---- src/Presentation/Tools/MovieTools.cs | 18 ++++---- src/Presentation/Tools/ReviewTools.cs | 46 +++++++++---------- src/Presentation/Tools/VersionTools.cs | 14 ++---- .../Tools/ReviewToolTests.cs | 17 ++++--- .../Tools/ToolListTests.cs | 2 + .../Tools/VersionToolTests.cs | 14 ++++-- .../Tools/AuthorToolTests.cs | 11 ++--- .../Tools/MovieToolTests.cs | 11 ++--- .../Tools/ReviewToolTests.cs | 29 ++++++------ .../Tools/VersionToolTests.cs | 6 +-- 15 files changed, 111 insertions(+), 107 deletions(-) create mode 100644 src/Presentation/Models/DeletedReview.cs diff --git a/README.md b/README.md index b522130..48cb600 100644 --- a/README.md +++ b/README.md @@ -84,6 +84,7 @@ The one deliberate break from Clean Architecture is that the Presentation projec - 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 - 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) diff --git a/src/Presentation/Extensions/WebApplicationBuilderExtensions.cs b/src/Presentation/Extensions/WebApplicationBuilderExtensions.cs index 3e4bf3d..5e3a61b 100644 --- a/src/Presentation/Extensions/WebApplicationBuilderExtensions.cs +++ b/src/Presentation/Extensions/WebApplicationBuilderExtensions.cs @@ -9,8 +9,8 @@ namespace CleanModelContextProtocol.Presentation.Extensions; using CleanModelContextProtocol.Presentation.Serialization; using Infrastructure; using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Http.Json; using Microsoft.Extensions.DependencyInjection; +using ModelContextProtocol; using Serilog; [ExcludeFromCodeCoverage] @@ -34,15 +34,12 @@ public static WebApplicationBuilder ConfigureApplicationBuilder(this WebApplicat #region Serialisation - _ = builder.Services.Configure(opt => + var serializerOptions = new JsonSerializerOptions(McpJsonUtilities.DefaultOptions) { - opt.SerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles; - opt.SerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull; - opt.SerializerOptions.PropertyNameCaseInsensitive = true; - opt.SerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase; - opt.SerializerOptions.Converters.Add(new JsonStringEnumConverter(JsonNamingPolicy.CamelCase)); - opt.SerializerOptions.TypeInfoResolverChain.Insert(0, AppJsonSerializerContext.Default); - }); + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull + }; + serializerOptions.TypeInfoResolverChain.Insert(0, AppJsonSerializerContext.Default); #endregion Serialisation @@ -85,7 +82,7 @@ A review links one author to one movie with a star rating from 1 (worst) to 5 (b """; }) .WithHttpTransport(options => options.Stateless = true) - .WithToolsFromAssembly() + .WithToolsFromAssembly(serializerOptions: serializerOptions) .WithRequestFilters(filters => filters.AddCallToolFilter(ToolErrorFilter.Filter)); #endregion Model Context Protocol diff --git a/src/Presentation/Models/DeletedReview.cs b/src/Presentation/Models/DeletedReview.cs new file mode 100644 index 0000000..4920453 --- /dev/null +++ b/src/Presentation/Models/DeletedReview.cs @@ -0,0 +1,12 @@ +namespace CleanModelContextProtocol.Presentation.Models; + +using System.ComponentModel; + +/// +/// The result of deleting a review. +/// +/// The id of the review that was deleted. +/// Whether the review was deleted. +public record DeletedReview( + [property: Description("The id of the review that was deleted.")] Guid ReviewId, + [property: Description("Whether the review was deleted.")] bool Deleted); diff --git a/src/Presentation/Serialization/AppJsonSerializerContext.cs b/src/Presentation/Serialization/AppJsonSerializerContext.cs index f7b82e0..449d5a0 100644 --- a/src/Presentation/Serialization/AppJsonSerializerContext.cs +++ b/src/Presentation/Serialization/AppJsonSerializerContext.cs @@ -5,6 +5,7 @@ namespace CleanModelContextProtocol.Presentation.Serialization; using Application.Movies.Entities; using Application.Reviews.Entities; using Application.Versions.Entities; +using CleanModelContextProtocol.Presentation.Models; /// /// JSON serialization context for compile-time source generation. @@ -26,6 +27,7 @@ namespace CleanModelContextProtocol.Presentation.Serialization; [JsonSerializable(typeof(ReviewedMovie))] [JsonSerializable(typeof(Version))] [JsonSerializable(typeof(List))] +[JsonSerializable(typeof(DeletedReview))] public partial class AppJsonSerializerContext : JsonSerializerContext { } diff --git a/src/Presentation/Tools/AuthorTools.cs b/src/Presentation/Tools/AuthorTools.cs index bbfa88e..85bfa04 100644 --- a/src/Presentation/Tools/AuthorTools.cs +++ b/src/Presentation/Tools/AuthorTools.cs @@ -1,33 +1,31 @@ namespace CleanModelContextProtocol.Presentation.Tools; using System.ComponentModel; -using System.Text.Json; 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)] + [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) + public static async Task> ListAuthors(ISender sender) { - var result = await sender.Send(new Queries.GetAuthors.GetAuthorsQuery()); - - return JsonSerializer.Serialize(result); + return await sender.Send(new Queries.GetAuthors.GetAuthorsQuery()); } - [McpServerTool(Name = "authors_get", Title = "Get author", ReadOnly = true, Idempotent = true, OpenWorld = false)] + [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( + public static async Task GetAuthor( ISender sender, [Description("The author's id (a GUID). Use authors_list to find it.")] Guid authorId) { - return JsonSerializer.Serialize(await sender.Send(new Queries.GetAuthorById.GetAuthorByIdQuery + return await sender.Send(new Queries.GetAuthorById.GetAuthorByIdQuery { Id = authorId - })); + }); } } diff --git a/src/Presentation/Tools/MovieTools.cs b/src/Presentation/Tools/MovieTools.cs index bc84866..096e62b 100644 --- a/src/Presentation/Tools/MovieTools.cs +++ b/src/Presentation/Tools/MovieTools.cs @@ -1,33 +1,31 @@ namespace CleanModelContextProtocol.Presentation.Tools; using System.ComponentModel; -using System.Text.Json; 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)] + [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) + public static async Task> ListMovies(ISender sender) { - var result = await sender.Send(new Queries.GetMovies.GetMoviesQuery()); - - return JsonSerializer.Serialize(result); + return await sender.Send(new Queries.GetMovies.GetMoviesQuery()); } - [McpServerTool(Name = "movies_get", Title = "Get movie", ReadOnly = true, Idempotent = true, OpenWorld = false)] + [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( + public static async Task GetMovie( ISender sender, [Description("The movie's id (a GUID). Use movies_list to find it.")] Guid movieId) { - return JsonSerializer.Serialize(await sender.Send(new Queries.GetMovieById.GetMovieByIdQuery + return await sender.Send(new Queries.GetMovieById.GetMovieByIdQuery { Id = movieId - })); + }); } } diff --git a/src/Presentation/Tools/ReviewTools.cs b/src/Presentation/Tools/ReviewTools.cs index d8d7bfc..86ac7a6 100644 --- a/src/Presentation/Tools/ReviewTools.cs +++ b/src/Presentation/Tools/ReviewTools.cs @@ -1,59 +1,56 @@ namespace CleanModelContextProtocol.Presentation.Tools; using System.ComponentModel; -using System.Text.Json; +using CleanModelContextProtocol.Presentation.Models; 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)] + [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) + public static async Task> ListReviews(ISender sender) { - var result = await sender.Send(new Queries.GetReviews.GetReviewsQuery()); - - return JsonSerializer.Serialize(result); + return await sender.Send(new Queries.GetReviews.GetReviewsQuery()); } - [McpServerTool(Name = "reviews_get", Title = "Get review", ReadOnly = true, Idempotent = true, OpenWorld = false)] + [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( + public static async Task GetReview( ISender sender, [Description("The review's id (a GUID). Use reviews_list to find it.")] Guid reviewId) { - return JsonSerializer.Serialize(await sender.Send(new Queries.GetReviewById.GetReviewByIdQuery + return await sender.Send(new Queries.GetReviewById.GetReviewByIdQuery { Id = reviewId - })); + }); } - [McpServerTool(Name = "reviews_create", Title = "Create review", ReadOnly = false, Destructive = false, Idempotent = false, OpenWorld = false)] + [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( + 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) { - var result = await sender.Send(new Commands.CreateReview.CreateReviewCommand + return await sender.Send(new Commands.CreateReview.CreateReviewCommand { AuthorId = authorId, MovieId = movieId, Stars = stars }); - - return JsonSerializer.Serialize(result); } - [McpServerTool(Name = "reviews_update", Title = "Update review", ReadOnly = false, Destructive = true, Idempotent = true, OpenWorld = false)] + [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.")] - public static async Task UpdateReview( + "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( 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, @@ -68,20 +65,23 @@ public static async Task UpdateReview( Stars = stars }); - return "Review updated successfully"; + return await sender.Send(new Queries.GetReviewById.GetReviewByIdQuery + { + Id = reviewId + }); } - [McpServerTool(Name = "reviews_delete", Title = "Delete review", ReadOnly = false, Destructive = true, Idempotent = true, OpenWorld = false)] + [McpServerTool(Name = "reviews_delete", Title = "Delete review", ReadOnly = false, Destructive = true, Idempotent = true, OpenWorld = false, UseStructuredContent = true)] [Description("Permanently delete a review. This can't be undone, so confirm with the user first.")] - public static async Task DeleteReview( + public static async Task DeleteReview( ISender sender, [Description("The id of the review to delete. Use reviews_list to find it.")] Guid reviewId) { - _ = await sender.Send(new Commands.DeleteReview.DeleteReviewCommand + var deleted = await sender.Send(new Commands.DeleteReview.DeleteReviewCommand { Id = reviewId }); - return "Review deleted successfully"; + return new DeletedReview(reviewId, deleted); } } diff --git a/src/Presentation/Tools/VersionTools.cs b/src/Presentation/Tools/VersionTools.cs index 53baf03..2020752 100644 --- a/src/Presentation/Tools/VersionTools.cs +++ b/src/Presentation/Tools/VersionTools.cs @@ -3,22 +3,16 @@ 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)] + [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) + public static async Task GetVersion(ISender sender) { - var result = await sender.Send(new Queries.GetVersion.GetVersionQuery()); - - return $""" - | Property | Value | - | --- | --- | - | File Version | {result.FileVersion} | - | Informational Version | {result.InformationalVersion} | - """; + return await sender.Send(new Queries.GetVersion.GetVersionQuery()); } } diff --git a/tests/Presentation.Tests.Integration/Tools/ReviewToolTests.cs b/tests/Presentation.Tests.Integration/Tools/ReviewToolTests.cs index c8b9541..860d818 100644 --- a/tests/Presentation.Tests.Integration/Tools/ReviewToolTests.cs +++ b/tests/Presentation.Tests.Integration/Tools/ReviewToolTests.cs @@ -1,5 +1,6 @@ namespace CleanModelContextProtocol.Presentation.Tests.Integration.Tools; +using CleanModelContextProtocol.Presentation.Models; using Extensions; using ModelContextProtocol; using ModelContextProtocol.Protocol; @@ -121,7 +122,7 @@ public async Task CreateReview_ShouldReturn_Review() } [Fact] - public async Task UpdateReview_ShouldReturn_Success() + public async Task UpdateReview_ShouldReturn_Review() { // Arrange var authorResult = await this.Client.CallToolAsync("authors_list"); @@ -148,12 +149,7 @@ public async Task UpdateReview_ShouldReturn_Success() var text = result.Content.OfType().First().Text; // Assert - text.ShouldBe("Review updated successfully"); - - var validateResult = await this.Client.CallToolAsync("reviews_get", - new Dictionary { ["reviewId"] = existingReview.Id }); - var validateText = validateResult.Content.OfType().First().Text; - var updatedReview = validateText.Deserialize(); + var updatedReview = text.Deserialize(); _ = updatedReview.ShouldNotBeNull(); @@ -171,7 +167,7 @@ public async Task UpdateReview_ShouldReturn_Success() } [Fact] - public async Task DeleteReview_ShouldReturn_Success() + public async Task DeleteReview_ShouldReturn_Result() { // Arrange var reviewsResult = await this.Client.CallToolAsync("reviews_list"); @@ -184,7 +180,10 @@ public async Task DeleteReview_ShouldReturn_Success() var text = result.Content.OfType().First().Text; // Assert - text.ShouldBe("Review deleted successfully"); + var deleted = text.Deserialize(); + + deleted.ReviewId.ShouldBe(existingReview.Id); + deleted.Deleted.ShouldBeTrue(); var validateResult = await this.Client.CallToolAsync("reviews_get", new Dictionary { ["reviewId"] = existingReview.Id }); diff --git a/tests/Presentation.Tests.Integration/Tools/ToolListTests.cs b/tests/Presentation.Tests.Integration/Tools/ToolListTests.cs index 0849c36..4a28f69 100644 --- a/tests/Presentation.Tests.Integration/Tools/ToolListTests.cs +++ b/tests/Presentation.Tests.Integration/Tools/ToolListTests.cs @@ -50,6 +50,8 @@ public async Task ListTools_ShouldDescribe_Tool(string name, string title, bool tool.Annotations.DestructiveHint.ShouldBe(destructive); } + _ = tool.OutputSchema.ShouldNotBeNull(); + foreach (var property in tool.InputSchema.GetProperty("properties").EnumerateObject()) { property.Value.GetProperty("description").GetString().ShouldNotBeNullOrWhiteSpace(); diff --git a/tests/Presentation.Tests.Integration/Tools/VersionToolTests.cs b/tests/Presentation.Tests.Integration/Tools/VersionToolTests.cs index 41b038d..db4e21a 100644 --- a/tests/Presentation.Tests.Integration/Tools/VersionToolTests.cs +++ b/tests/Presentation.Tests.Integration/Tools/VersionToolTests.cs @@ -1,5 +1,6 @@ namespace CleanModelContextProtocol.Presentation.Tests.Integration.Tools; +using Extensions; using ModelContextProtocol.Protocol; using Shouldly; using Xunit; @@ -13,12 +14,15 @@ public async Task GetVersion_ShouldReturn_Version() var result = await this.Client.CallToolAsync("server_get_version"); var text = result.Content.OfType().First().Text; + var version = text.Deserialize(); + // Assert - _ = text.ShouldNotBeNull(); - _ = text.ShouldBeOfType(); + _ = version.ShouldNotBeNull(); + + version.FileVersion.ShouldNotBeNullOrWhiteSpace(); + version.InformationalVersion.ShouldNotBeNullOrWhiteSpace(); - text.ShouldNotBeNullOrWhiteSpace(); - text.ShouldContain("File Version"); - text.ShouldContain("Informational Version"); + _ = result.StructuredContent.ShouldNotBeNull(); + result.StructuredContent.Value.GetProperty("fileVersion").GetString().ShouldBe(version.FileVersion); } } diff --git a/tests/Presentation.Tests.Unit/Tools/AuthorToolTests.cs b/tests/Presentation.Tests.Unit/Tools/AuthorToolTests.cs index 197dbce..1cd9184 100644 --- a/tests/Presentation.Tests.Unit/Tools/AuthorToolTests.cs +++ b/tests/Presentation.Tests.Unit/Tools/AuthorToolTests.cs @@ -1,6 +1,5 @@ namespace CleanModelContextProtocol.Presentation.Tests.Unit.Tools; -using System.Text.Json; using CleanModelContextProtocol.Presentation.Tools; using Mediator; using NSubstitute; @@ -11,10 +10,8 @@ namespace CleanModelContextProtocol.Presentation.Tests.Unit.Tools; public class AuthorToolTests { - private static readonly JsonSerializerOptions JsonOptions = new() { PropertyNameCaseInsensitive = true }; - [Fact] - public async Task GetAllAuthors_ShouldReturn_JsonResult() + public async Task GetAllAuthors_ShouldReturn_Result() { // Arrange var sender = Substitute.For(); @@ -30,7 +27,7 @@ public async Task GetAllAuthors_ShouldReturn_JsonResult() var response = await AuthorTools.ListAuthors(sender); // Assert - var result = JsonSerializer.Deserialize>(response, JsonOptions); + var result = response; result.ShouldNotBeNull(); result[0].Id.ShouldBe(Guid.Empty); @@ -40,7 +37,7 @@ public async Task GetAllAuthors_ShouldReturn_JsonResult() } [Fact] - public async Task GetAuthorById_ShouldReturn_JsonResult() + public async Task GetAuthorById_ShouldReturn_Result() { // Arrange var sender = Substitute.For(); @@ -53,7 +50,7 @@ public async Task GetAuthorById_ShouldReturn_JsonResult() var response = await AuthorTools.GetAuthor(sender, Guid.Empty); // Assert - var result = JsonSerializer.Deserialize(response, JsonOptions); + var result = response; result.ShouldNotBeNull(); result.Id.ShouldBe(Guid.Empty); diff --git a/tests/Presentation.Tests.Unit/Tools/MovieToolTests.cs b/tests/Presentation.Tests.Unit/Tools/MovieToolTests.cs index bfd5e01..68f07f1 100644 --- a/tests/Presentation.Tests.Unit/Tools/MovieToolTests.cs +++ b/tests/Presentation.Tests.Unit/Tools/MovieToolTests.cs @@ -1,6 +1,5 @@ namespace CleanModelContextProtocol.Presentation.Tests.Unit.Tools; -using System.Text.Json; using CleanModelContextProtocol.Presentation.Tools; using Mediator; using NSubstitute; @@ -11,10 +10,8 @@ namespace CleanModelContextProtocol.Presentation.Tests.Unit.Tools; public class MovieToolTests { - private static readonly JsonSerializerOptions JsonOptions = new() { PropertyNameCaseInsensitive = true }; - [Fact] - public async Task GetAllMovies_ShouldReturn_JsonResult() + public async Task GetAllMovies_ShouldReturn_Result() { // Arrange var sender = Substitute.For(); @@ -30,7 +27,7 @@ public async Task GetAllMovies_ShouldReturn_JsonResult() var response = await MovieTools.ListMovies(sender); // Assert - var result = JsonSerializer.Deserialize>(response, JsonOptions); + var result = response; result.ShouldNotBeNull(); result[0].Id.ShouldBe(Guid.Empty); @@ -39,7 +36,7 @@ public async Task GetAllMovies_ShouldReturn_JsonResult() } [Fact] - public async Task GetMovieById_ShouldReturn_JsonResult() + public async Task GetMovieById_ShouldReturn_Result() { // Arrange var sender = Substitute.For(); @@ -52,7 +49,7 @@ public async Task GetMovieById_ShouldReturn_JsonResult() var response = await MovieTools.GetMovie(sender, Guid.Empty); // Assert - var result = JsonSerializer.Deserialize(response, JsonOptions); + var result = response; result.ShouldNotBeNull(); result.Id.ShouldBe(Guid.Empty); diff --git a/tests/Presentation.Tests.Unit/Tools/ReviewToolTests.cs b/tests/Presentation.Tests.Unit/Tools/ReviewToolTests.cs index f096ed8..d011719 100644 --- a/tests/Presentation.Tests.Unit/Tools/ReviewToolTests.cs +++ b/tests/Presentation.Tests.Unit/Tools/ReviewToolTests.cs @@ -1,6 +1,5 @@ namespace CleanModelContextProtocol.Presentation.Tests.Unit.Tools; -using System.Text.Json; using Application.Authors.Entities; using Application.Movies.Entities; using CleanModelContextProtocol.Presentation.Tools; @@ -14,8 +13,6 @@ namespace CleanModelContextProtocol.Presentation.Tests.Unit.Tools; public class ReviewToolTests { - private static readonly JsonSerializerOptions JsonOptions = new() { PropertyNameCaseInsensitive = true }; - private static Entities.Review SampleReview() { return new( @@ -26,7 +23,7 @@ private static Entities.Review SampleReview() } [Fact] - public async Task GetAllReviews_ShouldReturn_JsonResult() + public async Task GetAllReviews_ShouldReturn_Result() { // Arrange var sender = Substitute.For(); @@ -39,7 +36,7 @@ public async Task GetAllReviews_ShouldReturn_JsonResult() var response = await ReviewTools.ListReviews(sender); // Assert - var result = JsonSerializer.Deserialize>(response, JsonOptions); + var result = response; result.ShouldNotBeNull(); result[0].Id.ShouldBe(Guid.Empty); @@ -52,7 +49,7 @@ public async Task GetAllReviews_ShouldReturn_JsonResult() } [Fact] - public async Task GetReviewById_ShouldReturn_JsonResult() + public async Task GetReviewById_ShouldReturn_Result() { // Arrange var sender = Substitute.For(); @@ -65,7 +62,7 @@ public async Task GetReviewById_ShouldReturn_JsonResult() var response = await ReviewTools.GetReview(sender, Guid.Empty); // Assert - var result = JsonSerializer.Deserialize(response, JsonOptions); + var result = response; result.ShouldNotBeNull(); result.Id.ShouldBe(Guid.Empty); @@ -78,7 +75,7 @@ public async Task GetReviewById_ShouldReturn_JsonResult() } [Fact] - public async Task CreateReview_ShouldReturn_JsonResult() + public async Task CreateReview_ShouldReturn_Result() { // Arrange var sender = Substitute.For(); @@ -91,7 +88,7 @@ public async Task CreateReview_ShouldReturn_JsonResult() var response = await ReviewTools.CreateReview(sender, Guid.Empty, Guid.Empty, 5); // Assert - var result = JsonSerializer.Deserialize(response, JsonOptions); + var result = response; result.ShouldNotBeNull(); result.Id.ShouldBe(Guid.Empty); @@ -104,7 +101,7 @@ public async Task CreateReview_ShouldReturn_JsonResult() } [Fact] - public async Task UpdateReview_ShouldReturn_Success() + public async Task UpdateReview_ShouldReturn_Review() { // Arrange var sender = Substitute.For(); @@ -113,15 +110,20 @@ public async Task UpdateReview_ShouldReturn_Success() .Send(Arg.Any()) .ReturnsForAnyArgs(true); + _ = sender + .Send(Arg.Any()) + .ReturnsForAnyArgs(SampleReview()); + // Act var response = await ReviewTools.UpdateReview(sender, Guid.Empty, Guid.Empty, Guid.Empty, 5); // Assert - response.ShouldBe("Review updated successfully"); + response.Id.ShouldBe(Guid.Empty); + response.Stars.ShouldBe(5); } [Fact] - public async Task DeleteReview_ShouldReturn_Success() + public async Task DeleteReview_ShouldReturn_Result() { // Arrange var sender = Substitute.For(); @@ -134,6 +136,7 @@ public async Task DeleteReview_ShouldReturn_Success() var response = await ReviewTools.DeleteReview(sender, Guid.Empty); // Assert - response.ShouldBe("Review deleted successfully"); + response.ReviewId.ShouldBe(Guid.Empty); + response.Deleted.ShouldBeTrue(); } } diff --git a/tests/Presentation.Tests.Unit/Tools/VersionToolTests.cs b/tests/Presentation.Tests.Unit/Tools/VersionToolTests.cs index 19693de..8c759cc 100644 --- a/tests/Presentation.Tests.Unit/Tools/VersionToolTests.cs +++ b/tests/Presentation.Tests.Unit/Tools/VersionToolTests.cs @@ -11,7 +11,7 @@ namespace CleanModelContextProtocol.Presentation.Tests.Unit.Tools; public class VersionToolTests { [Fact] - public async Task GetVersion_ShouldReturn_MarkdownTable() + public async Task GetVersion_ShouldReturn_Version() { // Arrange var sender = Substitute.For(); @@ -28,7 +28,7 @@ public async Task GetVersion_ShouldReturn_MarkdownTable() var response = await VersionTools.GetVersion(sender); // Assert - response.ShouldContain("| File Version | 1.2.3.4 |"); - response.ShouldContain("| Informational Version | 5.6.7.8 |"); + response.FileVersion.ShouldBe("1.2.3.4"); + response.InformationalVersion.ShouldBe("5.6.7.8"); } } From 9a0cf6953229765bb94b489b824d02ae2b73beba Mon Sep 17 00:00:00 2001 From: Stephen Walsh Date: Wed, 28 Oct 2026 15:45:50 +0000 Subject: [PATCH 4/9] feat: add search and paging queries to the Application layer SearchMovies, SearchAuthors and SearchReviews return one page of results with a total count and an opaque cursor for the next page. Movies and authors match a case-insensitive search term, and reviews filter by movie and author. Limits run from 1 to 50 with a default of 10, and invalid cursors fail validation with a message that explains how to get a valid one. --- src/Application/Authors/IAuthorsRepository.cs | 6 + .../SearchAuthors/SearchAuthorsHandler.cs | 19 +++ .../SearchAuthors/SearchAuthorsQuery.cs | 20 +++ .../SearchAuthors/SearchAuthorsValidator.cs | 14 ++ src/Application/Common/Paging/Page.cs | 10 ++ src/Application/Common/Paging/Paging.cs | 65 +++++++++ .../Paging/PagingValidatorExtensions.cs | 37 +++++ src/Application/Movies/IMoviesRepository.cs | 6 + .../SearchMovies/SearchMoviesHandler.cs | 19 +++ .../Queries/SearchMovies/SearchMoviesQuery.cs | 20 +++ .../SearchMovies/SearchMoviesValidator.cs | 14 ++ src/Application/Reviews/IReviewsRepository.cs | 7 + .../SearchReviews/SearchReviewsHandler.cs | 19 +++ .../SearchReviews/SearchReviewsQuery.cs | 23 ++++ .../SearchReviews/SearchReviewsValidator.cs | 15 ++ .../EntityFrameworkMovieReviewsRepository.cs | 93 +++++++++++++ .../SearchAuthorsHandlerTests.cs | 63 +++++++++ .../SearchAuthorsValidatorTests.cs | 66 +++++++++ .../Common/Paging/PagingTests.cs | 73 ++++++++++ .../SearchMovies/SearchMoviesHandlerTests.cs | 63 +++++++++ .../SearchMoviesValidatorTests.cs | 66 +++++++++ .../SearchReviewsHandlerTests.cs | 45 ++++++ .../SearchReviewsValidatorTests.cs | 90 ++++++++++++ ...ityFrameworkMovieReviewsRepositoryTests.cs | 130 ++++++++++++++++++ 24 files changed, 983 insertions(+) create mode 100644 src/Application/Authors/Queries/SearchAuthors/SearchAuthorsHandler.cs create mode 100644 src/Application/Authors/Queries/SearchAuthors/SearchAuthorsQuery.cs create mode 100644 src/Application/Authors/Queries/SearchAuthors/SearchAuthorsValidator.cs create mode 100644 src/Application/Common/Paging/Page.cs create mode 100644 src/Application/Common/Paging/Paging.cs create mode 100644 src/Application/Common/Paging/PagingValidatorExtensions.cs create mode 100644 src/Application/Movies/Queries/SearchMovies/SearchMoviesHandler.cs create mode 100644 src/Application/Movies/Queries/SearchMovies/SearchMoviesQuery.cs create mode 100644 src/Application/Movies/Queries/SearchMovies/SearchMoviesValidator.cs create mode 100644 src/Application/Reviews/Queries/SearchReviews/SearchReviewsHandler.cs create mode 100644 src/Application/Reviews/Queries/SearchReviews/SearchReviewsQuery.cs create mode 100644 src/Application/Reviews/Queries/SearchReviews/SearchReviewsValidator.cs create mode 100644 tests/Application.Tests.Unit/Authors/Queries/SearchAuthors/SearchAuthorsHandlerTests.cs create mode 100644 tests/Application.Tests.Unit/Authors/Queries/SearchAuthors/SearchAuthorsValidatorTests.cs create mode 100644 tests/Application.Tests.Unit/Common/Paging/PagingTests.cs create mode 100644 tests/Application.Tests.Unit/Movies/Queries/SearchMovies/SearchMoviesHandlerTests.cs create mode 100644 tests/Application.Tests.Unit/Movies/Queries/SearchMovies/SearchMoviesValidatorTests.cs create mode 100644 tests/Application.Tests.Unit/Reviews/Queries/SearchReviews/SearchReviewsHandlerTests.cs create mode 100644 tests/Application.Tests.Unit/Reviews/Queries/SearchReviews/SearchReviewsValidatorTests.cs diff --git a/src/Application/Authors/IAuthorsRepository.cs b/src/Application/Authors/IAuthorsRepository.cs index 062919f..b1ae1e7 100644 --- a/src/Application/Authors/IAuthorsRepository.cs +++ b/src/Application/Authors/IAuthorsRepository.cs @@ -10,4 +10,10 @@ public interface IAuthorsRepository public Task GetAuthorById(Guid id, CancellationToken cancellationToken); public Task AuthorExists(Guid id, CancellationToken cancellationToken); + + public Task<(List Items, int TotalCount)> SearchAuthors( + string query, + int offset, + int limit, + CancellationToken cancellationToken); } diff --git a/src/Application/Authors/Queries/SearchAuthors/SearchAuthorsHandler.cs b/src/Application/Authors/Queries/SearchAuthors/SearchAuthorsHandler.cs new file mode 100644 index 0000000..8af794c --- /dev/null +++ b/src/Application/Authors/Queries/SearchAuthors/SearchAuthorsHandler.cs @@ -0,0 +1,19 @@ +namespace CleanModelContextProtocol.Application.Authors.Queries.SearchAuthors; + +using System.Threading; +using System.Threading.Tasks; +using Common.Paging; +using Entities; +using Mediator; + +public class SearchAuthorsHandler(IAuthorsRepository repository) : IRequestHandler> +{ + public async ValueTask> Handle(SearchAuthorsQuery request, CancellationToken cancellationToken) + { + _ = Paging.TryDecode(request.Cursor, out var offset); + + var (items, totalCount) = await repository.SearchAuthors(request.Query, offset, request.Limit, cancellationToken); + + return Paging.ToPage(items, totalCount, offset); + } +} diff --git a/src/Application/Authors/Queries/SearchAuthors/SearchAuthorsQuery.cs b/src/Application/Authors/Queries/SearchAuthors/SearchAuthorsQuery.cs new file mode 100644 index 0000000..a3c12f7 --- /dev/null +++ b/src/Application/Authors/Queries/SearchAuthors/SearchAuthorsQuery.cs @@ -0,0 +1,20 @@ +namespace CleanModelContextProtocol.Application.Authors.Queries.SearchAuthors; + +using Common.Paging; +using Entities; +using Mediator; + +/// +/// Finds authors whose the first or last name contains a search term, one page at a time. +/// +public class SearchAuthorsQuery : IRequest> +{ + /// The words to look for, ignoring case. Leave empty to list every one. + public string Query { get; init; } + + /// The largest number of results to return, from 1 to 50. + public int Limit { get; init; } = Paging.DefaultLimit; + + /// The cursor from a previous page, or empty for the first page. + public string Cursor { get; init; } +} diff --git a/src/Application/Authors/Queries/SearchAuthors/SearchAuthorsValidator.cs b/src/Application/Authors/Queries/SearchAuthors/SearchAuthorsValidator.cs new file mode 100644 index 0000000..0d258c2 --- /dev/null +++ b/src/Application/Authors/Queries/SearchAuthors/SearchAuthorsValidator.cs @@ -0,0 +1,14 @@ +namespace CleanModelContextProtocol.Application.Authors.Queries.SearchAuthors; + +using Common.Paging; +using FluentValidation; + +public class SearchAuthorsValidator : AbstractValidator +{ + public SearchAuthorsValidator() + { + _ = this.RuleFor(r => r.Query).ValidSearchTerm(); + _ = this.RuleFor(r => r.Limit).ValidLimit(); + _ = this.RuleFor(r => r.Cursor).ValidCursor(); + } +} diff --git a/src/Application/Common/Paging/Page.cs b/src/Application/Common/Paging/Page.cs new file mode 100644 index 0000000..776cc83 --- /dev/null +++ b/src/Application/Common/Paging/Page.cs @@ -0,0 +1,10 @@ +namespace CleanModelContextProtocol.Application.Common.Paging; + +/// +/// One page of results from a search. +/// +/// The type of the results. +/// The results on this page. +/// The number of results across every page. +/// The cursor that fetches the next page, or null when this is the last page. +public record Page(List Items, int TotalCount, string NextCursor = null); diff --git a/src/Application/Common/Paging/Paging.cs b/src/Application/Common/Paging/Paging.cs new file mode 100644 index 0000000..440b9e2 --- /dev/null +++ b/src/Application/Common/Paging/Paging.cs @@ -0,0 +1,65 @@ +namespace CleanModelContextProtocol.Application.Common.Paging; + +using System.Globalization; +using System.Text; + +/// +/// Limits and opaque cursors shared by every search. +/// +public static class Paging +{ + /// The number of results returned when no limit is supplied. + public const int DefaultLimit = 10; + + /// The largest number of results a single page can return. + public const int MaxLimit = 50; + + private const string Prefix = "offset:"; + + /// Creates the cursor for the page that starts at . + /// The number of results to skip. + /// An opaque cursor. + public static string Encode(int offset) + { + return Convert.ToBase64String(Encoding.UTF8.GetBytes(Prefix + offset.ToString(CultureInfo.InvariantCulture))); + } + + /// Reads the offset from a cursor. An empty cursor is the first page. + /// The cursor from a previous page, or null for the first page. + /// The number of results to skip. + /// True when the cursor is empty or valid. + public static bool TryDecode(string cursor, out int offset) + { + offset = 0; + + if (string.IsNullOrEmpty(cursor)) + { + return true; + } + + try + { + var value = Encoding.UTF8.GetString(Convert.FromBase64String(cursor)); + + return value.StartsWith(Prefix, StringComparison.Ordinal) + && int.TryParse(value.AsSpan(Prefix.Length), NumberStyles.None, CultureInfo.InvariantCulture, out offset); + } + catch (FormatException) + { + return false; + } + } + + /// Creates the page for a set of results, with a cursor when more results remain. + /// The type of the results. + /// The results on this page. + /// The number of results across every page. + /// The number of results skipped before this page. + /// The page. + public static Page ToPage(List items, int totalCount, int offset) + { + var next = offset + items.Count; + + return new Page(items, totalCount, next < totalCount ? Encode(next) : null); + } +} diff --git a/src/Application/Common/Paging/PagingValidatorExtensions.cs b/src/Application/Common/Paging/PagingValidatorExtensions.cs new file mode 100644 index 0000000..940bb27 --- /dev/null +++ b/src/Application/Common/Paging/PagingValidatorExtensions.cs @@ -0,0 +1,37 @@ +namespace CleanModelContextProtocol.Application.Common.Paging; + +using FluentValidation; + +/// +/// Validation rules shared by every search. +/// +public static class PagingValidatorExtensions +{ + /// Checks that a limit is between 1 and . + /// The type being validated. + /// The rule for the limit. + /// The rule. + public static IRuleBuilderOptions ValidLimit(this IRuleBuilder rule) + { + return rule.InclusiveBetween(1, Paging.MaxLimit).WithMessage($"A limit must be between 1 and {Paging.MaxLimit}."); + } + + /// Checks that a cursor is empty or came from a previous page. + /// The type being validated. + /// The rule for the cursor. + /// The rule. + public static IRuleBuilderOptions ValidCursor(this IRuleBuilder rule) + { + return rule.Must(cursor => Paging.TryDecode(cursor, out _)) + .WithMessage("The cursor is not valid. Use the nextCursor from a previous page, or leave it empty for the first page."); + } + + /// Checks that a search term is no longer than 100 characters. + /// The type being validated. + /// The rule for the search term. + /// The rule. + public static IRuleBuilderOptions ValidSearchTerm(this IRuleBuilder rule) + { + return rule.MaximumLength(100).WithMessage("A search term can't be longer than 100 characters."); + } +} diff --git a/src/Application/Movies/IMoviesRepository.cs b/src/Application/Movies/IMoviesRepository.cs index 4c0c790..eb55f94 100644 --- a/src/Application/Movies/IMoviesRepository.cs +++ b/src/Application/Movies/IMoviesRepository.cs @@ -10,4 +10,10 @@ public interface IMoviesRepository public Task GetMovieById(Guid id, CancellationToken cancellationToken); public Task MovieExists(Guid id, CancellationToken cancellationToken); + + public Task<(List Items, int TotalCount)> SearchMovies( + string query, + int offset, + int limit, + CancellationToken cancellationToken); } diff --git a/src/Application/Movies/Queries/SearchMovies/SearchMoviesHandler.cs b/src/Application/Movies/Queries/SearchMovies/SearchMoviesHandler.cs new file mode 100644 index 0000000..2486af7 --- /dev/null +++ b/src/Application/Movies/Queries/SearchMovies/SearchMoviesHandler.cs @@ -0,0 +1,19 @@ +namespace CleanModelContextProtocol.Application.Movies.Queries.SearchMovies; + +using System.Threading; +using System.Threading.Tasks; +using Common.Paging; +using Entities; +using Mediator; + +public class SearchMoviesHandler(IMoviesRepository repository) : IRequestHandler> +{ + public async ValueTask> Handle(SearchMoviesQuery request, CancellationToken cancellationToken) + { + _ = Paging.TryDecode(request.Cursor, out var offset); + + var (items, totalCount) = await repository.SearchMovies(request.Query, offset, request.Limit, cancellationToken); + + return Paging.ToPage(items, totalCount, offset); + } +} diff --git a/src/Application/Movies/Queries/SearchMovies/SearchMoviesQuery.cs b/src/Application/Movies/Queries/SearchMovies/SearchMoviesQuery.cs new file mode 100644 index 0000000..39be8fa --- /dev/null +++ b/src/Application/Movies/Queries/SearchMovies/SearchMoviesQuery.cs @@ -0,0 +1,20 @@ +namespace CleanModelContextProtocol.Application.Movies.Queries.SearchMovies; + +using Common.Paging; +using Entities; +using Mediator; + +/// +/// Finds movies whose the title contains a search term, one page at a time. +/// +public class SearchMoviesQuery : IRequest> +{ + /// The words to look for, ignoring case. Leave empty to list every one. + public string Query { get; init; } + + /// The largest number of results to return, from 1 to 50. + public int Limit { get; init; } = Paging.DefaultLimit; + + /// The cursor from a previous page, or empty for the first page. + public string Cursor { get; init; } +} diff --git a/src/Application/Movies/Queries/SearchMovies/SearchMoviesValidator.cs b/src/Application/Movies/Queries/SearchMovies/SearchMoviesValidator.cs new file mode 100644 index 0000000..d45bca5 --- /dev/null +++ b/src/Application/Movies/Queries/SearchMovies/SearchMoviesValidator.cs @@ -0,0 +1,14 @@ +namespace CleanModelContextProtocol.Application.Movies.Queries.SearchMovies; + +using Common.Paging; +using FluentValidation; + +public class SearchMoviesValidator : AbstractValidator +{ + public SearchMoviesValidator() + { + _ = this.RuleFor(r => r.Query).ValidSearchTerm(); + _ = this.RuleFor(r => r.Limit).ValidLimit(); + _ = this.RuleFor(r => r.Cursor).ValidCursor(); + } +} diff --git a/src/Application/Reviews/IReviewsRepository.cs b/src/Application/Reviews/IReviewsRepository.cs index aa9efd2..1e59e60 100644 --- a/src/Application/Reviews/IReviewsRepository.cs +++ b/src/Application/Reviews/IReviewsRepository.cs @@ -19,6 +19,13 @@ public Task CreateReview( public Task ReviewExists(Guid id, CancellationToken cancellationToken); + public Task<(List Items, int TotalCount)> SearchReviews( + Guid? movieId, + Guid? authorId, + int offset, + int limit, + CancellationToken cancellationToken); + public Task UpdateReview( Guid id, Guid authorId, diff --git a/src/Application/Reviews/Queries/SearchReviews/SearchReviewsHandler.cs b/src/Application/Reviews/Queries/SearchReviews/SearchReviewsHandler.cs new file mode 100644 index 0000000..df733e3 --- /dev/null +++ b/src/Application/Reviews/Queries/SearchReviews/SearchReviewsHandler.cs @@ -0,0 +1,19 @@ +namespace CleanModelContextProtocol.Application.Reviews.Queries.SearchReviews; + +using System.Threading; +using System.Threading.Tasks; +using Common.Paging; +using Entities; +using Mediator; + +public class SearchReviewsHandler(IReviewsRepository repository) : IRequestHandler> +{ + public async ValueTask> Handle(SearchReviewsQuery request, CancellationToken cancellationToken) + { + _ = Paging.TryDecode(request.Cursor, out var offset); + + var (items, totalCount) = await repository.SearchReviews(request.MovieId, request.AuthorId, offset, request.Limit, cancellationToken); + + return Paging.ToPage(items, totalCount, offset); + } +} diff --git a/src/Application/Reviews/Queries/SearchReviews/SearchReviewsQuery.cs b/src/Application/Reviews/Queries/SearchReviews/SearchReviewsQuery.cs new file mode 100644 index 0000000..2080520 --- /dev/null +++ b/src/Application/Reviews/Queries/SearchReviews/SearchReviewsQuery.cs @@ -0,0 +1,23 @@ +namespace CleanModelContextProtocol.Application.Reviews.Queries.SearchReviews; + +using Common.Paging; +using Entities; +using Mediator; + +/// +/// Finds reviews, optionally only those for one movie or by one author, one page at a time. +/// +public class SearchReviewsQuery : IRequest> +{ + /// Only return reviews of this movie. Leave empty for every movie. + public Guid? MovieId { get; init; } + + /// Only return reviews by this author. Leave empty for every author. + public Guid? AuthorId { get; init; } + + /// The largest number of results to return, from 1 to 50. + public int Limit { get; init; } = Paging.DefaultLimit; + + /// The cursor from a previous page, or empty for the first page. + public string Cursor { get; init; } +} diff --git a/src/Application/Reviews/Queries/SearchReviews/SearchReviewsValidator.cs b/src/Application/Reviews/Queries/SearchReviews/SearchReviewsValidator.cs new file mode 100644 index 0000000..f37375b --- /dev/null +++ b/src/Application/Reviews/Queries/SearchReviews/SearchReviewsValidator.cs @@ -0,0 +1,15 @@ +namespace CleanModelContextProtocol.Application.Reviews.Queries.SearchReviews; + +using Common.Paging; +using FluentValidation; + +public class SearchReviewsValidator : AbstractValidator +{ + public SearchReviewsValidator() + { + _ = this.RuleFor(r => r.MovieId).NotEqual(Guid.Empty).WithMessage("A Movie Id can't be empty. Leave it out to search every movie."); + _ = this.RuleFor(r => r.AuthorId).NotEqual(Guid.Empty).WithMessage("An Author Id can't be empty. Leave it out to search every author."); + _ = this.RuleFor(r => r.Limit).ValidLimit(); + _ = this.RuleFor(r => r.Cursor).ValidCursor(); + } +} diff --git a/src/Infrastructure/Databases/MovieReviews/EntityFrameworkMovieReviewsRepository.cs b/src/Infrastructure/Databases/MovieReviews/EntityFrameworkMovieReviewsRepository.cs index fb7b4f8..4c5fec8 100644 --- a/src/Infrastructure/Databases/MovieReviews/EntityFrameworkMovieReviewsRepository.cs +++ b/src/Infrastructure/Databases/MovieReviews/EntityFrameworkMovieReviewsRepository.cs @@ -67,6 +67,36 @@ public virtual async Task AuthorExists(Guid id, CancellationToken cancella return await this.context.Authors.AsNoTracking().AnyAsync(a => a.Id == id, cancellationToken); } + public virtual async Task<(List Items, int TotalCount)> SearchAuthors( + string query, + int offset, + int limit, + CancellationToken cancellationToken) + { + var authors = this.context.Authors.AsNoTracking(); + + if (!string.IsNullOrWhiteSpace(query)) + { + var term = query.Trim(); + + authors = authors.Where(a => (a.FirstName + " " + a.LastName).Contains(term, StringComparison.OrdinalIgnoreCase)); + } + + var totalCount = await authors.CountAsync(cancellationToken); + + var result = await authors + .OrderBy(a => a.LastName) + .ThenBy(a => a.FirstName) + .ThenBy(a => a.Id) + .Skip(offset) + .Take(limit) + .Include(a => a.Reviews) + .ThenInclude(r => r.ReviewedMovie) + .ToListAsync(cancellationToken); + + return ([.. result.Select(this.mapper.ToDomain)], totalCount); + } + #endregion Authors #region Movies @@ -99,6 +129,35 @@ public virtual async Task MovieExists(Guid id, CancellationToken cancellat return await this.context.Movies.AsNoTracking().AnyAsync(m => m.Id == id, cancellationToken); } + public virtual async Task<(List Items, int TotalCount)> SearchMovies( + string query, + int offset, + int limit, + CancellationToken cancellationToken) + { + var movies = this.context.Movies.AsNoTracking(); + + if (!string.IsNullOrWhiteSpace(query)) + { + var term = query.Trim(); + + movies = movies.Where(m => m.Title.Contains(term, StringComparison.OrdinalIgnoreCase)); + } + + var totalCount = await movies.CountAsync(cancellationToken); + + var result = await movies + .OrderBy(m => m.Title) + .ThenBy(m => m.Id) + .Skip(offset) + .Take(limit) + .Include(m => m.Reviews) + .ThenInclude(r => r.ReviewAuthor) + .ToListAsync(cancellationToken); + + return ([.. result.Select(this.mapper.ToDomain)], totalCount); + } + #endregion Movies #region Reviews @@ -175,6 +234,40 @@ public async Task ReviewExists(Guid id, CancellationToken cancellationToke return await this.context.Reviews.AnyAsync(r => r.Id == id, cancellationToken); } + public async Task<(List Items, int TotalCount)> SearchReviews( + Guid? movieId, + Guid? authorId, + int offset, + int limit, + CancellationToken cancellationToken) + { + var reviews = this.context.Reviews.AsNoTracking(); + + if (movieId.HasValue) + { + reviews = reviews.Where(r => r.ReviewedMovieId == movieId.Value); + } + + if (authorId.HasValue) + { + reviews = reviews.Where(r => r.ReviewAuthorId == authorId.Value); + } + + var totalCount = await reviews.CountAsync(cancellationToken); + + var result = await reviews + .Include(r => r.ReviewAuthor) + .Include(r => r.ReviewedMovie) + .OrderBy(r => r.ReviewedMovie.Title) + .ThenBy(r => r.ReviewAuthor.LastName) + .ThenBy(r => r.Id) + .Skip(offset) + .Take(limit) + .ToListAsync(cancellationToken); + + return ([.. result.Select(this.mapper.ToDomain)], totalCount); + } + public async Task UpdateReview( Guid id, Guid authorId, diff --git a/tests/Application.Tests.Unit/Authors/Queries/SearchAuthors/SearchAuthorsHandlerTests.cs b/tests/Application.Tests.Unit/Authors/Queries/SearchAuthors/SearchAuthorsHandlerTests.cs new file mode 100644 index 0000000..fef0143 --- /dev/null +++ b/tests/Application.Tests.Unit/Authors/Queries/SearchAuthors/SearchAuthorsHandlerTests.cs @@ -0,0 +1,63 @@ +namespace CleanModelContextProtocol.Application.Tests.Unit.Authors.Queries.SearchAuthors; + +using System.Threading; +using System.Threading.Tasks; +using Application.Authors; +using Application.Authors.Entities; +using Application.Authors.Queries.SearchAuthors; +using Application.Common.Paging; +using NSubstitute; +using Shouldly; +using Xunit; + +public class SearchAuthorsHandlerTests +{ + [Fact] + public async Task Handle_ShouldPassThrough_Query() + { + // Arrange + var query = new SearchAuthorsQuery { Query = "Lorem", Limit = 1, Cursor = Paging.Encode(2) }; + + var repository = Substitute.For(); + var handler = new SearchAuthorsHandler(repository); + using var tokenSource = new CancellationTokenSource(); + var token = tokenSource.Token; + + _ = repository.SearchAuthors("Lorem", 2, 1, token).Returns(([new Author(Guid.Empty, "First", "Last")], 5)); + + // Act + var result = await handler.Handle(query, token); + + // Assert + _ = await repository.Received(1).SearchAuthors("Lorem", 2, 1, token); + + _ = result.ShouldNotBeNull(); + result.Items.Count.ShouldBe(1); + result.Items[0].FirstName.ShouldBe("First"); + result.TotalCount.ShouldBe(5); + result.NextCursor.ShouldBe(Paging.Encode(3)); + } + + [Fact] + public async Task Handle_ShouldStartAt_FirstPage() + { + // Arrange + var query = new SearchAuthorsQuery(); + + var repository = Substitute.For(); + var handler = new SearchAuthorsHandler(repository); + using var tokenSource = new CancellationTokenSource(); + var token = tokenSource.Token; + + _ = repository.SearchAuthors(null, 0, Paging.DefaultLimit, token).Returns(([new Author(Guid.Empty, "First", "Last")], 1)); + + // Act + var result = await handler.Handle(query, token); + + // Assert + _ = await repository.Received(1).SearchAuthors(null, 0, Paging.DefaultLimit, token); + + result.TotalCount.ShouldBe(1); + result.NextCursor.ShouldBeNull(); + } +} diff --git a/tests/Application.Tests.Unit/Authors/Queries/SearchAuthors/SearchAuthorsValidatorTests.cs b/tests/Application.Tests.Unit/Authors/Queries/SearchAuthors/SearchAuthorsValidatorTests.cs new file mode 100644 index 0000000..af9375d --- /dev/null +++ b/tests/Application.Tests.Unit/Authors/Queries/SearchAuthors/SearchAuthorsValidatorTests.cs @@ -0,0 +1,66 @@ +namespace CleanModelContextProtocol.Application.Tests.Unit.Authors.Queries.SearchAuthors; + +using Application.Authors.Queries.SearchAuthors; +using FluentValidation.TestHelper; +using Xunit; + +public class SearchAuthorsValidatorTests +{ + private static readonly SearchAuthorsValidator Validator = new(); + + [Theory] + [InlineData(0)] + [InlineData(51)] + public void Validator_ShouldHaveValidationErrorFor_Limit(int limit) + { + // Arrange + var query = new SearchAuthorsQuery { Limit = limit }; + + // Act + var result = Validator.TestValidate(query); + + // Assert + _ = result.ShouldHaveValidationErrorFor(query => query.Limit); + } + + [Fact] + public void Validator_ShouldHaveValidationErrorFor_Cursor() + { + // Arrange + var query = new SearchAuthorsQuery { Cursor = "not a cursor" }; + + // Act + var result = Validator.TestValidate(query); + + // Assert + _ = result.ShouldHaveValidationErrorFor(query => query.Cursor); + } + + [Fact] + public void Validator_ShouldHaveValidationErrorFor_Query() + { + // Arrange + var query = new SearchAuthorsQuery { Query = new string('a', 101) }; + + // Act + var result = Validator.TestValidate(query); + + // Assert + _ = result.ShouldHaveValidationErrorFor(query => query.Query); + } + + [Theory] + [InlineData(null, 1, null)] + [InlineData("Lorem", 50, "b2Zmc2V0OjEw")] + public void Validator_ShouldNotHaveValidationErrors(string search, int limit, string cursor) + { + // Arrange + var query = new SearchAuthorsQuery { Query = search, Limit = limit, Cursor = cursor }; + + // Act + var result = Validator.TestValidate(query); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/Application.Tests.Unit/Common/Paging/PagingTests.cs b/tests/Application.Tests.Unit/Common/Paging/PagingTests.cs new file mode 100644 index 0000000..3876ab9 --- /dev/null +++ b/tests/Application.Tests.Unit/Common/Paging/PagingTests.cs @@ -0,0 +1,73 @@ +namespace CleanModelContextProtocol.Application.Tests.Unit.Common.Paging; + +using Application.Common.Paging; +using Shouldly; +using Xunit; + +public class PagingTests +{ + [Theory] + [InlineData(0)] + [InlineData(10)] + [InlineData(12345)] + public void Encode_ShouldRoundTrip_Offset(int offset) + { + // Act + var cursor = Paging.Encode(offset); + var result = Paging.TryDecode(cursor, out var decoded); + + // Assert + result.ShouldBeTrue(); + decoded.ShouldBe(offset); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + public void TryDecode_ShouldReturn_FirstPage(string cursor) + { + // Act + var result = Paging.TryDecode(cursor, out var offset); + + // Assert + result.ShouldBeTrue(); + offset.ShouldBe(0); + } + + [Theory] + [InlineData("not a cursor")] + [InlineData("b2Zmc2V0Og==")] + [InlineData("b2Zmc2V0Oi0x")] + [InlineData("cGFnZToy")] + public void TryDecode_ShouldReturn_False(string cursor) + { + // Act + var result = Paging.TryDecode(cursor, out _); + + // Assert + result.ShouldBeFalse(); + } + + [Fact] + public void ToPage_ShouldReturn_NextCursor() + { + // Act + var result = Paging.ToPage([1, 2], 5, 2); + + // Assert + result.Items.ShouldBe([1, 2]); + result.TotalCount.ShouldBe(5); + _ = Paging.TryDecode(result.NextCursor, out var next); + next.ShouldBe(4); + } + + [Fact] + public void ToPage_ShouldReturn_NoCursorOnLastPage() + { + // Act + var result = Paging.ToPage([5], 5, 4); + + // Assert + result.NextCursor.ShouldBeNull(); + } +} diff --git a/tests/Application.Tests.Unit/Movies/Queries/SearchMovies/SearchMoviesHandlerTests.cs b/tests/Application.Tests.Unit/Movies/Queries/SearchMovies/SearchMoviesHandlerTests.cs new file mode 100644 index 0000000..e412875 --- /dev/null +++ b/tests/Application.Tests.Unit/Movies/Queries/SearchMovies/SearchMoviesHandlerTests.cs @@ -0,0 +1,63 @@ +namespace CleanModelContextProtocol.Application.Tests.Unit.Movies.Queries.SearchMovies; + +using System.Threading; +using System.Threading.Tasks; +using Application.Movies; +using Application.Movies.Entities; +using Application.Movies.Queries.SearchMovies; +using Application.Common.Paging; +using NSubstitute; +using Shouldly; +using Xunit; + +public class SearchMoviesHandlerTests +{ + [Fact] + public async Task Handle_ShouldPassThrough_Query() + { + // Arrange + var query = new SearchMoviesQuery { Query = "Lorem", Limit = 1, Cursor = Paging.Encode(2) }; + + var repository = Substitute.For(); + var handler = new SearchMoviesHandler(repository); + using var tokenSource = new CancellationTokenSource(); + var token = tokenSource.Token; + + _ = repository.SearchMovies("Lorem", 2, 1, token).Returns(([new Movie(Guid.Empty, "Title")], 5)); + + // Act + var result = await handler.Handle(query, token); + + // Assert + _ = await repository.Received(1).SearchMovies("Lorem", 2, 1, token); + + _ = result.ShouldNotBeNull(); + result.Items.Count.ShouldBe(1); + result.Items[0].Title.ShouldBe("Title"); + result.TotalCount.ShouldBe(5); + result.NextCursor.ShouldBe(Paging.Encode(3)); + } + + [Fact] + public async Task Handle_ShouldStartAt_FirstPage() + { + // Arrange + var query = new SearchMoviesQuery(); + + var repository = Substitute.For(); + var handler = new SearchMoviesHandler(repository); + using var tokenSource = new CancellationTokenSource(); + var token = tokenSource.Token; + + _ = repository.SearchMovies(null, 0, Paging.DefaultLimit, token).Returns(([new Movie(Guid.Empty, "Title")], 1)); + + // Act + var result = await handler.Handle(query, token); + + // Assert + _ = await repository.Received(1).SearchMovies(null, 0, Paging.DefaultLimit, token); + + result.TotalCount.ShouldBe(1); + result.NextCursor.ShouldBeNull(); + } +} diff --git a/tests/Application.Tests.Unit/Movies/Queries/SearchMovies/SearchMoviesValidatorTests.cs b/tests/Application.Tests.Unit/Movies/Queries/SearchMovies/SearchMoviesValidatorTests.cs new file mode 100644 index 0000000..15bebdb --- /dev/null +++ b/tests/Application.Tests.Unit/Movies/Queries/SearchMovies/SearchMoviesValidatorTests.cs @@ -0,0 +1,66 @@ +namespace CleanModelContextProtocol.Application.Tests.Unit.Movies.Queries.SearchMovies; + +using Application.Movies.Queries.SearchMovies; +using FluentValidation.TestHelper; +using Xunit; + +public class SearchMoviesValidatorTests +{ + private static readonly SearchMoviesValidator Validator = new(); + + [Theory] + [InlineData(0)] + [InlineData(51)] + public void Validator_ShouldHaveValidationErrorFor_Limit(int limit) + { + // Arrange + var query = new SearchMoviesQuery { Limit = limit }; + + // Act + var result = Validator.TestValidate(query); + + // Assert + _ = result.ShouldHaveValidationErrorFor(query => query.Limit); + } + + [Fact] + public void Validator_ShouldHaveValidationErrorFor_Cursor() + { + // Arrange + var query = new SearchMoviesQuery { Cursor = "not a cursor" }; + + // Act + var result = Validator.TestValidate(query); + + // Assert + _ = result.ShouldHaveValidationErrorFor(query => query.Cursor); + } + + [Fact] + public void Validator_ShouldHaveValidationErrorFor_Query() + { + // Arrange + var query = new SearchMoviesQuery { Query = new string('a', 101) }; + + // Act + var result = Validator.TestValidate(query); + + // Assert + _ = result.ShouldHaveValidationErrorFor(query => query.Query); + } + + [Theory] + [InlineData(null, 1, null)] + [InlineData("Lorem", 50, "b2Zmc2V0OjEw")] + public void Validator_ShouldNotHaveValidationErrors(string search, int limit, string cursor) + { + // Arrange + var query = new SearchMoviesQuery { Query = search, Limit = limit, Cursor = cursor }; + + // Act + var result = Validator.TestValidate(query); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/Application.Tests.Unit/Reviews/Queries/SearchReviews/SearchReviewsHandlerTests.cs b/tests/Application.Tests.Unit/Reviews/Queries/SearchReviews/SearchReviewsHandlerTests.cs new file mode 100644 index 0000000..ed0d137 --- /dev/null +++ b/tests/Application.Tests.Unit/Reviews/Queries/SearchReviews/SearchReviewsHandlerTests.cs @@ -0,0 +1,45 @@ +namespace CleanModelContextProtocol.Application.Tests.Unit.Reviews.Queries.SearchReviews; + +using System.Threading; +using System.Threading.Tasks; +using Application.Authors.Entities; +using Application.Common.Paging; +using Application.Movies.Entities; +using Application.Reviews; +using Application.Reviews.Entities; +using Application.Reviews.Queries.SearchReviews; +using NSubstitute; +using Shouldly; +using Xunit; + +public class SearchReviewsHandlerTests +{ + [Fact] + public async Task Handle_ShouldPassThrough_Query() + { + // Arrange + var movieId = Guid.NewGuid(); + var authorId = Guid.NewGuid(); + var query = new SearchReviewsQuery { MovieId = movieId, AuthorId = authorId, Limit = 1, Cursor = Paging.Encode(1) }; + + var repository = Substitute.For(); + var handler = new SearchReviewsHandler(repository); + using var tokenSource = new CancellationTokenSource(); + var token = tokenSource.Token; + + _ = repository.SearchReviews(movieId, authorId, 1, 1, token) + .Returns(([new Review(Guid.Empty, 5, new ReviewedMovie(movieId, "Title"), new ReviewAuthor(authorId, "First", "Last"))], 2)); + + // Act + var result = await handler.Handle(query, token); + + // Assert + _ = await repository.Received(1).SearchReviews(movieId, authorId, 1, 1, token); + + _ = result.ShouldNotBeNull(); + result.Items.Count.ShouldBe(1); + result.Items[0].Stars.ShouldBe(5); + result.TotalCount.ShouldBe(2); + result.NextCursor.ShouldBeNull(); + } +} diff --git a/tests/Application.Tests.Unit/Reviews/Queries/SearchReviews/SearchReviewsValidatorTests.cs b/tests/Application.Tests.Unit/Reviews/Queries/SearchReviews/SearchReviewsValidatorTests.cs new file mode 100644 index 0000000..a4bc567 --- /dev/null +++ b/tests/Application.Tests.Unit/Reviews/Queries/SearchReviews/SearchReviewsValidatorTests.cs @@ -0,0 +1,90 @@ +namespace CleanModelContextProtocol.Application.Tests.Unit.Reviews.Queries.SearchReviews; + +using Application.Reviews.Queries.SearchReviews; +using FluentValidation.TestHelper; +using Xunit; + +public class SearchReviewsValidatorTests +{ + private static readonly SearchReviewsValidator Validator = new(); + + [Fact] + public void Validator_ShouldHaveValidationErrorFor_MovieIdEmpty() + { + // Arrange + var query = new SearchReviewsQuery { MovieId = Guid.Empty }; + + // Act + var result = Validator.TestValidate(query); + + // Assert + _ = result.ShouldHaveValidationErrorFor(query => query.MovieId); + } + + [Fact] + public void Validator_ShouldHaveValidationErrorFor_AuthorIdEmpty() + { + // Arrange + var query = new SearchReviewsQuery { AuthorId = Guid.Empty }; + + // Act + var result = Validator.TestValidate(query); + + // Assert + _ = result.ShouldHaveValidationErrorFor(query => query.AuthorId); + } + + [Theory] + [InlineData(0)] + [InlineData(51)] + public void Validator_ShouldHaveValidationErrorFor_Limit(int limit) + { + // Arrange + var query = new SearchReviewsQuery { Limit = limit }; + + // Act + var result = Validator.TestValidate(query); + + // Assert + _ = result.ShouldHaveValidationErrorFor(query => query.Limit); + } + + [Fact] + public void Validator_ShouldHaveValidationErrorFor_Cursor() + { + // Arrange + var query = new SearchReviewsQuery { Cursor = "not a cursor" }; + + // Act + var result = Validator.TestValidate(query); + + // Assert + _ = result.ShouldHaveValidationErrorFor(query => query.Cursor); + } + + [Fact] + public void Validator_ShouldNotHaveValidationErrors() + { + // Arrange + var query = new SearchReviewsQuery { MovieId = Guid.NewGuid(), AuthorId = Guid.NewGuid(), Limit = 50 }; + + // Act + var result = Validator.TestValidate(query); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } + + [Fact] + public void Validator_ShouldNotHaveValidationErrors_WithoutFilters() + { + // Arrange + var query = new SearchReviewsQuery(); + + // Act + var result = Validator.TestValidate(query); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/Infrastructure.Tests.Integration/Databases/MovieReviews/EntityFrameworkMovieReviewsRepositoryTests.cs b/tests/Infrastructure.Tests.Integration/Databases/MovieReviews/EntityFrameworkMovieReviewsRepositoryTests.cs index fa20c1a..bd2230d 100644 --- a/tests/Infrastructure.Tests.Integration/Databases/MovieReviews/EntityFrameworkMovieReviewsRepositoryTests.cs +++ b/tests/Infrastructure.Tests.Integration/Databases/MovieReviews/EntityFrameworkMovieReviewsRepositoryTests.cs @@ -95,6 +95,44 @@ public async Task AuthorExists_ShouldReturn_False() result.ShouldBeFalse(); } + [Theory] + [InlineData(null, 3)] + [InlineData("one", 1)] + [InlineData("TWO TWO", 1)] + [InlineData("missing", 0)] + public async Task SearchAuthors_ShouldReturn_Matches(string query, int expected) + { + // Arrange + var repository = fixture.Repository; + using var tokenSource = new CancellationTokenSource(); + var token = tokenSource.Token; + + // Act + var (items, totalCount) = await repository.SearchAuthors(query, 0, 10, token); + + // Assert + items.Count.ShouldBe(expected); + totalCount.ShouldBe(expected); + items.ShouldAllBe(a => a.Reviews != null); + } + + [Fact] + public async Task SearchAuthors_ShouldReturn_Page() + { + // Arrange + var repository = fixture.Repository; + using var tokenSource = new CancellationTokenSource(); + var token = tokenSource.Token; + + // Act + var (items, totalCount) = await repository.SearchAuthors(null, 1, 1, token); + + // Assert + items.Count.ShouldBe(1); + items[0].LastName.ShouldBe("Three"); + totalCount.ShouldBe(3); + } + #endregion Authors #region Movies @@ -182,6 +220,46 @@ public async Task MovieExists_ShouldReturn_False() result.ShouldBeFalse(); } + [Theory] + [InlineData(null, 3)] + [InlineData("t", 2)] + [InlineData("ONE", 1)] + [InlineData("missing", 0)] + public async Task SearchMovies_ShouldReturn_Matches(string query, int expected) + { + // Arrange + var repository = fixture.Repository; + using var tokenSource = new CancellationTokenSource(); + var token = tokenSource.Token; + + // Act + var (items, totalCount) = await repository.SearchMovies(query, 0, 10, token); + + // Assert + items.Count.ShouldBe(expected); + totalCount.ShouldBe(expected); + items.ShouldAllBe(m => m.Reviews != null); + } + + [Fact] + public async Task SearchMovies_ShouldReturn_PagesInTitleOrder() + { + // Arrange + var repository = fixture.Repository; + using var tokenSource = new CancellationTokenSource(); + var token = tokenSource.Token; + + // Act + var (first, firstTotal) = await repository.SearchMovies(null, 0, 2, token); + var (second, secondTotal) = await repository.SearchMovies(null, 2, 2, token); + + // Assert + first.Select(m => m.Title).ShouldBe(["One", "Three"]); + second.Select(m => m.Title).ShouldBe(["Two"]); + firstTotal.ShouldBe(3); + secondTotal.ShouldBe(3); + } + #endregion Movies #region Reviews @@ -385,5 +463,57 @@ public async Task UpdateReview_ShouldReturn_False() result.ShouldBeFalse(); } + [Fact] + public async Task SearchReviews_ShouldReturn_ReviewsForMovie() + { + // Arrange + var repository = fixture.Repository; + using var tokenSource = new CancellationTokenSource(); + var token = tokenSource.Token; + var movieId = fixture.Context.Movies.First(m => m.Title == "Two").Id; + + // Act + var (items, totalCount) = await repository.SearchReviews(movieId, null, 0, 50, token); + + // Assert + items.ShouldNotBeEmpty(); + items.Count.ShouldBe(totalCount); + items.ShouldAllBe(r => r.ReviewedMovie.Id == movieId && r.ReviewedMovie.Title == "Two"); + items.ShouldAllBe(r => r.ReviewAuthor != null); + } + + [Fact] + public async Task SearchReviews_ShouldReturn_ReviewsForAuthorAndMovie() + { + // Arrange + var repository = fixture.Repository; + using var tokenSource = new CancellationTokenSource(); + var token = tokenSource.Token; + var movieId = fixture.Context.Movies.First(m => m.Title == "Three").Id; + var authorId = fixture.Context.Authors.First(a => a.FirstName == "Two").Id; + + // Act + var (items, _) = await repository.SearchReviews(movieId, authorId, 0, 50, token); + + // Assert + items.ShouldAllBe(r => r.ReviewedMovie.Id == movieId && r.ReviewAuthor.Id == authorId); + } + + [Fact] + public async Task SearchReviews_ShouldReturn_Page() + { + // Arrange + var repository = fixture.Repository; + using var tokenSource = new CancellationTokenSource(); + var token = tokenSource.Token; + + // Act + var (items, totalCount) = await repository.SearchReviews(null, null, 0, 2, token); + + // Assert + items.Count.ShouldBe(2); + totalCount.ShouldBeGreaterThan(2); + } + #endregion Reviews } From 7f0dff5b418fb4134d2808ff63d6b476c3f5da26 Mon Sep 17 00:00:00 2001 From: Stephen Walsh Date: Wed, 28 Oct 2026 15:53:10 +0000 Subject: [PATCH 5/9] feat: reshape the MCP tools around what agents need to do Replace the ten CRUD tools with six: movies_search, movies_get, authors_search, reviews_list, reviews_write and reviews_delete. Searches page through results ten at a time with a total count and a cursor, return review counts and average stars instead of every nested review unless asked, and put movie titles and author names next to their ids. reviews_write creates a review, or replaces one when given its id, and reviews_list can fetch a single review by id. --- README.md | 3 +- src/Presentation/Errors/ToolErrorFilter.cs | 15 +- .../WebApplicationBuilderExtensions.cs | 7 +- src/Presentation/Models/AuthorResult.cs | 18 ++ src/Presentation/Models/MovieResult.cs | 18 ++ src/Presentation/Models/ResultMapper.cs | 65 +++++ src/Presentation/Models/ResultPage.cs | 15 + src/Presentation/Models/ReviewResult.cs | 20 ++ .../Serialization/AppJsonSerializerContext.cs | 6 + src/Presentation/Tools/AuthorTools.cs | 31 +- src/Presentation/Tools/MovieTools.cs | 35 ++- src/Presentation/Tools/ReviewTools.cs | 86 +++--- .../Tools/AuthorToolTests.cs | 115 ++------ .../Tools/BaseToolTests.cs | 20 ++ .../Tools/MovieToolTests.cs | 155 ++++++---- .../Tools/ReviewToolTests.cs | 265 +++++++----------- .../Tools/ToolListTests.cs | 9 +- .../Errors/ToolErrorFilterTests.cs | 18 +- .../Tools/AuthorToolTests.cs | 47 ++-- .../Tools/MovieToolTests.cs | 79 ++++-- .../Tools/ReviewToolTests.cs | 107 ++++--- 21 files changed, 613 insertions(+), 521 deletions(-) create mode 100644 src/Presentation/Models/AuthorResult.cs create mode 100644 src/Presentation/Models/MovieResult.cs create mode 100644 src/Presentation/Models/ResultMapper.cs create mode 100644 src/Presentation/Models/ResultPage.cs create mode 100644 src/Presentation/Models/ReviewResult.cs diff --git a/README.md b/README.md index 48cb600..9fe3bb7 100644 --- a/README.md +++ b/README.md @@ -80,7 +80,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 16516cf..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,13 +42,4 @@ public static CallToolResult ToResult(Exception exception, string toolName = nul Content = [new TextContentBlock { Text = message }] }; } - - private static string ListToolHint(string toolName) - { - var separator = toolName?.IndexOf('_') ?? -1; - - 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 bcebd96..5544ad7 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 CleanModelContextProtocolApplication(); diff --git a/tests/Presentation.Tests.Integration/Tools/MovieToolTests.cs b/tests/Presentation.Tests.Integration/Tools/MovieToolTests.cs index d45bae6..47bb951 100644 --- a/tests/Presentation.Tests.Integration/Tools/MovieToolTests.cs +++ b/tests/Presentation.Tests.Integration/Tools/MovieToolTests.cs @@ -1,116 +1,153 @@ 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(); + movie.AverageStars.Value.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(); } } From 8c13519789cc4c10ac4261e52884a545854e2b2f Mon Sep 17 00:00:00 2001 From: Stephen Walsh Date: Wed, 28 Oct 2026 15:56:14 +0000 Subject: [PATCH 6/9] fix: pattern-match the optional review filters --- .../MovieReviews/EntityFrameworkMovieReviewsRepository.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/Infrastructure/Databases/MovieReviews/EntityFrameworkMovieReviewsRepository.cs b/src/Infrastructure/Databases/MovieReviews/EntityFrameworkMovieReviewsRepository.cs index 4c5fec8..8dc950b 100644 --- a/src/Infrastructure/Databases/MovieReviews/EntityFrameworkMovieReviewsRepository.cs +++ b/src/Infrastructure/Databases/MovieReviews/EntityFrameworkMovieReviewsRepository.cs @@ -243,14 +243,14 @@ public async Task ReviewExists(Guid id, CancellationToken cancellationToke { var reviews = this.context.Reviews.AsNoTracking(); - if (movieId.HasValue) + if (movieId is Guid reviewedMovieId) { - reviews = reviews.Where(r => r.ReviewedMovieId == movieId.Value); + reviews = reviews.Where(r => r.ReviewedMovieId == reviewedMovieId); } - if (authorId.HasValue) + if (authorId is Guid reviewAuthorId) { - reviews = reviews.Where(r => r.ReviewAuthorId == authorId.Value); + reviews = reviews.Where(r => r.ReviewAuthorId == reviewAuthorId); } var totalCount = await reviews.CountAsync(cancellationToken); From caa42fa99f8809b25e1fba5dddaece845144d82a Mon Sep 17 00:00:00 2001 From: Stephen Walsh Date: Wed, 28 Oct 2026 15:56:49 +0000 Subject: [PATCH 7/9] fix: guard the tool name before building the not-found hint --- src/Presentation/Errors/ToolErrorFilter.cs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/Presentation/Errors/ToolErrorFilter.cs b/src/Presentation/Errors/ToolErrorFilter.cs index 16516cf..de302f8 100644 --- a/src/Presentation/Errors/ToolErrorFilter.cs +++ b/src/Presentation/Errors/ToolErrorFilter.cs @@ -45,7 +45,12 @@ public static CallToolResult ToResult(Exception exception, string toolName = nul private static string ListToolHint(string toolName) { - var separator = toolName?.IndexOf('_') ?? -1; + 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." From 7703bb5db8fb1fe0ef147f7ecfbe105dcb8913db Mon Sep 17 00:00:00 2001 From: Stephen Walsh Date: Wed, 28 Oct 2026 16:02:09 +0000 Subject: [PATCH 8/9] feat: add resources, prompts and completions to the MCP server --- README.md | 4 +- .../Completions/CompletionHandler.cs | 78 +++++++++++ .../Errors/ProtocolErrorFilter.cs | 45 ++++++ .../WebApplicationBuilderExtensions.cs | 29 ++-- src/Presentation/Prompts/MoviePrompts.cs | 130 ++++++++++++++++++ src/Presentation/Resources/AuthorResources.cs | 26 ++++ src/Presentation/Resources/MovieResources.cs | 26 ++++ src/Presentation/Resources/ReviewResources.cs | 26 ++++ .../Resources/VersionResources.cs | 18 +++ .../Serialization/McpSerializer.cs | 31 +++++ src/Presentation/Tools/VersionTools.cs | 18 --- .../Completions/CompletionTests.cs | 74 ++++++++++ .../Prompts/PromptTests.cs | 123 +++++++++++++++++ .../Resources/ResourceTests.cs | 123 +++++++++++++++++ .../Tools/ToolListTests.cs | 1 - .../Tools/VersionToolTests.cs | 28 ---- .../Errors/ProtocolErrorFilterTests.cs | 66 +++++++++ .../Tools/VersionToolTests.cs | 34 ----- 18 files changed, 782 insertions(+), 98 deletions(-) create mode 100644 src/Presentation/Completions/CompletionHandler.cs create mode 100644 src/Presentation/Errors/ProtocolErrorFilter.cs create mode 100644 src/Presentation/Prompts/MoviePrompts.cs create mode 100644 src/Presentation/Resources/AuthorResources.cs create mode 100644 src/Presentation/Resources/MovieResources.cs create mode 100644 src/Presentation/Resources/ReviewResources.cs create mode 100644 src/Presentation/Resources/VersionResources.cs create mode 100644 src/Presentation/Serialization/McpSerializer.cs delete mode 100644 src/Presentation/Tools/VersionTools.cs create mode 100644 tests/Presentation.Tests.Integration/Completions/CompletionTests.cs create mode 100644 tests/Presentation.Tests.Integration/Prompts/PromptTests.cs create mode 100644 tests/Presentation.Tests.Integration/Resources/ResourceTests.cs delete mode 100644 tests/Presentation.Tests.Integration/Tools/VersionToolTests.cs create mode 100644 tests/Presentation.Tests.Unit/Errors/ProtocolErrorFilterTests.cs delete mode 100644 tests/Presentation.Tests.Unit/Tools/VersionToolTests.cs diff --git a/README.md b/README.md index 9fe3bb7..71469ba 100644 --- a/README.md +++ b/README.md @@ -81,12 +81,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"); - } -} From 01330ee3c4bcc37cf2fc77bc14c5c240eba83369 Mon Sep 17 00:00:00 2001 From: Stephen Walsh Date: Wed, 28 Oct 2026 16:07:17 +0000 Subject: [PATCH 9/9] test: assert the average stars without dereferencing the nullable --- tests/Presentation.Tests.Integration/Tools/MovieToolTests.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/tests/Presentation.Tests.Integration/Tools/MovieToolTests.cs b/tests/Presentation.Tests.Integration/Tools/MovieToolTests.cs index 47bb951..6ee1f8f 100644 --- a/tests/Presentation.Tests.Integration/Tools/MovieToolTests.cs +++ b/tests/Presentation.Tests.Integration/Tools/MovieToolTests.cs @@ -27,8 +27,7 @@ public async Task SearchMovies_ShouldReturn_FirstPage() if (movie.ReviewCount > 0) { - _ = movie.AverageStars.ShouldNotBeNull(); - movie.AverageStars.Value.ShouldBeInRange(1, 5); + movie.AverageStars.ShouldNotBeNull().ShouldBeInRange(1, 5); } } }