From e8d6efac61b9a9ced5065e915f391c1622286ece Mon Sep 17 00:00:00 2001
From: Stephen Walsh <868017+stphnwlsh@users.noreply.github.com>
Date: Wed, 28 Oct 2026 23:43:29 +0000
Subject: [PATCH 1/7] feat: apply best-practices review
- Turn on nullable reference types and fix every warning
- Page the search and list tools with offset and limit, returning nextOffset instead of a cursor
- Pass the CancellationToken through every tool, resource and prompt
- Let reviews_write change only the stars of an existing review
- Store data in SQLite with EF Core migrations, seeded once at startup with a fixed seed
- Run tests against a throwaway in-memory SQLite database
- Register the DbContext and repositories as scoped, fixing concurrent request failures
- Only publish from stphnwlsh/CleanModelContextProtocol
- Remove committed coverage reports
---
.github/workflows/build-pipeline.yml | 2 +-
.gitignore | 6 +
Directory.Build.props | 1 +
Dockerfile | 2 +-
README.md | 4 +-
docs/RUN.md | 13 ++
src/Application/Authors/Entities/Author.cs | 2 +-
src/Application/Authors/IAuthorsRepository.cs | 15 +-
.../Queries/GetAuthors/GetAuthorsHandler.cs | 11 +-
.../Queries/GetAuthors/GetAuthorsQuery.cs | 14 +-
.../GetAuthorsValidator.cs} | 8 +-
.../SearchAuthors/SearchAuthorsHandler.cs | 19 --
.../SearchAuthors/SearchAuthorsQuery.cs | 20 --
.../Common/Exceptions/NotFoundException.cs | 4 +-
src/Application/Common/Paging/Page.cs | 7 +-
src/Application/Common/Paging/Paging.cs | 54 +----
.../Paging/PagingValidatorExtensions.cs | 21 +-
src/Application/Movies/Entities/Movie.cs | 2 +-
src/Application/Movies/IMoviesRepository.cs | 15 +-
.../Queries/GetMovies/GetMoviesHandler.cs | 11 +-
.../Queries/GetMovies/GetMoviesQuery.cs | 14 +-
.../Queries/GetMovies/GetMoviesValidator.cs | 14 ++
.../SearchMovies/SearchMoviesHandler.cs | 19 --
.../Queries/SearchMovies/SearchMoviesQuery.cs | 20 --
.../SearchMovies/SearchMoviesValidator.cs | 14 --
.../UpdateReview/UpdateReviewCommand.cs | 11 +-
.../UpdateReview/UpdateReviewHandler.cs | 22 +-
.../UpdateReview/UpdateReviewValidator.cs | 2 -
src/Application/Reviews/Entities/Review.cs | 4 +-
src/Application/Reviews/IReviewsRepository.cs | 20 +-
.../Queries/GetReviews/GetReviewsHandler.cs | 11 +-
.../Queries/GetReviews/GetReviewsQuery.cs | 17 +-
.../Queries/GetReviews/GetReviewsValidator.cs | 15 ++
.../SearchReviews/SearchReviewsHandler.cs | 19 --
.../SearchReviews/SearchReviewsQuery.cs | 23 --
.../SearchReviews/SearchReviewsValidator.cs | 15 --
src/Application/Versions/Entities/Version.cs | 4 +-
.../Configuration/EntityConfiguration.cs | 4 +-
.../EntityFrameworkMovieReviewsRepository.cs | 216 ++++++++----------
.../MovieReviewsDbContextExtensions.cs | 30 ++-
.../Mapping/MovieReviewsMapper.cs | 4 +
.../20261028000000_InitialCreate.Designer.cs | 130 +++++++++++
.../20261028000000_InitialCreate.cs | 96 ++++++++
.../MovieReviewsDbContextModelSnapshot.cs | 127 ++++++++++
.../Databases/MovieReviews/Models/Author.cs | 6 +-
.../Databases/MovieReviews/Models/Movie.cs | 4 +-
.../Databases/MovieReviews/Models/Review.cs | 4 +-
.../MovieReviews/MovieReviewsDatabase.cs | 34 +++
.../MovieReviews/MovieReviewsDbContext.cs | 6 +-
.../MovieReviewsDbContextFactory.cs | 22 ++
src/Infrastructure/DependencyInjection.cs | 38 ++-
src/Infrastructure/Infrastructure.csproj | 6 +-
.../Authentication/AuthenticationSettings.cs | 4 +-
.../Completions/CompletionHandler.cs | 8 +-
.../Errors/ProtocolErrorFilter.cs | 2 +-
.../WebApplicationBuilderExtensions.cs | 4 +-
.../Extensions/WebApplicationExtensions.cs | 7 +
src/Presentation/Models/AuthorResult.cs | 2 +-
src/Presentation/Models/MovieResult.cs | 2 +-
src/Presentation/Models/ResultMapper.cs | 6 +-
src/Presentation/Models/ResultPage.cs | 6 +-
src/Presentation/Models/ReviewResult.cs | 4 +-
src/Presentation/Prompts/MoviePrompts.cs | 18 +-
src/Presentation/Resources/AuthorResources.cs | 5 +-
src/Presentation/Resources/MovieResources.cs | 5 +-
src/Presentation/Resources/ReviewResources.cs | 5 +-
.../Resources/VersionResources.cs | 4 +-
src/Presentation/Tools/AuthorTools.cs | 13 +-
src/Presentation/Tools/MovieTools.cs | 18 +-
src/Presentation/Tools/ReviewTools.cs | 45 ++--
src/Presentation/appsettings.json | 3 +
.../GetAuthors/GetAuthorsHandlerTests.cs | 46 +++-
.../GetAuthorsValidatorTests.cs} | 26 +--
.../SearchAuthorsHandlerTests.cs | 63 -----
.../Exceptions/NotFoundExceptionTests.cs | 2 +-
.../Common/Paging/PagingTests.cs | 73 ------
.../GetMovies/GetMoviesHandlerTests.cs | 45 +++-
.../GetMoviesValidatorTests.cs} | 26 +--
.../SearchMovies/SearchMoviesHandlerTests.cs | 63 -----
.../UpdateReview/UpdateReviewHandlerTests.cs | 109 +--------
.../UpdateReviewValidatorTests.cs | 118 +---------
.../GetReviews/GetReviewsHandlerTests.cs | 48 +++-
.../GetReviewsValidatorTests.cs} | 55 ++---
.../SearchReviewsHandlerTests.cs | 45 ----
...ityFrameworkMovieReviewsRepositoryTests.cs | 129 ++++-------
.../MovieReviewsCollectionFixture.cs | 22 +-
.../MovieReviewsConfigurationTests.cs | 6 +-
.../MovieReviews/MovieReviewsDatabaseTests.cs | 50 ++++
.../DependencyInjectionTests.cs | 124 ++++++++++
.../Authentication/AuthenticationTests.cs | 8 +-
.../Extensions/JsonSerializerExtensions.cs | 2 +-
.../ModelContextProtocolApplication.cs | 16 +-
.../Prompts/PromptTests.cs | 16 +-
.../Resources/ResourceTests.cs | 6 +-
.../Tools/AuthorToolTests.cs | 10 +-
.../Tools/BaseToolTests.cs | 4 +-
.../Tools/MovieToolTests.cs | 41 ++--
.../Tools/ReviewToolTests.cs | 53 +++--
.../Tools/ToolListTests.cs | 2 +-
.../AuthenticationSettingsTests.cs | 2 +-
.../Tools/AuthorToolTests.cs | 20 +-
.../Tools/MovieToolTests.cs | 30 +--
.../Tools/ReviewToolTests.cs | 42 +++-
103 files changed, 1374 insertions(+), 1291 deletions(-)
rename src/Application/Authors/Queries/{SearchAuthors/SearchAuthorsValidator.cs => GetAuthors/GetAuthorsValidator.cs} (56%)
delete mode 100644 src/Application/Authors/Queries/SearchAuthors/SearchAuthorsHandler.cs
delete mode 100644 src/Application/Authors/Queries/SearchAuthors/SearchAuthorsQuery.cs
create mode 100644 src/Application/Movies/Queries/GetMovies/GetMoviesValidator.cs
delete mode 100644 src/Application/Movies/Queries/SearchMovies/SearchMoviesHandler.cs
delete mode 100644 src/Application/Movies/Queries/SearchMovies/SearchMoviesQuery.cs
delete mode 100644 src/Application/Movies/Queries/SearchMovies/SearchMoviesValidator.cs
create mode 100644 src/Application/Reviews/Queries/GetReviews/GetReviewsValidator.cs
delete mode 100644 src/Application/Reviews/Queries/SearchReviews/SearchReviewsHandler.cs
delete mode 100644 src/Application/Reviews/Queries/SearchReviews/SearchReviewsQuery.cs
delete mode 100644 src/Application/Reviews/Queries/SearchReviews/SearchReviewsValidator.cs
create mode 100644 src/Infrastructure/Databases/MovieReviews/Migrations/20261028000000_InitialCreate.Designer.cs
create mode 100644 src/Infrastructure/Databases/MovieReviews/Migrations/20261028000000_InitialCreate.cs
create mode 100644 src/Infrastructure/Databases/MovieReviews/Migrations/MovieReviewsDbContextModelSnapshot.cs
create mode 100644 src/Infrastructure/Databases/MovieReviews/MovieReviewsDatabase.cs
create mode 100644 src/Infrastructure/Databases/MovieReviews/MovieReviewsDbContextFactory.cs
rename tests/Application.Tests.Unit/Authors/Queries/{SearchAuthors/SearchAuthorsValidatorTests.cs => GetAuthors/GetAuthorsValidatorTests.cs} (55%)
delete mode 100644 tests/Application.Tests.Unit/Authors/Queries/SearchAuthors/SearchAuthorsHandlerTests.cs
delete mode 100644 tests/Application.Tests.Unit/Common/Paging/PagingTests.cs
rename tests/Application.Tests.Unit/Movies/Queries/{SearchMovies/SearchMoviesValidatorTests.cs => GetMovies/GetMoviesValidatorTests.cs} (56%)
delete mode 100644 tests/Application.Tests.Unit/Movies/Queries/SearchMovies/SearchMoviesHandlerTests.cs
rename tests/Application.Tests.Unit/Reviews/Queries/{SearchReviews/SearchReviewsValidatorTests.cs => GetReviews/GetReviewsValidatorTests.cs} (51%)
delete mode 100644 tests/Application.Tests.Unit/Reviews/Queries/SearchReviews/SearchReviewsHandlerTests.cs
create mode 100644 tests/Infrastructure.Tests.Integration/Databases/MovieReviews/MovieReviewsDatabaseTests.cs
create mode 100644 tests/Infrastructure.Tests.Integration/DependencyInjectionTests.cs
diff --git a/.github/workflows/build-pipeline.yml b/.github/workflows/build-pipeline.yml
index a7a6f50..adc9468 100644
--- a/.github/workflows/build-pipeline.yml
+++ b/.github/workflows/build-pipeline.yml
@@ -290,7 +290,7 @@ jobs:
name: Publish
runs-on: ubuntu-latest
needs: [build, coverage, scan, analysis]
- if: ${{ github.ref == 'refs/heads/main' && (github.event_name == 'push' || github.event_name == 'workflow_dispatch') }}
+ if: ${{ github.repository == 'stphnwlsh/CleanModelContextProtocol' && github.ref == 'refs/heads/main' && (github.event_name == 'push' || github.event_name == 'workflow_dispatch') }}
permissions:
contents: write
id-token: write
diff --git a/.gitignore b/.gitignore
index 702fd02..9f74819 100644
--- a/.gitignore
+++ b/.gitignore
@@ -366,3 +366,9 @@ out/
.Trashes
ehthumbs.db
Thumbs.db
+
+# SQLite databases and coverage reports
+*.db
+*.db-shm
+*.db-wal
+coverage.cobertura.xml
diff --git a/Directory.Build.props b/Directory.Build.props
index 8db3048..79797a9 100644
--- a/Directory.Build.props
+++ b/Directory.Build.props
@@ -5,6 +5,7 @@
CleanModelContextProtocol.$(AssemblyName)
AnyCPU
enable
+ enable
true
latest
diff --git a/Dockerfile b/Dockerfile
index ce0023f..6147df2 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -35,7 +35,7 @@ RUN dotnet build --no-restore -c Release -v minimal -p:VersionPrefix=${VERSION_P
# Dotnet Test
FROM build AS test
-RUN dotnet test --no-restore --no-build -c Release -v minimal -p:CollectCoverage=true -p:CoverletOutput=../results/ -p:MergeWith="../results/coverage.json" -p:CoverletOutputFormat=opencover%2cjson -m:1 -p:ExcludeByFile="**/Program.cs"
+RUN dotnet test --no-restore --no-build -c Release -v minimal -p:CollectCoverage=true -p:CoverletOutput=../results/ -p:MergeWith="../results/coverage.json" -p:CoverletOutputFormat=opencover%2cjson -m:1 -p:ExcludeByFile="**/Program.cs%2c**/Migrations/*.cs"
FROM scratch AS coverage
COPY --from=test /sln/tests/results/*.xml .
diff --git a/README.md b/README.md
index 9434071..8c4f797 100644
--- a/README.md
+++ b/README.md
@@ -87,7 +87,7 @@ The one deliberate break from Clean Architecture is that the Presentation projec
- 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
+- Search with paging and small results by default: every list returns 10 items, a total count and the offset of the next page, with names and average ratings next to ids
- Optional OAuth protection for `/mcp`: JWT bearer tokens plus MCP protected resource metadata, turned on by setting an authority
- 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)
@@ -95,7 +95,7 @@ The one deliberate break from Clean Architecture is that the Presentation projec
- Typed tool results published with an output schema and returned as structured content as well as JSON text
- 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)
+- Data stored in [SQLite](https://learn.microsoft.com/ef/core/providers/sqlite/) using [Entity Framework Core](https://learn.microsoft.com/ef/core) migrations, seeded with [Bogus](https://github.com/bchavez/Bogus). Tests use a throwaway in-memory SQLite database, so they never touch a real one
- 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)
- CI with GitHub Actions: build and test, 95% coverage gate, [Trivy](https://trivy.dev) container scan, [CodeQL](https://codeql.github.com) static analysis, then NuGet publishing and a GitHub release from `main` using [trusted publishing](https://learn.microsoft.com/nuget/nuget-org/trusted-publishing)
- Monthly grouped dependency updates using [Dependabot](https://docs.github.com/code-security/dependabot)
diff --git a/docs/RUN.md b/docs/RUN.md
index 9ee7f48..85f528f 100644
--- a/docs/RUN.md
+++ b/docs/RUN.md
@@ -2,6 +2,17 @@
There are two pre-configured environments, `local` and `docker`. The matching `appsettings.*.json` files decide where logs go: the console when running locally, and a [Seq](https://datalust.co/seq) container when running in Docker.
+## Database
+
+The app stores its data in a SQLite file, `movie-reviews.db`, next to the app. On startup it applies any pending Entity Framework Core migrations and seeds the same sample data every time if the database is empty. Delete the file to start again. Change `ConnectionStrings:MovieReviews` to point somewhere else, or to `Data Source=MovieReviews;Mode=Memory;Cache=Shared` to keep everything in memory.
+
+To add a migration after changing the data model:
+
+``` bash
+dotnet tool install --global dotnet-ef
+dotnet ef migrations add --project ./src/Infrastructure --output-dir Databases/MovieReviews/Migrations
+```
+
## .NET CLI
`launchSettings.json` sets the ports, environment and logging, so one command is enough.
@@ -33,3 +44,5 @@ docker compose down
``` bash
dotnet test
```
+
+The tests never touch `movie-reviews.db`. Each test run builds its own in-memory SQLite database from the migrations and the same fixed seed, so the results are the same every time.
diff --git a/src/Application/Authors/Entities/Author.cs b/src/Application/Authors/Entities/Author.cs
index c3d93e4..49a6b28 100644
--- a/src/Application/Authors/Entities/Author.cs
+++ b/src/Application/Authors/Entities/Author.cs
@@ -9,4 +9,4 @@ namespace CleanModelContextProtocol.Application.Authors.Entities;
/// The author's first name.
/// The author's last name.
/// The reviews the author has written.
-public record Author(Guid Id, string FirstName, string LastName, ICollection Reviews = null);
+public record Author(Guid Id, string FirstName, string LastName, ICollection? Reviews = null);
diff --git a/src/Application/Authors/IAuthorsRepository.cs b/src/Application/Authors/IAuthorsRepository.cs
index b1ae1e7..192d58f 100644
--- a/src/Application/Authors/IAuthorsRepository.cs
+++ b/src/Application/Authors/IAuthorsRepository.cs
@@ -1,19 +1,16 @@
namespace CleanModelContextProtocol.Application.Authors;
-using System.Threading.Tasks;
using Entities;
public interface IAuthorsRepository
{
- public Task> GetAuthors(CancellationToken cancellationToken);
-
- public Task GetAuthorById(Guid id, CancellationToken cancellationToken);
-
- public Task AuthorExists(Guid id, CancellationToken cancellationToken);
-
- public Task<(List Items, int TotalCount)> SearchAuthors(
- string query,
+ public Task<(List Items, int TotalCount)> GetAuthors(
+ string? query,
int offset,
int limit,
CancellationToken cancellationToken);
+
+ public Task GetAuthorById(Guid id, CancellationToken cancellationToken);
+
+ public Task AuthorExists(Guid id, CancellationToken cancellationToken);
}
diff --git a/src/Application/Authors/Queries/GetAuthors/GetAuthorsHandler.cs b/src/Application/Authors/Queries/GetAuthors/GetAuthorsHandler.cs
index 00af4f7..5e8cc55 100644
--- a/src/Application/Authors/Queries/GetAuthors/GetAuthorsHandler.cs
+++ b/src/Application/Authors/Queries/GetAuthors/GetAuthorsHandler.cs
@@ -1,14 +1,15 @@
namespace CleanModelContextProtocol.Application.Authors.Queries.GetAuthors;
-using System.Threading;
-using System.Threading.Tasks;
+using Common.Paging;
using Entities;
using Mediator;
-public class GetAuthorsHandler(IAuthorsRepository repository) : IRequestHandler>
+public class GetAuthorsHandler(IAuthorsRepository repository) : IRequestHandler>
{
- public async ValueTask> Handle(GetAuthorsQuery request, CancellationToken cancellationToken)
+ public async ValueTask> Handle(GetAuthorsQuery request, CancellationToken cancellationToken)
{
- return await repository.GetAuthors(cancellationToken);
+ var (items, totalCount) = await repository.GetAuthors(request.Query, request.Offset, request.Limit, cancellationToken);
+
+ return new Page(items, request.Offset, request.Limit, totalCount);
}
}
diff --git a/src/Application/Authors/Queries/GetAuthors/GetAuthorsQuery.cs b/src/Application/Authors/Queries/GetAuthors/GetAuthorsQuery.cs
index fa23471..63031b9 100644
--- a/src/Application/Authors/Queries/GetAuthors/GetAuthorsQuery.cs
+++ b/src/Application/Authors/Queries/GetAuthors/GetAuthorsQuery.cs
@@ -1,8 +1,20 @@
namespace CleanModelContextProtocol.Application.Authors.Queries.GetAuthors;
+using Common.Paging;
using Entities;
using Mediator;
-public class GetAuthorsQuery : IRequest>
+///
+/// Lists authors one page at a time, optionally only those whose name contains a search term.
+///
+public class GetAuthorsQuery : IRequest>
{
+ /// The words to look for in the first, last or full name, ignoring case. Leave empty to list every author.
+ public string? Query { get; init; }
+
+ /// The number of results to skip, 0 for the first page.
+ public int Offset { get; init; }
+
+ /// The largest number of results to return, from 1 to 50.
+ public int Limit { get; init; } = Paging.DefaultLimit;
}
diff --git a/src/Application/Authors/Queries/SearchAuthors/SearchAuthorsValidator.cs b/src/Application/Authors/Queries/GetAuthors/GetAuthorsValidator.cs
similarity index 56%
rename from src/Application/Authors/Queries/SearchAuthors/SearchAuthorsValidator.cs
rename to src/Application/Authors/Queries/GetAuthors/GetAuthorsValidator.cs
index 0d258c2..5509117 100644
--- a/src/Application/Authors/Queries/SearchAuthors/SearchAuthorsValidator.cs
+++ b/src/Application/Authors/Queries/GetAuthors/GetAuthorsValidator.cs
@@ -1,14 +1,14 @@
-namespace CleanModelContextProtocol.Application.Authors.Queries.SearchAuthors;
+namespace CleanModelContextProtocol.Application.Authors.Queries.GetAuthors;
using Common.Paging;
using FluentValidation;
-public class SearchAuthorsValidator : AbstractValidator
+public class GetAuthorsValidator : AbstractValidator
{
- public SearchAuthorsValidator()
+ public GetAuthorsValidator()
{
_ = this.RuleFor(r => r.Query).ValidSearchTerm();
+ _ = this.RuleFor(r => r.Offset).ValidOffset();
_ = this.RuleFor(r => r.Limit).ValidLimit();
- _ = this.RuleFor(r => r.Cursor).ValidCursor();
}
}
diff --git a/src/Application/Authors/Queries/SearchAuthors/SearchAuthorsHandler.cs b/src/Application/Authors/Queries/SearchAuthors/SearchAuthorsHandler.cs
deleted file mode 100644
index 8af794c..0000000
--- a/src/Application/Authors/Queries/SearchAuthors/SearchAuthorsHandler.cs
+++ /dev/null
@@ -1,19 +0,0 @@
-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
deleted file mode 100644
index a3c12f7..0000000
--- a/src/Application/Authors/Queries/SearchAuthors/SearchAuthorsQuery.cs
+++ /dev/null
@@ -1,20 +0,0 @@
-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/Common/Exceptions/NotFoundException.cs b/src/Application/Common/Exceptions/NotFoundException.cs
index 196ccec..57cbe7d 100644
--- a/src/Application/Common/Exceptions/NotFoundException.cs
+++ b/src/Application/Common/Exceptions/NotFoundException.cs
@@ -1,6 +1,7 @@
namespace CleanModelContextProtocol.Application.Common.Exceptions;
using System;
+using System.Diagnostics.CodeAnalysis;
using Enums;
public class NotFoundException(string message) : Exception(message)
@@ -8,7 +9,7 @@ public class NotFoundException(string message) : Exception(message)
/// Throws a if is null.
/// The reference type argument to validate as non-null.
/// The entity type of the parameter.
- public static void ThrowIfNull(object argument, EntityType entityType)
+ public static void ThrowIfNull([NotNull] object? argument, EntityType entityType)
{
if (argument is null)
{
@@ -18,6 +19,7 @@ public static void ThrowIfNull(object argument, EntityType entityType)
/// Throws a
/// The entity type that was not found.
+ [DoesNotReturn]
public static void Throw(EntityType entityType)
{
throw new NotFoundException($"The {entityType} with the supplied id was not found.");
diff --git a/src/Application/Common/Paging/Page.cs b/src/Application/Common/Paging/Page.cs
index 776cc83..e01132a 100644
--- a/src/Application/Common/Paging/Page.cs
+++ b/src/Application/Common/Paging/Page.cs
@@ -1,10 +1,11 @@
namespace CleanModelContextProtocol.Application.Common.Paging;
///
-/// One page of results from a search.
+/// One page of results from a list.
///
/// The type of the results.
/// The results on this page.
+/// The number of results skipped before this page.
+/// The largest number of results this page could hold.
/// 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);
+public record Page(List Items, int Offset, int Limit, int TotalCount);
diff --git a/src/Application/Common/Paging/Paging.cs b/src/Application/Common/Paging/Paging.cs
index 440b9e2..e6aa4bc 100644
--- a/src/Application/Common/Paging/Paging.cs
+++ b/src/Application/Common/Paging/Paging.cs
@@ -1,10 +1,7 @@
namespace CleanModelContextProtocol.Application.Common.Paging;
-using System.Globalization;
-using System.Text;
-
///
-/// Limits and opaque cursors shared by every search.
+/// The limits shared by every paged list.
///
public static class Paging
{
@@ -13,53 +10,4 @@ public static class Paging
/// 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
index 940bb27..040ba78 100644
--- a/src/Application/Common/Paging/PagingValidatorExtensions.cs
+++ b/src/Application/Common/Paging/PagingValidatorExtensions.cs
@@ -3,34 +3,33 @@ namespace CleanModelContextProtocol.Application.Common.Paging;
using FluentValidation;
///
-/// Validation rules shared by every search.
+/// Validation rules shared by every paged list.
///
public static class PagingValidatorExtensions
{
- /// Checks that a limit is between 1 and .
+ /// Checks that an offset is zero or more.
/// The type being validated.
- /// The rule for the limit.
+ /// The rule for the offset.
/// The rule.
- public static IRuleBuilderOptions ValidLimit(this IRuleBuilder rule)
+ public static IRuleBuilderOptions ValidOffset(this IRuleBuilder rule)
{
- return rule.InclusiveBetween(1, Paging.MaxLimit).WithMessage($"A limit must be between 1 and {Paging.MaxLimit}.");
+ return rule.GreaterThanOrEqualTo(0).WithMessage("An offset can't be negative. Use 0 for the first page.");
}
- /// Checks that a cursor is empty or came from a previous page.
+ /// Checks that a limit is between 1 and .
/// The type being validated.
- /// The rule for the cursor.
+ /// The rule for the limit.
/// The rule.
- public static IRuleBuilderOptions ValidCursor(this IRuleBuilder rule)
+ public static IRuleBuilderOptions ValidLimit(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.");
+ return rule.InclusiveBetween(1, Paging.MaxLimit).WithMessage($"A limit must be between 1 and {Paging.MaxLimit}.");
}
/// 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)
+ 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/Entities/Movie.cs b/src/Application/Movies/Entities/Movie.cs
index a664863..6fbe762 100644
--- a/src/Application/Movies/Entities/Movie.cs
+++ b/src/Application/Movies/Entities/Movie.cs
@@ -8,4 +8,4 @@ namespace CleanModelContextProtocol.Application.Movies.Entities;
/// The unique identifier of the movie.
/// The title of the movie.
/// The reviews written about the movie.
-public record Movie(Guid Id, string Title, ICollection Reviews = null);
+public record Movie(Guid Id, string Title, ICollection? Reviews = null);
diff --git a/src/Application/Movies/IMoviesRepository.cs b/src/Application/Movies/IMoviesRepository.cs
index eb55f94..7b7de29 100644
--- a/src/Application/Movies/IMoviesRepository.cs
+++ b/src/Application/Movies/IMoviesRepository.cs
@@ -1,19 +1,16 @@
namespace CleanModelContextProtocol.Application.Movies;
-using System.Threading.Tasks;
using Entities;
public interface IMoviesRepository
{
- public Task> GetMovies(CancellationToken cancellationToken);
-
- public Task GetMovieById(Guid id, CancellationToken cancellationToken);
-
- public Task MovieExists(Guid id, CancellationToken cancellationToken);
-
- public Task<(List Items, int TotalCount)> SearchMovies(
- string query,
+ public Task<(List Items, int TotalCount)> GetMovies(
+ string? query,
int offset,
int limit,
CancellationToken cancellationToken);
+
+ public Task GetMovieById(Guid id, CancellationToken cancellationToken);
+
+ public Task MovieExists(Guid id, CancellationToken cancellationToken);
}
diff --git a/src/Application/Movies/Queries/GetMovies/GetMoviesHandler.cs b/src/Application/Movies/Queries/GetMovies/GetMoviesHandler.cs
index 81488e2..4bddf54 100644
--- a/src/Application/Movies/Queries/GetMovies/GetMoviesHandler.cs
+++ b/src/Application/Movies/Queries/GetMovies/GetMoviesHandler.cs
@@ -1,14 +1,15 @@
namespace CleanModelContextProtocol.Application.Movies.Queries.GetMovies;
-using System.Threading;
-using System.Threading.Tasks;
+using Common.Paging;
using Entities;
using Mediator;
-public class GetMoviesHandler(IMoviesRepository repository) : IRequestHandler>
+public class GetMoviesHandler(IMoviesRepository repository) : IRequestHandler>
{
- public async ValueTask> Handle(GetMoviesQuery request, CancellationToken cancellationToken)
+ public async ValueTask> Handle(GetMoviesQuery request, CancellationToken cancellationToken)
{
- return await repository.GetMovies(cancellationToken);
+ var (items, totalCount) = await repository.GetMovies(request.Query, request.Offset, request.Limit, cancellationToken);
+
+ return new Page(items, request.Offset, request.Limit, totalCount);
}
}
diff --git a/src/Application/Movies/Queries/GetMovies/GetMoviesQuery.cs b/src/Application/Movies/Queries/GetMovies/GetMoviesQuery.cs
index 03a644c..40072fb 100644
--- a/src/Application/Movies/Queries/GetMovies/GetMoviesQuery.cs
+++ b/src/Application/Movies/Queries/GetMovies/GetMoviesQuery.cs
@@ -1,8 +1,20 @@
namespace CleanModelContextProtocol.Application.Movies.Queries.GetMovies;
+using Common.Paging;
using Entities;
using Mediator;
-public class GetMoviesQuery : IRequest>
+///
+/// Lists movies one page at a time, optionally only those whose title contains a search term.
+///
+public class GetMoviesQuery : IRequest>
{
+ /// The words to look for in the title, ignoring case. Leave empty to list every movie.
+ public string? Query { get; init; }
+
+ /// The number of results to skip, 0 for the first page.
+ public int Offset { get; init; }
+
+ /// The largest number of results to return, from 1 to 50.
+ public int Limit { get; init; } = Paging.DefaultLimit;
}
diff --git a/src/Application/Movies/Queries/GetMovies/GetMoviesValidator.cs b/src/Application/Movies/Queries/GetMovies/GetMoviesValidator.cs
new file mode 100644
index 0000000..883d8f7
--- /dev/null
+++ b/src/Application/Movies/Queries/GetMovies/GetMoviesValidator.cs
@@ -0,0 +1,14 @@
+namespace CleanModelContextProtocol.Application.Movies.Queries.GetMovies;
+
+using Common.Paging;
+using FluentValidation;
+
+public class GetMoviesValidator : AbstractValidator
+{
+ public GetMoviesValidator()
+ {
+ _ = this.RuleFor(r => r.Query).ValidSearchTerm();
+ _ = this.RuleFor(r => r.Offset).ValidOffset();
+ _ = this.RuleFor(r => r.Limit).ValidLimit();
+ }
+}
diff --git a/src/Application/Movies/Queries/SearchMovies/SearchMoviesHandler.cs b/src/Application/Movies/Queries/SearchMovies/SearchMoviesHandler.cs
deleted file mode 100644
index 2486af7..0000000
--- a/src/Application/Movies/Queries/SearchMovies/SearchMoviesHandler.cs
+++ /dev/null
@@ -1,19 +0,0 @@
-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
deleted file mode 100644
index 39be8fa..0000000
--- a/src/Application/Movies/Queries/SearchMovies/SearchMoviesQuery.cs
+++ /dev/null
@@ -1,20 +0,0 @@
-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
deleted file mode 100644
index d45bca5..0000000
--- a/src/Application/Movies/Queries/SearchMovies/SearchMoviesValidator.cs
+++ /dev/null
@@ -1,14 +0,0 @@
-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/Commands/UpdateReview/UpdateReviewCommand.cs b/src/Application/Reviews/Commands/UpdateReview/UpdateReviewCommand.cs
index 0f11c5d..2ba0410 100644
--- a/src/Application/Reviews/Commands/UpdateReview/UpdateReviewCommand.cs
+++ b/src/Application/Reviews/Commands/UpdateReview/UpdateReviewCommand.cs
@@ -2,13 +2,14 @@ namespace CleanModelContextProtocol.Application.Reviews.Commands.UpdateReview;
using Mediator;
+///
+/// Changes the star rating of a review. The author and the movie of a review can't change.
+///
public class UpdateReviewCommand : IRequest
{
- public Guid Id { get; set; }
-
- public Guid AuthorId { get; init; }
-
- public Guid MovieId { get; init; }
+ /// The unique identifier of the review.
+ public Guid Id { get; init; }
+ /// The new star rating, from 1 to 5.
public int Stars { get; init; }
}
diff --git a/src/Application/Reviews/Commands/UpdateReview/UpdateReviewHandler.cs b/src/Application/Reviews/Commands/UpdateReview/UpdateReviewHandler.cs
index 90b07f3..7e9dedc 100644
--- a/src/Application/Reviews/Commands/UpdateReview/UpdateReviewHandler.cs
+++ b/src/Application/Reviews/Commands/UpdateReview/UpdateReviewHandler.cs
@@ -1,17 +1,10 @@
namespace CleanModelContextProtocol.Application.Reviews.Commands.UpdateReview;
-using System.Threading;
-using System.Threading.Tasks;
-using CleanModelContextProtocol.Application.Authors;
-using CleanModelContextProtocol.Application.Movies;
using Common.Enums;
using Common.Exceptions;
using Mediator;
-public class UpdateReviewHandler(
- IAuthorsRepository authorsRepository,
- IMoviesRepository moviesRepository,
- IReviewsRepository reviewsRepository) : IRequestHandler
+public class UpdateReviewHandler(IReviewsRepository reviewsRepository) : IRequestHandler
{
public async ValueTask Handle(UpdateReviewCommand request, CancellationToken cancellationToken)
{
@@ -20,17 +13,6 @@ public async ValueTask Handle(UpdateReviewCommand request, CancellationTok
NotFoundException.Throw(EntityType.Review);
}
- if (!await authorsRepository.AuthorExists(request.AuthorId, cancellationToken))
- {
- NotFoundException.Throw(EntityType.Author);
- }
-
- if (!await moviesRepository.MovieExists(request.MovieId, cancellationToken))
- {
- NotFoundException.Throw(EntityType.Movie);
- }
-
- return await reviewsRepository
- .UpdateReview(request.Id, request.AuthorId, request.MovieId, request.Stars, cancellationToken);
+ return await reviewsRepository.UpdateReview(request.Id, request.Stars, cancellationToken);
}
}
diff --git a/src/Application/Reviews/Commands/UpdateReview/UpdateReviewValidator.cs b/src/Application/Reviews/Commands/UpdateReview/UpdateReviewValidator.cs
index d95b20f..a1bb7b1 100644
--- a/src/Application/Reviews/Commands/UpdateReview/UpdateReviewValidator.cs
+++ b/src/Application/Reviews/Commands/UpdateReview/UpdateReviewValidator.cs
@@ -7,8 +7,6 @@ public class UpdateReviewValidator : AbstractValidator
public UpdateReviewValidator()
{
_ = this.RuleFor(r => r.Id).NotEqual(Guid.Empty).WithMessage("A review id was not supplied to Update the review.");
- _ = this.RuleFor(r => r.AuthorId).NotEqual(Guid.Empty).WithMessage("An author id was not supplied to Update the review.");
- _ = this.RuleFor(r => r.MovieId).NotEqual(Guid.Empty).WithMessage("A movie id was not supplied to Update the review.");
_ = this.RuleFor(r => r.Stars).InclusiveBetween(1, 5).WithMessage("A star rating must be between 1 and 5.");
}
}
diff --git a/src/Application/Reviews/Entities/Review.cs b/src/Application/Reviews/Entities/Review.cs
index 580814e..da115ce 100644
--- a/src/Application/Reviews/Entities/Review.cs
+++ b/src/Application/Reviews/Entities/Review.cs
@@ -13,5 +13,5 @@ namespace CleanModelContextProtocol.Application.Reviews.Entities;
public record Review(
Guid Id,
int Stars,
- ReviewedMovie ReviewedMovie = null,
- ReviewAuthor ReviewAuthor = null);
+ ReviewedMovie? ReviewedMovie = null,
+ ReviewAuthor? ReviewAuthor = null);
diff --git a/src/Application/Reviews/IReviewsRepository.cs b/src/Application/Reviews/IReviewsRepository.cs
index 1e59e60..9cfc82e 100644
--- a/src/Application/Reviews/IReviewsRepository.cs
+++ b/src/Application/Reviews/IReviewsRepository.cs
@@ -1,6 +1,5 @@
namespace CleanModelContextProtocol.Application.Reviews;
-using System.Threading.Tasks;
using Entities;
public interface IReviewsRepository
@@ -13,23 +12,16 @@ public Task CreateReview(
public Task DeleteReview(Guid id, CancellationToken cancellationToken);
- public Task> GetReviews(CancellationToken cancellationToken);
-
- public Task GetReviewById(Guid id, CancellationToken cancellationToken);
-
- public Task ReviewExists(Guid id, CancellationToken cancellationToken);
-
- public Task<(List Items, int TotalCount)> SearchReviews(
+ public Task<(List Items, int TotalCount)> GetReviews(
Guid? movieId,
Guid? authorId,
int offset,
int limit,
CancellationToken cancellationToken);
- public Task UpdateReview(
- Guid id,
- Guid authorId,
- Guid movieId,
- int stars,
- CancellationToken cancellationToken);
+ public Task GetReviewById(Guid id, CancellationToken cancellationToken);
+
+ public Task ReviewExists(Guid id, CancellationToken cancellationToken);
+
+ public Task UpdateReview(Guid id, int stars, CancellationToken cancellationToken);
}
diff --git a/src/Application/Reviews/Queries/GetReviews/GetReviewsHandler.cs b/src/Application/Reviews/Queries/GetReviews/GetReviewsHandler.cs
index fc0c1a9..e46086e 100644
--- a/src/Application/Reviews/Queries/GetReviews/GetReviewsHandler.cs
+++ b/src/Application/Reviews/Queries/GetReviews/GetReviewsHandler.cs
@@ -1,14 +1,15 @@
namespace CleanModelContextProtocol.Application.Reviews.Queries.GetReviews;
-using System.Threading;
-using System.Threading.Tasks;
+using Common.Paging;
using Entities;
using Mediator;
-public class GetReviewsHandler(IReviewsRepository repository) : IRequestHandler>
+public class GetReviewsHandler(IReviewsRepository repository) : IRequestHandler>
{
- public async ValueTask> Handle(GetReviewsQuery request, CancellationToken cancellationToken)
+ public async ValueTask> Handle(GetReviewsQuery request, CancellationToken cancellationToken)
{
- return await repository.GetReviews(cancellationToken);
+ var (items, totalCount) = await repository.GetReviews(request.MovieId, request.AuthorId, request.Offset, request.Limit, cancellationToken);
+
+ return new Page(items, request.Offset, request.Limit, totalCount);
}
}
diff --git a/src/Application/Reviews/Queries/GetReviews/GetReviewsQuery.cs b/src/Application/Reviews/Queries/GetReviews/GetReviewsQuery.cs
index 23c80bc..6e735bd 100644
--- a/src/Application/Reviews/Queries/GetReviews/GetReviewsQuery.cs
+++ b/src/Application/Reviews/Queries/GetReviews/GetReviewsQuery.cs
@@ -1,8 +1,23 @@
namespace CleanModelContextProtocol.Application.Reviews.Queries.GetReviews;
+using Common.Paging;
using Entities;
using Mediator;
-public class GetReviewsQuery : IRequest>
+///
+/// Lists reviews one page at a time, optionally only those of one movie, by one author, or both.
+///
+public class GetReviewsQuery : 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 number of results to skip, 0 for the first page.
+ public int Offset { get; init; }
+
+ /// The largest number of results to return, from 1 to 50.
+ public int Limit { get; init; } = Paging.DefaultLimit;
}
diff --git a/src/Application/Reviews/Queries/GetReviews/GetReviewsValidator.cs b/src/Application/Reviews/Queries/GetReviews/GetReviewsValidator.cs
new file mode 100644
index 0000000..e917878
--- /dev/null
+++ b/src/Application/Reviews/Queries/GetReviews/GetReviewsValidator.cs
@@ -0,0 +1,15 @@
+namespace CleanModelContextProtocol.Application.Reviews.Queries.GetReviews;
+
+using Common.Paging;
+using FluentValidation;
+
+public class GetReviewsValidator : AbstractValidator
+{
+ public GetReviewsValidator()
+ {
+ _ = this.RuleFor(r => r.MovieId).NotEqual(Guid.Empty).WithMessage("A Movie Id can't be empty. Leave it out to list every movie.");
+ _ = this.RuleFor(r => r.AuthorId).NotEqual(Guid.Empty).WithMessage("An Author Id can't be empty. Leave it out to list every author.");
+ _ = this.RuleFor(r => r.Offset).ValidOffset();
+ _ = this.RuleFor(r => r.Limit).ValidLimit();
+ }
+}
diff --git a/src/Application/Reviews/Queries/SearchReviews/SearchReviewsHandler.cs b/src/Application/Reviews/Queries/SearchReviews/SearchReviewsHandler.cs
deleted file mode 100644
index df733e3..0000000
--- a/src/Application/Reviews/Queries/SearchReviews/SearchReviewsHandler.cs
+++ /dev/null
@@ -1,19 +0,0 @@
-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
deleted file mode 100644
index 2080520..0000000
--- a/src/Application/Reviews/Queries/SearchReviews/SearchReviewsQuery.cs
+++ /dev/null
@@ -1,23 +0,0 @@
-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
deleted file mode 100644
index f37375b..0000000
--- a/src/Application/Reviews/Queries/SearchReviews/SearchReviewsValidator.cs
+++ /dev/null
@@ -1,15 +0,0 @@
-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/Application/Versions/Entities/Version.cs b/src/Application/Versions/Entities/Version.cs
index 1c064ee..9eaf65d 100644
--- a/src/Application/Versions/Entities/Version.cs
+++ b/src/Application/Versions/Entities/Version.cs
@@ -9,11 +9,11 @@ public class Version
/// The assembly file version.
///
/// 1.1.0.0
- public string FileVersion { get; init; }
+ public required string FileVersion { get; init; }
///
/// The informational version, which can include a pre-release label or commit hash.
///
/// 1.1.0+e30eba8
- public string InformationalVersion { get; init; }
+ public required string InformationalVersion { get; init; }
}
diff --git a/src/Infrastructure/Databases/MovieReviews/Configuration/EntityConfiguration.cs b/src/Infrastructure/Databases/MovieReviews/Configuration/EntityConfiguration.cs
index bf6ec2a..fb4ce72 100644
--- a/src/Infrastructure/Databases/MovieReviews/Configuration/EntityConfiguration.cs
+++ b/src/Infrastructure/Databases/MovieReviews/Configuration/EntityConfiguration.cs
@@ -11,7 +11,7 @@ public virtual void Configure(EntityTypeBuilder builder)
{
_ = builder.HasKey(e => e.Id);
_ = builder.Property(m => m.Id).ValueGeneratedOnAdd().IsRequired();
- _ = builder.Property(m => m.DateCreated).ValueGeneratedOnAdd().IsRequired();
- _ = builder.Property(m => m.DateModified).ValueGeneratedOnAdd().IsRequired();
+ _ = builder.Property(m => m.DateCreated).IsRequired();
+ _ = builder.Property(m => m.DateModified).IsRequired();
}
}
diff --git a/src/Infrastructure/Databases/MovieReviews/EntityFrameworkMovieReviewsRepository.cs b/src/Infrastructure/Databases/MovieReviews/EntityFrameworkMovieReviewsRepository.cs
index 8dc950b..640726a 100644
--- a/src/Infrastructure/Databases/MovieReviews/EntityFrameworkMovieReviewsRepository.cs
+++ b/src/Infrastructure/Databases/MovieReviews/EntityFrameworkMovieReviewsRepository.cs
@@ -2,11 +2,8 @@ namespace CleanModelContextProtocol.Infrastructure.Databases.MovieReviews;
using System;
using Application.Authors;
-using Application.Common.Enums;
-using Application.Common.Exceptions;
using Application.Movies;
using Application.Reviews;
-using Extensions;
using Mapping;
using Microsoft.EntityFrameworkCore;
using Models;
@@ -32,43 +29,12 @@ public EntityFrameworkMovieReviewsRepository(
this.context = context;
this.timeProvider = timeProvider;
this.mapper = mapper;
-
- _ = this.context.Database.EnsureDeleted();
- _ = this.context.Database.EnsureCreated();
- _ = this.context.AddData();
}
#region Authors
- public virtual async Task> GetAuthors(CancellationToken cancellationToken)
- {
- var authors = await this.context.Authors
- .Include(a => a.Reviews)
- .ThenInclude(r => r.ReviewedMovie)
- .AsNoTracking()
- .ToListAsync(cancellationToken);
-
- return [.. authors.Select(this.mapper.ToDomain)];
- }
-
- public virtual async Task GetAuthorById(Guid id, CancellationToken cancellationToken)
- {
- var author = await this.context.Authors
- .Where(r => r.Id == id).Include(a => a.Reviews)
- .ThenInclude(r => r.ReviewedMovie)
- .AsNoTracking()
- .FirstOrDefaultAsync(cancellationToken);
-
- return this.mapper.ToDomain(author);
- }
-
- public virtual async Task AuthorExists(Guid id, CancellationToken cancellationToken)
- {
- return await this.context.Authors.AsNoTracking().AnyAsync(a => a.Id == id, cancellationToken);
- }
-
- public virtual async Task<(List Items, int TotalCount)> SearchAuthors(
- string query,
+ public virtual async Task<(List Items, int TotalCount)> GetAuthors(
+ string? query,
int offset,
int limit,
CancellationToken cancellationToken)
@@ -77,9 +43,9 @@ public virtual async Task AuthorExists(Guid id, CancellationToken cancella
if (!string.IsNullOrWhiteSpace(query))
{
- var term = query.Trim();
+ var pattern = ContainsPattern(query);
- authors = authors.Where(a => (a.FirstName + " " + a.LastName).Contains(term, StringComparison.OrdinalIgnoreCase));
+ authors = authors.Where(a => EF.Functions.Like(a.FirstName + " " + a.LastName, pattern, EscapeCharacter));
}
var totalCount = await authors.CountAsync(cancellationToken);
@@ -97,40 +63,28 @@ public virtual async Task AuthorExists(Guid id, CancellationToken cancella
return ([.. result.Select(this.mapper.ToDomain)], totalCount);
}
- #endregion Authors
-
- #region Movies
-
- public virtual async Task> GetMovies(CancellationToken cancellationToken)
+ public virtual async Task GetAuthorById(Guid id, CancellationToken cancellationToken)
{
- var result = await this.context.Movies
- .Include(m => m.Reviews)
- .ThenInclude(r => r.ReviewAuthor)
- .AsNoTracking()
- .ToListAsync(cancellationToken);
-
- return [.. result.Select(this.mapper.ToDomain)];
- }
-
- public virtual async Task GetMovieById(Guid id, CancellationToken cancellationToken)
- {
- var result = await this.context.Movies
- .Where(r => r.Id == id)
- .Include(m => m.Reviews)
- .ThenInclude(r => r.ReviewAuthor)
+ var author = await this.context.Authors
+ .Where(r => r.Id == id).Include(a => a.Reviews)
+ .ThenInclude(r => r.ReviewedMovie)
.AsNoTracking()
.FirstOrDefaultAsync(cancellationToken);
- return this.mapper.ToDomain(result);
+ return author is null ? null : this.mapper.ToDomain(author);
}
- public virtual async Task MovieExists(Guid id, CancellationToken cancellationToken)
+ public virtual async Task AuthorExists(Guid id, CancellationToken cancellationToken)
{
- return await this.context.Movies.AsNoTracking().AnyAsync(m => m.Id == id, cancellationToken);
+ return await this.context.Authors.AsNoTracking().AnyAsync(a => a.Id == id, cancellationToken);
}
- public virtual async Task<(List Items, int TotalCount)> SearchMovies(
- string query,
+ #endregion Authors
+
+ #region Movies
+
+ public virtual async Task<(List Items, int TotalCount)> GetMovies(
+ string? query,
int offset,
int limit,
CancellationToken cancellationToken)
@@ -139,9 +93,9 @@ public virtual async Task MovieExists(Guid id, CancellationToken cancellat
if (!string.IsNullOrWhiteSpace(query))
{
- var term = query.Trim();
+ var pattern = ContainsPattern(query);
- movies = movies.Where(m => m.Title.Contains(term, StringComparison.OrdinalIgnoreCase));
+ movies = movies.Where(m => EF.Functions.Like(m.Title, pattern, EscapeCharacter));
}
var totalCount = await movies.CountAsync(cancellationToken);
@@ -158,6 +112,23 @@ public virtual async Task MovieExists(Guid id, CancellationToken cancellat
return ([.. result.Select(this.mapper.ToDomain)], totalCount);
}
+ public virtual async Task GetMovieById(Guid id, CancellationToken cancellationToken)
+ {
+ var result = await this.context.Movies
+ .Where(r => r.Id == id)
+ .Include(m => m.Reviews)
+ .ThenInclude(r => r.ReviewAuthor)
+ .AsNoTracking()
+ .FirstOrDefaultAsync(cancellationToken);
+
+ return result is null ? null : this.mapper.ToDomain(result);
+ }
+
+ public virtual async Task MovieExists(Guid id, CancellationToken cancellationToken)
+ {
+ return await this.context.Movies.AsNoTracking().AnyAsync(m => m.Id == id, cancellationToken);
+ }
+
#endregion Movies
#region Reviews
@@ -168,13 +139,15 @@ public async Task CreateReview(
int stars,
CancellationToken cancellationToken)
{
+ var now = this.timeProvider.GetUtcNow().UtcDateTime;
+
var review = new Review
{
ReviewAuthorId = authorId,
ReviewedMovieId = movieId,
Stars = stars,
- DateCreated = this.timeProvider.GetUtcNow().UtcDateTime,
- DateModified = this.timeProvider.GetUtcNow().UtcDateTime
+ DateCreated = now,
+ DateModified = now
};
var id = this.context.Add(review).Entity.Id;
@@ -193,48 +166,14 @@ public async Task CreateReview(
public async Task DeleteReview(Guid id, CancellationToken cancellationToken)
{
- try
- {
- _ = this.context.Remove(this.context.Reviews.Single(r => r.Id == id));
- _ = await this.context.SaveChangesAsync(cancellationToken);
- }
- catch (Exception)
- {
- return false;
- }
-
- return true;
- }
-
- public async Task> GetReviews(CancellationToken cancellationToken)
- {
- var result = await this.context.Reviews
- .Include(r => r.ReviewAuthor)
- .Include(r => r.ReviewedMovie)
- .AsNoTracking()
- .ToListAsync(cancellationToken);
-
- return [.. result.Select(this.mapper.ToDomain)];
- }
-
- public async Task GetReviewById(Guid id, CancellationToken cancellationToken)
- {
- var result = await this.context.Reviews
+ var deleted = await this.context.Reviews
.Where(r => r.Id == id)
- .Include(r => r.ReviewAuthor)
- .Include(r => r.ReviewedMovie)
- .AsNoTracking()
- .FirstOrDefaultAsync(cancellationToken);
+ .ExecuteDeleteAsync(cancellationToken);
- return this.mapper.ToDomain(result);
- }
-
- public async Task ReviewExists(Guid id, CancellationToken cancellationToken)
- {
- return await this.context.Reviews.AnyAsync(r => r.Id == id, cancellationToken);
+ return deleted > 0;
}
- public async Task<(List Items, int TotalCount)> SearchReviews(
+ public async Task<(List Items, int TotalCount)> GetReviews(
Guid? movieId,
Guid? authorId,
int offset,
@@ -268,34 +207,57 @@ public async Task ReviewExists(Guid id, CancellationToken cancellationToke
return ([.. result.Select(this.mapper.ToDomain)], totalCount);
}
- public async Task UpdateReview(
- Guid id,
- Guid authorId,
- Guid movieId,
- int stars,
- CancellationToken cancellationToken)
+ public async Task GetReviewById(Guid id, CancellationToken cancellationToken)
{
- try
- {
- var review = this.context.Reviews.FirstOrDefault(r => r.Id == id);
+ var result = await this.context.Reviews
+ .Where(r => r.Id == id)
+ .Include(r => r.ReviewAuthor)
+ .Include(r => r.ReviewedMovie)
+ .AsNoTracking()
+ .FirstOrDefaultAsync(cancellationToken);
- NotFoundException.ThrowIfNull(review, EntityType.Review);
+ return result is null ? null : this.mapper.ToDomain(result);
+ }
- review.Stars = stars;
- review.ReviewAuthorId = authorId;
- review.ReviewedMovieId = movieId;
- review.DateModified = this.timeProvider.GetUtcNow().UtcDateTime;
+ public async Task ReviewExists(Guid id, CancellationToken cancellationToken)
+ {
+ return await this.context.Reviews.AnyAsync(r => r.Id == id, cancellationToken);
+ }
- _ = this.context.Update(review);
- _ = await this.context.SaveChangesAsync(cancellationToken);
- }
- catch (Exception)
- {
- return false;
- }
+ public async Task UpdateReview(Guid id, int stars, CancellationToken cancellationToken)
+ {
+ var now = this.timeProvider.GetUtcNow().UtcDateTime;
+
+ var updated = await this.context.Reviews
+ .Where(r => r.Id == id)
+ .ExecuteUpdateAsync(
+ setters => setters
+ .SetProperty(r => r.Stars, stars)
+ .SetProperty(r => r.DateModified, now),
+ cancellationToken);
- return true;
+ return updated > 0;
}
#endregion Reviews
+
+ #region Search
+
+ private const string EscapeCharacter = "\\";
+
+ ///
+ /// Builds a LIKE pattern that matches any text containing the search term. LIKE ignores case for
+ /// ASCII text in SQLite and SQL Server, and the term's own wildcards are escaped so they match literally.
+ ///
+ private static string ContainsPattern(string query)
+ {
+ var term = query.Trim()
+ .Replace(EscapeCharacter, EscapeCharacter + EscapeCharacter, StringComparison.Ordinal)
+ .Replace("%", EscapeCharacter + "%", StringComparison.Ordinal)
+ .Replace("_", EscapeCharacter + "_", StringComparison.Ordinal);
+
+ return $"%{term}%";
+ }
+
+ #endregion Search
}
diff --git a/src/Infrastructure/Databases/MovieReviews/Extensions/MovieReviewsDbContextExtensions.cs b/src/Infrastructure/Databases/MovieReviews/Extensions/MovieReviewsDbContextExtensions.cs
index f1333df..6aef8c3 100644
--- a/src/Infrastructure/Databases/MovieReviews/Extensions/MovieReviewsDbContextExtensions.cs
+++ b/src/Infrastructure/Databases/MovieReviews/Extensions/MovieReviewsDbContextExtensions.cs
@@ -6,34 +6,46 @@ namespace CleanModelContextProtocol.Infrastructure.Databases.MovieReviews.Extens
internal static class MovieReviewsDbContextExtensions
{
+ // A fixed seed and reference date give the same sample data on every run.
+ private const int Seed = 20211014;
+ private static readonly DateTime ReferenceDate = new(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc);
+
public static MovieReviewsDbContext AddData(this MovieReviewsDbContext context)
{
+ if (context.Authors.Any())
+ {
+ return context;
+ }
+
var authors = new Faker()
- .RuleFor(a => a.Id, _ => Guid.NewGuid())
+ .UseSeed(Seed)
+ .RuleFor(a => a.Id, f => f.Random.Guid())
.RuleFor(a => a.FirstName, f => f.Person.FirstName)
.RuleFor(a => a.LastName, f => f.Person.LastName)
- .RuleFor(a => a.DateCreated, f => f.Date.Past())
- .RuleFor(a => a.DateModified, f => f.Date.Past())
+ .RuleFor(a => a.DateCreated, f => f.Date.Past(refDate: ReferenceDate))
+ .RuleFor(a => a.DateModified, f => f.Date.Past(refDate: ReferenceDate))
.Generate(15);
context.AddRange(authors);
var movies = new Faker()
- .RuleFor(m => m.Id, _ => Guid.NewGuid())
+ .UseSeed(Seed)
+ .RuleFor(m => m.Id, f => f.Random.Guid())
.RuleFor(m => m.Title, f => f.Company.CatchPhrase())
- .RuleFor(m => m.DateCreated, f => f.Date.Past())
- .RuleFor(m => m.DateModified, f => f.Date.Past())
+ .RuleFor(m => m.DateCreated, f => f.Date.Past(refDate: ReferenceDate))
+ .RuleFor(m => m.DateModified, f => f.Date.Past(refDate: ReferenceDate))
.Generate(50);
context.AddRange(movies);
var reviews = new Faker()
- .RuleFor(r => r.Id, _ => Guid.NewGuid())
+ .UseSeed(Seed)
+ .RuleFor(r => r.Id, f => f.Random.Guid())
.RuleFor(r => r.ReviewedMovieId, f => f.PickRandom(movies).Id)
.RuleFor(r => r.ReviewAuthorId, f => f.PickRandom(authors).Id)
.RuleFor(r => r.Stars, f => f.Random.Number(1, 5))
- .RuleFor(r => r.DateCreated, f => f.Date.Past())
- .RuleFor(r => r.DateModified, f => f.Date.Past())
+ .RuleFor(r => r.DateCreated, f => f.Date.Past(refDate: ReferenceDate))
+ .RuleFor(r => r.DateModified, f => f.Date.Past(refDate: ReferenceDate))
.Generate(150);
context.AddRange(reviews);
diff --git a/src/Infrastructure/Databases/MovieReviews/Mapping/MovieReviewsMapper.cs b/src/Infrastructure/Databases/MovieReviews/Mapping/MovieReviewsMapper.cs
index f5dfcd2..1bd5647 100644
--- a/src/Infrastructure/Databases/MovieReviews/Mapping/MovieReviewsMapper.cs
+++ b/src/Infrastructure/Databases/MovieReviews/Mapping/MovieReviewsMapper.cs
@@ -15,6 +15,8 @@ internal partial class MovieReviewsMapper
{
// Infrastructure → Domain
+ [MapperIgnoreSource(nameof(InfraAuthor.DateCreated))]
+ [MapperIgnoreSource(nameof(InfraAuthor.DateModified))]
public partial AppAuthor ToDomain(InfraAuthor author);
[MapperIgnoreSource(nameof(InfraAuthor.Reviews))]
@@ -22,6 +24,8 @@ internal partial class MovieReviewsMapper
[MapperIgnoreSource(nameof(InfraAuthor.DateModified))]
public partial AppReviewAuthor ToReviewAuthor(InfraAuthor author);
+ [MapperIgnoreSource(nameof(InfraMovie.DateCreated))]
+ [MapperIgnoreSource(nameof(InfraMovie.DateModified))]
public partial AppMovie ToDomain(InfraMovie movie);
[MapperIgnoreSource(nameof(InfraMovie.Reviews))]
diff --git a/src/Infrastructure/Databases/MovieReviews/Migrations/20261028000000_InitialCreate.Designer.cs b/src/Infrastructure/Databases/MovieReviews/Migrations/20261028000000_InitialCreate.Designer.cs
new file mode 100644
index 0000000..daa9732
--- /dev/null
+++ b/src/Infrastructure/Databases/MovieReviews/Migrations/20261028000000_InitialCreate.Designer.cs
@@ -0,0 +1,130 @@
+//
+using System;
+using CleanModelContextProtocol.Infrastructure.Databases.MovieReviews;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Infrastructure;
+using Microsoft.EntityFrameworkCore.Migrations;
+using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
+
+#nullable disable
+
+namespace CleanModelContextProtocol.Infrastructure.Databases.MovieReviews.Migrations
+{
+ [DbContext(typeof(MovieReviewsDbContext))]
+ [Migration("20261028000000_InitialCreate")]
+ partial class InitialCreate
+ {
+ ///
+ protected override void BuildTargetModel(ModelBuilder modelBuilder)
+ {
+#pragma warning disable 612, 618
+ modelBuilder.HasAnnotation("ProductVersion", "10.0.14");
+
+ modelBuilder.Entity("CleanModelContextProtocol.Infrastructure.Databases.MovieReviews.Models.Author", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("TEXT");
+
+ b.Property("DateCreated")
+ .HasColumnType("TEXT");
+
+ b.Property("DateModified")
+ .HasColumnType("TEXT");
+
+ b.Property("FirstName")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ b.Property("LastName")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.ToTable("Authors");
+ });
+
+ modelBuilder.Entity("CleanModelContextProtocol.Infrastructure.Databases.MovieReviews.Models.Movie", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("TEXT");
+
+ b.Property("DateCreated")
+ .HasColumnType("TEXT");
+
+ b.Property("DateModified")
+ .HasColumnType("TEXT");
+
+ b.Property("Title")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.ToTable("Movies");
+ });
+
+ modelBuilder.Entity("CleanModelContextProtocol.Infrastructure.Databases.MovieReviews.Models.Review", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("TEXT");
+
+ b.Property("DateCreated")
+ .HasColumnType("TEXT");
+
+ b.Property("DateModified")
+ .HasColumnType("TEXT");
+
+ b.Property("ReviewAuthorId")
+ .HasColumnType("TEXT");
+
+ b.Property("ReviewedMovieId")
+ .HasColumnType("TEXT");
+
+ b.Property("Stars")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("ReviewAuthorId");
+
+ b.HasIndex("ReviewedMovieId");
+
+ b.ToTable("Reviews");
+ });
+
+ modelBuilder.Entity("CleanModelContextProtocol.Infrastructure.Databases.MovieReviews.Models.Review", b =>
+ {
+ b.HasOne("CleanModelContextProtocol.Infrastructure.Databases.MovieReviews.Models.Author", "ReviewAuthor")
+ .WithMany("Reviews")
+ .HasForeignKey("ReviewAuthorId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.HasOne("CleanModelContextProtocol.Infrastructure.Databases.MovieReviews.Models.Movie", "ReviewedMovie")
+ .WithMany("Reviews")
+ .HasForeignKey("ReviewedMovieId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("ReviewAuthor");
+
+ b.Navigation("ReviewedMovie");
+ });
+
+ modelBuilder.Entity("CleanModelContextProtocol.Infrastructure.Databases.MovieReviews.Models.Author", b =>
+ {
+ b.Navigation("Reviews");
+ });
+
+ modelBuilder.Entity("CleanModelContextProtocol.Infrastructure.Databases.MovieReviews.Models.Movie", b =>
+ {
+ b.Navigation("Reviews");
+ });
+#pragma warning restore 612, 618
+ }
+ }
+}
diff --git a/src/Infrastructure/Databases/MovieReviews/Migrations/20261028000000_InitialCreate.cs b/src/Infrastructure/Databases/MovieReviews/Migrations/20261028000000_InitialCreate.cs
new file mode 100644
index 0000000..3356e0d
--- /dev/null
+++ b/src/Infrastructure/Databases/MovieReviews/Migrations/20261028000000_InitialCreate.cs
@@ -0,0 +1,96 @@
+//
+using System;
+using Microsoft.EntityFrameworkCore.Migrations;
+
+#nullable disable
+
+namespace CleanModelContextProtocol.Infrastructure.Databases.MovieReviews.Migrations
+{
+ ///
+ public partial class InitialCreate : Migration
+ {
+ ///
+ protected override void Up(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.CreateTable(
+ name: "Authors",
+ columns: table => new
+ {
+ Id = table.Column(type: "TEXT", nullable: false),
+ FirstName = table.Column(type: "TEXT", nullable: false),
+ LastName = table.Column(type: "TEXT", nullable: false),
+ DateCreated = table.Column(type: "TEXT", nullable: false),
+ DateModified = table.Column(type: "TEXT", nullable: false)
+ },
+ constraints: table =>
+ {
+ table.PrimaryKey("PK_Authors", x => x.Id);
+ });
+
+ migrationBuilder.CreateTable(
+ name: "Movies",
+ columns: table => new
+ {
+ Id = table.Column(type: "TEXT", nullable: false),
+ Title = table.Column(type: "TEXT", nullable: false),
+ DateCreated = table.Column(type: "TEXT", nullable: false),
+ DateModified = table.Column(type: "TEXT", nullable: false)
+ },
+ constraints: table =>
+ {
+ table.PrimaryKey("PK_Movies", x => x.Id);
+ });
+
+ migrationBuilder.CreateTable(
+ name: "Reviews",
+ columns: table => new
+ {
+ Id = table.Column(type: "TEXT", nullable: false),
+ Stars = table.Column(type: "INTEGER", nullable: false),
+ ReviewedMovieId = table.Column(type: "TEXT", nullable: false),
+ ReviewAuthorId = table.Column(type: "TEXT", nullable: false),
+ DateCreated = table.Column(type: "TEXT", nullable: false),
+ DateModified = table.Column(type: "TEXT", nullable: false)
+ },
+ constraints: table =>
+ {
+ table.PrimaryKey("PK_Reviews", x => x.Id);
+ table.ForeignKey(
+ name: "FK_Reviews_Authors_ReviewAuthorId",
+ column: x => x.ReviewAuthorId,
+ principalTable: "Authors",
+ principalColumn: "Id",
+ onDelete: ReferentialAction.Cascade);
+ table.ForeignKey(
+ name: "FK_Reviews_Movies_ReviewedMovieId",
+ column: x => x.ReviewedMovieId,
+ principalTable: "Movies",
+ principalColumn: "Id",
+ onDelete: ReferentialAction.Cascade);
+ });
+
+ migrationBuilder.CreateIndex(
+ name: "IX_Reviews_ReviewAuthorId",
+ table: "Reviews",
+ column: "ReviewAuthorId");
+
+ migrationBuilder.CreateIndex(
+ name: "IX_Reviews_ReviewedMovieId",
+ table: "Reviews",
+ column: "ReviewedMovieId");
+ }
+
+ ///
+ protected override void Down(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.DropTable(
+ name: "Reviews");
+
+ migrationBuilder.DropTable(
+ name: "Authors");
+
+ migrationBuilder.DropTable(
+ name: "Movies");
+ }
+ }
+}
diff --git a/src/Infrastructure/Databases/MovieReviews/Migrations/MovieReviewsDbContextModelSnapshot.cs b/src/Infrastructure/Databases/MovieReviews/Migrations/MovieReviewsDbContextModelSnapshot.cs
new file mode 100644
index 0000000..3552e71
--- /dev/null
+++ b/src/Infrastructure/Databases/MovieReviews/Migrations/MovieReviewsDbContextModelSnapshot.cs
@@ -0,0 +1,127 @@
+//
+using System;
+using CleanModelContextProtocol.Infrastructure.Databases.MovieReviews;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Infrastructure;
+using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
+
+#nullable disable
+
+namespace CleanModelContextProtocol.Infrastructure.Databases.MovieReviews.Migrations
+{
+ [DbContext(typeof(MovieReviewsDbContext))]
+ partial class MovieReviewsDbContextModelSnapshot : ModelSnapshot
+ {
+ protected override void BuildModel(ModelBuilder modelBuilder)
+ {
+#pragma warning disable 612, 618
+ modelBuilder.HasAnnotation("ProductVersion", "10.0.14");
+
+ modelBuilder.Entity("CleanModelContextProtocol.Infrastructure.Databases.MovieReviews.Models.Author", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("TEXT");
+
+ b.Property("DateCreated")
+ .HasColumnType("TEXT");
+
+ b.Property("DateModified")
+ .HasColumnType("TEXT");
+
+ b.Property("FirstName")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ b.Property("LastName")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.ToTable("Authors");
+ });
+
+ modelBuilder.Entity("CleanModelContextProtocol.Infrastructure.Databases.MovieReviews.Models.Movie", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("TEXT");
+
+ b.Property("DateCreated")
+ .HasColumnType("TEXT");
+
+ b.Property("DateModified")
+ .HasColumnType("TEXT");
+
+ b.Property("Title")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.ToTable("Movies");
+ });
+
+ modelBuilder.Entity("CleanModelContextProtocol.Infrastructure.Databases.MovieReviews.Models.Review", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("TEXT");
+
+ b.Property("DateCreated")
+ .HasColumnType("TEXT");
+
+ b.Property("DateModified")
+ .HasColumnType("TEXT");
+
+ b.Property("ReviewAuthorId")
+ .HasColumnType("TEXT");
+
+ b.Property("ReviewedMovieId")
+ .HasColumnType("TEXT");
+
+ b.Property("Stars")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("ReviewAuthorId");
+
+ b.HasIndex("ReviewedMovieId");
+
+ b.ToTable("Reviews");
+ });
+
+ modelBuilder.Entity("CleanModelContextProtocol.Infrastructure.Databases.MovieReviews.Models.Review", b =>
+ {
+ b.HasOne("CleanModelContextProtocol.Infrastructure.Databases.MovieReviews.Models.Author", "ReviewAuthor")
+ .WithMany("Reviews")
+ .HasForeignKey("ReviewAuthorId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.HasOne("CleanModelContextProtocol.Infrastructure.Databases.MovieReviews.Models.Movie", "ReviewedMovie")
+ .WithMany("Reviews")
+ .HasForeignKey("ReviewedMovieId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("ReviewAuthor");
+
+ b.Navigation("ReviewedMovie");
+ });
+
+ modelBuilder.Entity("CleanModelContextProtocol.Infrastructure.Databases.MovieReviews.Models.Author", b =>
+ {
+ b.Navigation("Reviews");
+ });
+
+ modelBuilder.Entity("CleanModelContextProtocol.Infrastructure.Databases.MovieReviews.Models.Movie", b =>
+ {
+ b.Navigation("Reviews");
+ });
+#pragma warning restore 612, 618
+ }
+ }
+}
diff --git a/src/Infrastructure/Databases/MovieReviews/Models/Author.cs b/src/Infrastructure/Databases/MovieReviews/Models/Author.cs
index f1dda04..8d8ef9d 100644
--- a/src/Infrastructure/Databases/MovieReviews/Models/Author.cs
+++ b/src/Infrastructure/Databases/MovieReviews/Models/Author.cs
@@ -5,9 +5,9 @@ namespace CleanModelContextProtocol.Infrastructure.Databases.MovieReviews.Models
[ExcludeFromCodeCoverage]
internal record Author : Entity
{
- public string FirstName { get; init; }
+ public required string FirstName { get; init; }
- public string LastName { get; init; }
+ public required string LastName { get; init; }
- public ICollection Reviews { get; init; }
+ public ICollection Reviews { get; init; } = [];
}
diff --git a/src/Infrastructure/Databases/MovieReviews/Models/Movie.cs b/src/Infrastructure/Databases/MovieReviews/Models/Movie.cs
index fdd298c..0daf229 100644
--- a/src/Infrastructure/Databases/MovieReviews/Models/Movie.cs
+++ b/src/Infrastructure/Databases/MovieReviews/Models/Movie.cs
@@ -5,7 +5,7 @@ namespace CleanModelContextProtocol.Infrastructure.Databases.MovieReviews.Models
[ExcludeFromCodeCoverage]
internal record Movie : Entity
{
- public string Title { get; init; }
+ public required string Title { get; init; }
- public ICollection Reviews { get; init; }
+ public ICollection Reviews { get; init; } = [];
}
diff --git a/src/Infrastructure/Databases/MovieReviews/Models/Review.cs b/src/Infrastructure/Databases/MovieReviews/Models/Review.cs
index 6e415a5..9aa944f 100644
--- a/src/Infrastructure/Databases/MovieReviews/Models/Review.cs
+++ b/src/Infrastructure/Databases/MovieReviews/Models/Review.cs
@@ -11,10 +11,10 @@ internal record Review : Entity
[ForeignKey("ReviewedMovie")]
public Guid ReviewedMovieId { get; set; }
- public Movie ReviewedMovie { get; init; }
+ public Movie ReviewedMovie { get; init; } = null!;
[ForeignKey("ReviewAuthor")]
public Guid ReviewAuthorId { get; set; }
- public Author ReviewAuthor { get; init; }
+ public Author ReviewAuthor { get; init; } = null!;
}
diff --git a/src/Infrastructure/Databases/MovieReviews/MovieReviewsDatabase.cs b/src/Infrastructure/Databases/MovieReviews/MovieReviewsDatabase.cs
new file mode 100644
index 0000000..14f6ba4
--- /dev/null
+++ b/src/Infrastructure/Databases/MovieReviews/MovieReviewsDatabase.cs
@@ -0,0 +1,34 @@
+namespace CleanModelContextProtocol.Infrastructure.Databases.MovieReviews;
+
+using Microsoft.Data.Sqlite;
+
+///
+/// The connection details of the movie reviews database.
+///
+///
+/// A shared in-memory SQLite database, such as Data Source=Movies;Mode=Memory;Cache=Shared, only lives while a
+/// connection to it is open, so this keeps one open for as long as the application runs.
+///
+internal sealed class MovieReviewsDatabase(string connectionString) : IDisposable
+{
+ private SqliteConnection? keepAlive;
+
+ public string ConnectionString { get; } = connectionString;
+
+ public bool IsInMemory => new SqliteConnectionStringBuilder(this.ConnectionString).Mode == SqliteOpenMode.Memory;
+
+ public void KeepAlive()
+ {
+ if (this.IsInMemory && this.keepAlive is null)
+ {
+ this.keepAlive = new SqliteConnection(this.ConnectionString);
+ this.keepAlive.Open();
+ }
+ }
+
+ public void Dispose()
+ {
+ this.keepAlive?.Dispose();
+ this.keepAlive = null;
+ }
+}
diff --git a/src/Infrastructure/Databases/MovieReviews/MovieReviewsDbContext.cs b/src/Infrastructure/Databases/MovieReviews/MovieReviewsDbContext.cs
index 4e2d69c..24cce2e 100644
--- a/src/Infrastructure/Databases/MovieReviews/MovieReviewsDbContext.cs
+++ b/src/Infrastructure/Databases/MovieReviews/MovieReviewsDbContext.cs
@@ -6,9 +6,9 @@ namespace CleanModelContextProtocol.Infrastructure.Databases.MovieReviews;
internal class MovieReviewsDbContext(DbContextOptions options) : DbContext(options)
{
- public DbSet Authors { get; set; }
- public DbSet Movies { get; set; }
- public DbSet Reviews { get; set; }
+ public DbSet Authors => this.Set();
+ public DbSet Movies => this.Set();
+ public DbSet Reviews => this.Set();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
diff --git a/src/Infrastructure/Databases/MovieReviews/MovieReviewsDbContextFactory.cs b/src/Infrastructure/Databases/MovieReviews/MovieReviewsDbContextFactory.cs
new file mode 100644
index 0000000..c8a8f47
--- /dev/null
+++ b/src/Infrastructure/Databases/MovieReviews/MovieReviewsDbContextFactory.cs
@@ -0,0 +1,22 @@
+namespace CleanModelContextProtocol.Infrastructure.Databases.MovieReviews;
+
+using System.Diagnostics.CodeAnalysis;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Design;
+
+///
+/// Lets the EF Core tools create the context, for example to add a migration:
+/// dotnet ef migrations add Name --project src/Infrastructure --output-dir Databases/MovieReviews/Migrations.
+///
+[ExcludeFromCodeCoverage]
+internal class MovieReviewsDbContextFactory : IDesignTimeDbContextFactory
+{
+ public MovieReviewsDbContext CreateDbContext(string[] args)
+ {
+ var options = new DbContextOptionsBuilder()
+ .UseSqlite(DependencyInjection.DefaultConnectionString)
+ .Options;
+
+ return new MovieReviewsDbContext(options);
+ }
+}
diff --git a/src/Infrastructure/DependencyInjection.cs b/src/Infrastructure/DependencyInjection.cs
index 211ee9b..1816bc0 100644
--- a/src/Infrastructure/DependencyInjection.cs
+++ b/src/Infrastructure/DependencyInjection.cs
@@ -5,29 +5,53 @@ namespace CleanModelContextProtocol.Infrastructure;
using Application.Movies;
using Application.Reviews;
using Databases.MovieReviews;
+using Databases.MovieReviews.Extensions;
using Databases.MovieReviews.Mapping;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
public static class DependencyInjection
{
- public static IServiceCollection AddInfrastructure(this IServiceCollection services)
+ /// The connection string used when none is configured.
+ public const string DefaultConnectionString = "Data Source=movie-reviews.db";
+
+ public static IServiceCollection AddInfrastructure(this IServiceCollection services, string? connectionString = null)
{
- _ = services.AddDbContext(options =>
- options.UseInMemoryDatabase($"Movies-{Guid.NewGuid()}"), ServiceLifetime.Singleton);
+ var database = new MovieReviewsDatabase(string.IsNullOrWhiteSpace(connectionString) ? DefaultConnectionString : connectionString);
+
+ _ = services.AddSingleton(database);
+ _ = services.AddDbContext(options => options.UseSqlite(database.ConnectionString));
_ = services.AddSingleton();
- _ = services.AddSingleton();
+ _ = services.AddScoped();
- _ = services.AddSingleton(p =>
+ _ = services.AddScoped(p =>
p.GetRequiredService());
- _ = services.AddSingleton(x =>
+ _ = services.AddScoped(x =>
x.GetRequiredService());
- _ = services.AddSingleton(x =>
+ _ = services.AddScoped(x =>
x.GetRequiredService());
_ = services.AddSingleton(TimeProvider.System);
return services;
}
+
+ ///
+ /// Creates or upgrades the database with the migrations, then adds the sample data when it is empty.
+ /// Call it once at startup, before the first request.
+ ///
+ public static IServiceProvider InitialiseInfrastructure(this IServiceProvider services)
+ {
+ services.GetRequiredService().KeepAlive();
+
+ using var scope = services.CreateScope();
+
+ var context = scope.ServiceProvider.GetRequiredService();
+
+ context.Database.Migrate();
+ _ = context.AddData();
+
+ return services;
+ }
}
diff --git a/src/Infrastructure/Infrastructure.csproj b/src/Infrastructure/Infrastructure.csproj
index ada2a82..2f60570 100644
--- a/src/Infrastructure/Infrastructure.csproj
+++ b/src/Infrastructure/Infrastructure.csproj
@@ -7,7 +7,11 @@
-
+
+ all
+ runtime; build; native; contentfiles; analyzers; buildtransitive
+
+
diff --git a/src/Presentation/Authentication/AuthenticationSettings.cs b/src/Presentation/Authentication/AuthenticationSettings.cs
index e3eecd7..426fdb6 100644
--- a/src/Presentation/Authentication/AuthenticationSettings.cs
+++ b/src/Presentation/Authentication/AuthenticationSettings.cs
@@ -10,10 +10,10 @@ public class AuthenticationSettings
public const string SectionName = "Authentication";
/// The OAuth authorization server that issues access tokens, such as https://login.example.com.
- public string Authority { get; init; }
+ public string? Authority { get; init; }
/// The audience access tokens must be issued for. This is usually the server's own URL.
- public string Audience { get; init; }
+ public string? Audience { get; init; }
/// The scopes clients should ask for, published in the protected resource metadata.
public List Scopes { get; init; } = [];
diff --git a/src/Presentation/Completions/CompletionHandler.cs b/src/Presentation/Completions/CompletionHandler.cs
index 7d690ec..0bd0ec0 100644
--- a/src/Presentation/Completions/CompletionHandler.cs
+++ b/src/Presentation/Completions/CompletionHandler.cs
@@ -17,10 +17,10 @@ public static class CompletionHandler
public static async ValueTask Handle(RequestContext context, CancellationToken cancellationToken)
{
- return await Complete(context.Services.GetRequiredService(), context.Params, cancellationToken);
+ return await Complete(context.Services!.GetRequiredService(), context.Params, cancellationToken);
}
- public static async Task Complete(ISender sender, CompleteRequestParams request, CancellationToken cancellationToken)
+ public static async Task Complete(ISender sender, CompleteRequestParams? request, CancellationToken cancellationToken)
{
var argument = request?.Argument;
@@ -33,7 +33,7 @@ public static async Task Complete(ISender sender, CompleteReques
{
case "movieTitle" or "firstMovieTitle" or "secondMovieTitle":
{
- var page = await sender.Send(new MovieQueries.SearchMovies.SearchMoviesQuery
+ var page = await sender.Send(new MovieQueries.GetMovies.GetMoviesQuery
{
Query = argument.Value,
Limit = Paging.MaxLimit
@@ -44,7 +44,7 @@ public static async Task Complete(ISender sender, CompleteReques
case "authorName":
{
- var page = await sender.Send(new AuthorQueries.SearchAuthors.SearchAuthorsQuery
+ var page = await sender.Send(new AuthorQueries.GetAuthors.GetAuthorsQuery
{
Query = argument.Value,
Limit = Paging.MaxLimit
diff --git a/src/Presentation/Errors/ProtocolErrorFilter.cs b/src/Presentation/Errors/ProtocolErrorFilter.cs
index 98b6ebd..f5675b7 100644
--- a/src/Presentation/Errors/ProtocolErrorFilter.cs
+++ b/src/Presentation/Errors/ProtocolErrorFilter.cs
@@ -25,7 +25,7 @@ public static McpRequestHandler Filter(McpRe
};
}
- public static McpProtocolException ToProtocolException(Exception exception)
+ public static McpProtocolException? ToProtocolException(Exception exception)
{
return exception switch
{
diff --git a/src/Presentation/Extensions/WebApplicationBuilderExtensions.cs b/src/Presentation/Extensions/WebApplicationBuilderExtensions.cs
index f745d2c..0b50b9c 100644
--- a/src/Presentation/Extensions/WebApplicationBuilderExtensions.cs
+++ b/src/Presentation/Extensions/WebApplicationBuilderExtensions.cs
@@ -36,7 +36,7 @@ public static WebApplicationBuilder ConfigureApplicationBuilder(this WebApplicat
#region Project Dependencies
_ = builder.Services.AddMediator(options => options.ServiceLifetime = ServiceLifetime.Scoped);
- _ = builder.Services.AddInfrastructure();
+ _ = builder.Services.AddInfrastructure(builder.Configuration.GetConnectionString("MovieReviews"));
_ = builder.Services.AddApplication();
#endregion Project Dependencies
@@ -62,7 +62,7 @@ public static WebApplicationBuilder ConfigureApplicationBuilder(this WebApplicat
.AddMcp(options => options.ResourceMetadata = new()
{
Resource = authentication.Audience,
- AuthorizationServers = [authentication.Authority],
+ AuthorizationServers = [authentication.Authority!],
ScopesSupported = authentication.Scopes,
ResourceName = "Clean Model Context Protocol"
});
diff --git a/src/Presentation/Extensions/WebApplicationExtensions.cs b/src/Presentation/Extensions/WebApplicationExtensions.cs
index 0fe8b1f..417bcbd 100644
--- a/src/Presentation/Extensions/WebApplicationExtensions.cs
+++ b/src/Presentation/Extensions/WebApplicationExtensions.cs
@@ -2,6 +2,7 @@ namespace CleanModelContextProtocol.Presentation.Extensions;
using System.Diagnostics.CodeAnalysis;
using CleanModelContextProtocol.Presentation.Authentication;
+using Infrastructure;
using Microsoft.AspNetCore.Builder;
using Serilog;
@@ -10,6 +11,12 @@ public static class WebApplicationExtensions
{
public static WebApplication ConfigureApplication(this WebApplication app)
{
+ #region Database
+
+ _ = app.Services.InitialiseInfrastructure();
+
+ #endregion Database
+
#region Logging
_ = app.UseSerilogRequestLogging();
diff --git a/src/Presentation/Models/AuthorResult.cs b/src/Presentation/Models/AuthorResult.cs
index b675d1c..f940891 100644
--- a/src/Presentation/Models/AuthorResult.cs
+++ b/src/Presentation/Models/AuthorResult.cs
@@ -15,4 +15,4 @@ public record AuthorResult(
[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);
+ [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
index c857ba1..59f4dfb 100644
--- a/src/Presentation/Models/MovieResult.cs
+++ b/src/Presentation/Models/MovieResult.cs
@@ -15,4 +15,4 @@ public record MovieResult(
[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);
+ [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
index cd7c3dd..9cf0922 100644
--- a/src/Presentation/Models/ResultMapper.cs
+++ b/src/Presentation/Models/ResultMapper.cs
@@ -34,7 +34,7 @@ public static AuthorResult ToResult(this Author author, bool includeReviews)
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)
+ public static ReviewResult ToResult(this Review review, ReviewedMovie? movie = null, ReviewAuthor? author = null)
{
movie = review.ReviewedMovie ?? movie;
author = review.ReviewAuthor ?? author;
@@ -50,7 +50,9 @@ public static ReviewResult ToResult(this Review review, ReviewedMovie movie = nu
public static ResultPage ToResult(this Page page, Func map)
{
- return new ResultPage([.. page.Items.Select(map)], page.TotalCount, page.NextCursor);
+ var nextOffset = page.Offset + page.Items.Count;
+
+ return new ResultPage([.. page.Items.Select(map)], page.TotalCount, nextOffset < page.TotalCount ? nextOffset : null);
}
private static string FullName(string firstName, string lastName)
diff --git a/src/Presentation/Models/ResultPage.cs b/src/Presentation/Models/ResultPage.cs
index 1fddd91..5d09266 100644
--- a/src/Presentation/Models/ResultPage.cs
+++ b/src/Presentation/Models/ResultPage.cs
@@ -3,13 +3,13 @@ namespace CleanModelContextProtocol.Presentation.Models;
using System.ComponentModel;
///
-/// One page of results from a search tool.
+/// One page of results from a list or 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.
+/// Pass this as the offset 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);
+ [property: Description("Pass this as the offset to get the next page. Null when this is the last page.")] int? NextOffset);
diff --git a/src/Presentation/Models/ReviewResult.cs b/src/Presentation/Models/ReviewResult.cs
index 8864490..9f89c8c 100644
--- a/src/Presentation/Models/ReviewResult.cs
+++ b/src/Presentation/Models/ReviewResult.cs
@@ -15,6 +15,6 @@ 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 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);
+ [property: Description("The full name of the author who wrote the review.")] string? AuthorName);
diff --git a/src/Presentation/Prompts/MoviePrompts.cs b/src/Presentation/Prompts/MoviePrompts.cs
index 9a3864f..18ad593 100644
--- a/src/Presentation/Prompts/MoviePrompts.cs
+++ b/src/Presentation/Prompts/MoviePrompts.cs
@@ -15,9 +15,10 @@ public static class MoviePrompts
[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)
+ [Description("The movie's title, or part of it.")] string movieTitle,
+ CancellationToken cancellationToken)
{
- var movie = await FindMovie(sender, movieTitle);
+ var movie = await FindMovie(sender, movieTitle, cancellationToken);
var messages = new List
{
@@ -45,10 +46,11 @@ public static async Task SummariseMovieReception(
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)
+ [Description("The second movie's title, or part of it.")] string secondMovieTitle,
+ CancellationToken cancellationToken)
{
- var first = await FindMovie(sender, firstMovieTitle);
- var second = await FindMovie(sender, secondMovieTitle);
+ var first = await FindMovie(sender, firstMovieTitle, cancellationToken);
+ var second = await FindMovie(sender, secondMovieTitle, cancellationToken);
var messages = new List
{
@@ -88,13 +90,13 @@ public static GetPromptResult ReviewMovie(
};
}
- private static async Task FindMovie(ISender sender, string title)
+ private static async Task FindMovie(ISender sender, string? title, CancellationToken cancellationToken)
{
- var page = await sender.Send(new Queries.SearchMovies.SearchMoviesQuery
+ var page = await sender.Send(new Queries.GetMovies.GetMoviesQuery
{
Query = title,
Limit = 5
- });
+ }, cancellationToken);
var movie = page.Items.FirstOrDefault(m => string.Equals(m.Title, title?.Trim(), StringComparison.OrdinalIgnoreCase))
?? (page.TotalCount == 1 ? page.Items[0] : null);
diff --git a/src/Presentation/Resources/AuthorResources.cs b/src/Presentation/Resources/AuthorResources.cs
index 6cca893..45a9f5d 100644
--- a/src/Presentation/Resources/AuthorResources.cs
+++ b/src/Presentation/Resources/AuthorResources.cs
@@ -14,12 +14,13 @@ public static class AuthorResources
[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)
+ [Description("The author's id (a GUID).")] Guid authorId,
+ CancellationToken cancellationToken)
{
var author = await sender.Send(new Queries.GetAuthorById.GetAuthorByIdQuery
{
Id = authorId
- });
+ }, cancellationToken);
return McpSerializer.Serialize(author.ToResult(includeReviews: true));
}
diff --git a/src/Presentation/Resources/MovieResources.cs b/src/Presentation/Resources/MovieResources.cs
index d4887cf..1e843c2 100644
--- a/src/Presentation/Resources/MovieResources.cs
+++ b/src/Presentation/Resources/MovieResources.cs
@@ -14,12 +14,13 @@ public static class MovieResources
[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)
+ [Description("The movie's id (a GUID).")] Guid movieId,
+ CancellationToken cancellationToken)
{
var movie = await sender.Send(new Queries.GetMovieById.GetMovieByIdQuery
{
Id = movieId
- });
+ }, cancellationToken);
return McpSerializer.Serialize(movie.ToResult(includeReviews: true));
}
diff --git a/src/Presentation/Resources/ReviewResources.cs b/src/Presentation/Resources/ReviewResources.cs
index aa14e9c..4ce2055 100644
--- a/src/Presentation/Resources/ReviewResources.cs
+++ b/src/Presentation/Resources/ReviewResources.cs
@@ -14,12 +14,13 @@ public static class ReviewResources
[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)
+ [Description("The review's id (a GUID).")] Guid reviewId,
+ CancellationToken cancellationToken)
{
var review = await sender.Send(new Queries.GetReviewById.GetReviewByIdQuery
{
Id = reviewId
- });
+ }, cancellationToken);
return McpSerializer.Serialize(review.ToResult());
}
diff --git a/src/Presentation/Resources/VersionResources.cs b/src/Presentation/Resources/VersionResources.cs
index 37fb428..6dcf6fd 100644
--- a/src/Presentation/Resources/VersionResources.cs
+++ b/src/Presentation/Resources/VersionResources.cs
@@ -11,8 +11,8 @@ 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)
+ public static async Task GetVersion(ISender sender, CancellationToken cancellationToken)
{
- return McpSerializer.Serialize(await sender.Send(new Queries.GetVersion.GetVersionQuery()));
+ return McpSerializer.Serialize(await sender.Send(new Queries.GetVersion.GetVersionQuery(), cancellationToken));
}
}
diff --git a/src/Presentation/Tools/AuthorTools.cs b/src/Presentation/Tools/AuthorTools.cs
index 5865514..0ac5bdf 100644
--- a/src/Presentation/Tools/AuthorTools.cs
+++ b/src/Presentation/Tools/AuthorTools.cs
@@ -15,17 +15,18 @@ public static class AuthorTools
"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("Part of the author's name, such as 'marie' or 'marie hirthe'. Leave empty to list every author.")] string query = null,
+ CancellationToken cancellationToken,
+ [Description("Part of the author's name, such as 'marie' or 'marie hirthe'. Leave empty to list every author.")] string? query = null,
+ [Description("The number of results to skip, 0 for the first page. Pass the nextOffset from a previous call to get the next page.")] int offset = 0,
[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)
{
- var page = await sender.Send(new Queries.SearchAuthors.SearchAuthorsQuery
+ var page = await sender.Send(new Queries.GetAuthors.GetAuthorsQuery
{
Query = query,
- Limit = limit,
- Cursor = cursor
- });
+ Offset = offset,
+ Limit = limit
+ }, cancellationToken);
return page.ToResult(a => a.ToResult(includeReviews));
}
diff --git a/src/Presentation/Tools/MovieTools.cs b/src/Presentation/Tools/MovieTools.cs
index fd53d54..4ae3187 100644
--- a/src/Presentation/Tools/MovieTools.cs
+++ b/src/Presentation/Tools/MovieTools.cs
@@ -15,17 +15,18 @@ public static class MovieTools
"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,
+ CancellationToken cancellationToken,
+ [Description("Words to look for in the title, such as 'matrix'. Leave empty to list every movie.")] string? query = null,
+ [Description("The number of results to skip, 0 for the first page. Pass the nextOffset from a previous call to get the next page.")] int offset = 0,
[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)
{
- var page = await sender.Send(new Queries.SearchMovies.SearchMoviesQuery
+ var page = await sender.Send(new Queries.GetMovies.GetMoviesQuery
{
Query = query,
- Limit = limit,
- Cursor = cursor
- });
+ Offset = offset,
+ Limit = limit
+ }, cancellationToken);
return page.ToResult(m => m.ToResult(includeReviews));
}
@@ -34,12 +35,13 @@ public static async Task> SearchMovies(
[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_search to find it.")] Guid movieId)
+ [Description("The movie's id (a GUID). Use movies_search to find it.")] Guid movieId,
+ CancellationToken cancellationToken)
{
var movie = await sender.Send(new Queries.GetMovieById.GetMovieByIdQuery
{
Id = movieId
- });
+ }, cancellationToken);
return movie.ToResult(includeReviews: true);
}
diff --git a/src/Presentation/Tools/ReviewTools.cs b/src/Presentation/Tools/ReviewTools.cs
index 6c931b1..5b24f2c 100644
--- a/src/Presentation/Tools/ReviewTools.cs
+++ b/src/Presentation/Tools/ReviewTools.cs
@@ -15,52 +15,54 @@ public static class ReviewTools
"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,
+ CancellationToken cancellationToken,
[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)
+ [Description("The number of results to skip, 0 for the first page. Pass the nextOffset from a previous call to get the next page.")] int offset = 0,
+ [Description("The most results to return, from 1 to 50.")] int limit = 10)
{
if (reviewId.HasValue)
{
var review = await sender.Send(new Queries.GetReviewById.GetReviewByIdQuery
{
Id = reviewId.Value
- });
+ }, cancellationToken);
return new ResultPage([review.ToResult()], 1, null);
}
- var page = await sender.Send(new Queries.SearchReviews.SearchReviewsQuery
+ var page = await sender.Send(new Queries.GetReviews.GetReviewsQuery
{
MovieId = movieId,
AuthorId = authorId,
- Limit = limit,
- Cursor = cursor
- });
+ Offset = offset,
+ Limit = limit
+ }, cancellationToken);
return page.ToResult(r => r.ToResult());
}
[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.")]
+ [Description("Create a review of a movie by an author with a star rating from 1 to 5, or pass a reviewId to change that " +
+ "review's stars. The movie and author of a review can't change. 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 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)
+ CancellationToken cancellationToken,
+ [Description("The id of the movie being reviewed, needed to create a review. Use movies_search to find it.")] Guid? movieId = null,
+ [Description("The id of the author writing the review, needed to create a review. Use authors_search to find it.")] Guid? authorId = null,
+ [Description("The id of an existing review to change the stars of. 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,
+ AuthorId = authorId ?? Guid.Empty,
+ MovieId = movieId ?? Guid.Empty,
Stars = stars
- });
+ }, cancellationToken);
return created.ToResult();
}
@@ -68,15 +70,13 @@ public static async Task WriteReview(
_ = await sender.Send(new Commands.UpdateReview.UpdateReviewCommand
{
Id = reviewId.Value,
- AuthorId = authorId,
- MovieId = movieId,
Stars = stars
- });
+ }, cancellationToken);
var updated = await sender.Send(new Queries.GetReviewById.GetReviewByIdQuery
{
Id = reviewId.Value
- });
+ }, cancellationToken);
return updated.ToResult();
}
@@ -85,12 +85,13 @@ public static async Task