Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,11 @@ updates:
patterns: ["*"]
multi-ecosystem-group: "monthly-dependencies"

- package-ecosystem: "docker-compose"
directory: "/"
patterns: ["*"]
multi-ecosystem-group: "monthly-dependencies"

- package-ecosystem: "github-actions"
directory: "/"
patterns: ["*"]
Expand Down
25 changes: 20 additions & 5 deletions .github/release.yml
Original file line number Diff line number Diff line change
@@ -1,11 +1,26 @@
changelog:
exclude:
labels:
- ignore-for-release
categories:
- title: Changes
- title: Breaking changes
labels:
- "*"
exclude:
labels:
- dependencies
- breaking-change
- title: New features
labels:
- enhancement
- title: Bug fixes
labels:
- bug
- title: Documentation
labels:
- documentation
- title: Build and pipeline
labels:
- build
- title: Dependencies
labels:
- dependencies
- title: Other changes
labels:
- "*"
6 changes: 5 additions & 1 deletion .github/workflows/build-pipeline.yml
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,10 @@ jobs:
with:
dotnet-version: '10.0.x'

- name: Format
id: format
run: dotnet format --verify-no-changes --verbosity diagnostic

- name: Pack
id: pack
run: |
Expand Down Expand Up @@ -290,7 +294,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
Expand Down
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -366,3 +366,9 @@ out/
.Trashes
ehthumbs.db
Thumbs.db

# SQLite databases and coverage reports
*.db
*.db-shm
*.db-wal
coverage.cobertura.xml
11 changes: 11 additions & 0 deletions Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,19 @@
<RootNamespace>CleanModelContextProtocol.$(AssemblyName)</RootNamespace>
<PlatformTarget>AnyCPU</PlatformTarget>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<EnableNETAnalyzers>true</EnableNETAnalyzers>
<LangVersion>latest</LangVersion>
</PropertyGroup>

<PropertyGroup>
<!-- The .editorconfig rules and the recommended analyzers are checked on every build, and any warning fails it. -->
<AnalysisLevel>latest-recommended</AnalysisLevel>
<EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<!-- Needed for IDE0005 (unused usings) to be reported. Missing XML comments aren't errors. -->
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<NoWarn>$(NoWarn);1591</NoWarn>
</PropertyGroup>

</Project>
33 changes: 33 additions & 0 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<Project>

<PropertyGroup>
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
</PropertyGroup>

<ItemGroup>
<PackageVersion Include="Bogus" Version="35.6.5" />
<PackageVersion Include="coverlet.msbuild" Version="10.1.0" />
<PackageVersion Include="FluentValidation.DependencyInjectionExtensions" Version="12.2.0" />
<PackageVersion Include="Mediator.Abstractions" Version="3.0.2" />
<PackageVersion Include="Mediator.SourceGenerator" Version="3.0.2" />
<PackageVersion Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.14" />
<PackageVersion Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.14" />
<PackageVersion Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.14" />
<PackageVersion Include="Microsoft.EntityFrameworkCore.Sqlite" Version="10.0.14" />
<PackageVersion Include="Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore" Version="10.0.14" />
<PackageVersion Include="Microsoft.Extensions.TimeProvider.Testing" Version="10.11.0" />
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="18.11.0" />
<PackageVersion Include="ModelContextProtocol.AspNetCore" Version="2.3.0" />
<PackageVersion Include="NSubstitute" Version="6.2.0" />
<PackageVersion Include="Riok.Mapperly" Version="4.3.1" />
<PackageVersion Include="Serilog.AspNetCore" Version="10.0.0" />
<PackageVersion Include="Serilog.Enrichers.Environment" Version="3.0.1" />
<PackageVersion Include="Serilog.Extensions.Hosting" Version="10.0.0" />
<PackageVersion Include="Serilog.Sinks.Console" Version="6.1.1" />
<PackageVersion Include="Serilog.Sinks.Seq" Version="9.1.0" />
<PackageVersion Include="Shouldly" Version="4.3.0" />
<PackageVersion Include="xunit" Version="2.9.3" />
<PackageVersion Include="xunit.runner.visualstudio" Version="4.0.1" />
</ItemGroup>

</Project>
14 changes: 11 additions & 3 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ ENV DOTNET_ENVIRONMENT=${ENVIRONMENT}
WORKDIR /sln

# Dotnet Restore
COPY ./*.sln ./NuGet.config ./Directory.Build.props ./
COPY ./*.sln ./NuGet.config ./Directory.Build.props ./Directory.Packages.props ./
COPY src/*/*.csproj ./
RUN for file in $(ls *.csproj); do mkdir -p src/${file%.*}/ && mv $file src/${file%.*}/; done
COPY tests/*/*.csproj ./
Expand All @@ -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 .
Expand All @@ -48,7 +48,15 @@ RUN dotnet publish ./src/**/Presentation.csproj --no-restore -c Release -v quiet

# Runtime Image
FROM ${BASE_IMAGE_REPO}/${BASE_IMAGE_RUNTIME}:${BASE_IMAGE_RUNTIME_TAG} AS run
WORKDIR /
WORKDIR /app
EXPOSE 8080
COPY --from=publish /sln/app .

# The database lives in /app/data, the only folder the non-root app user can write to.
RUN mkdir -p /app/data && chown $APP_UID /app/data
USER $APP_UID

HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
CMD wget -qO- http://localhost:8080/health/live || exit 1

ENTRYPOINT ["dotnet", "Presentation.dll"]
11 changes: 7 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,18 +87,21 @@ 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)
- Validation using [FluentValidation](https://github.com/FluentValidation/FluentValidation) in an Application pipeline behaviour
- Typed tool results published with an output schema and returned as structured content as well as JSON text
- 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) only when `Database:SeedSampleData` is on. Each test uses its own throwaway in-memory SQLite database, so tests never touch a real one or each other's data
- 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)
- Build rules in `Directory.Build.props`: code style and the recommended analyzers are checked on every build, warnings fail it, and package versions live in one place with [Central Package Management](https://learn.microsoft.com/nuget/consume-packages/central-package-management)
- CI with GitHub Actions: build and test, a `dotnet format` check, 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)
- Health checks at `/health/live` and `/health/ready`, using [ASP.NET Core health checks](https://learn.microsoft.com/aspnet/core/host-and-deploy/health-checks)
- Monthly grouped dependency updates using [Dependabot](https://docs.github.com/code-security/dependabot), including the pinned Seq image
- A Docker image that runs as a non-root user with a health check

## Related templates

Expand Down
6 changes: 5 additions & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ services:
- "8080:8080"
environment:
DOTNET_ENVIRONMENT: docker
volumes:
- movie-reviews-data:/app/data
networks:
- cleanmodelcontextprotocol_network
depends_on:
Expand All @@ -24,14 +26,16 @@ services:
depends_on:
- api
seq:
image: datalust/seq:latest
image: datalust/seq:2026.1.17473
ports:
- "5341:80"
environment:
ACCEPT_EULA: "Y"
SEQ_FIRSTRUN_NOAUTHENTICATION: "true"
networks:
- cleanmodelcontextprotocol_network
volumes:
movie-reviews-data:
networks:
cleanmodelcontextprotocol_network:
driver: bridge
20 changes: 20 additions & 0 deletions docs/RUN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. In Docker the file is `/app/data/movie-reviews.db`, on the `movie-reviews-data` volume, so it survives a restart. On startup the app applies any pending Entity Framework Core migrations. When `Database:SeedSampleData` is `true`, it also seeds the same sample data into an empty database. It's on in `appsettings.local.json` and `appsettings.docker.json` and off everywhere else, so a deployed copy never starts with fake data. Delete the file, or run `docker compose down -v`, 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 <Name> --project ./src/Infrastructure --output-dir Databases/MovieReviews/Migrations
```

## .NET CLI

`launchSettings.json` sets the ports, environment and logging, so one command is enough.
Expand All @@ -21,15 +32,24 @@ docker compose up -d --build
- App: <http://localhost:8080/mcp> (MCP endpoint, Streamable HTTP)
- MCP Inspector: <http://localhost:6274>. Flip the switch on the server card to connect, then open **Tools** to see every tool with its description and input schema and run it.
- Seq: <http://localhost:5341>
- Health checks: <http://localhost:8080/health/live> (the process is up) and <http://localhost:8080/health/ready> (the database can be reached). Both answer without a token. The image's `HEALTHCHECK` uses the live one.

The container runs as the image's non-root `app` user.

To shut the containers down:

``` bash
docker compose down
```

## HTTPS

Outside the `local` and `Development` environments the app sends an HSTS header and redirects HTTP to HTTPS. The container only listens on HTTP, so in production put it behind a proxy or load balancer that ends TLS, and set `ASPNETCORE_FORWARDEDHEADERS_ENABLED=true` so the app knows the original request was HTTPS.

## Tests

``` bash
dotnet test
```

The tests never touch `movie-reviews.db`. Each test builds its own in-memory SQLite database from the migrations and the same fixed seed, so no test can change what another one sees and the results are the same every time.
6 changes: 2 additions & 4 deletions src/Application/Application.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,11 @@

<PropertyGroup>
<IsPackable>false</IsPackable>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<NoWarn>$(NoWarn);1591</NoWarn>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="FluentValidation.DependencyInjectionExtensions" Version="12.2.0" />
<PackageReference Include="Mediator.Abstractions" Version="3.0.2" />
<PackageReference Include="FluentValidation.DependencyInjectionExtensions" />
<PackageReference Include="Mediator.Abstractions" />
</ItemGroup>

</Project>
2 changes: 1 addition & 1 deletion src/Application/Authors/Entities/Author.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,4 @@ namespace CleanModelContextProtocol.Application.Authors.Entities;
/// <param name="FirstName">The author's first name.</param>
/// <param name="LastName">The author's last name.</param>
/// <param name="Reviews">The reviews the author has written.</param>
public record Author(Guid Id, string FirstName, string LastName, ICollection<Review> Reviews = null);
public record Author(Guid Id, string FirstName, string LastName, ICollection<Review> Reviews);
11 changes: 11 additions & 0 deletions src/Application/Authors/Entities/AuthorSummary.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
namespace CleanModelContextProtocol.Application.Authors.Entities;

/// <summary>
/// An author in a list, with how many reviews they have written and their average star rating instead of the reviews themselves.
/// </summary>
/// <param name="Id">The unique identifier of the author.</param>
/// <param name="FirstName">The author's first name.</param>
/// <param name="LastName">The author's last name.</param>
/// <param name="ReviewCount">The number of reviews the author has written.</param>
/// <param name="AverageStars">The average star rating the author gives to one decimal place, or null when they have no reviews.</param>
public record AuthorSummary(Guid Id, string FirstName, string LastName, int ReviewCount, double? AverageStars);
15 changes: 6 additions & 9 deletions src/Application/Authors/IAuthorsRepository.cs
Original file line number Diff line number Diff line change
@@ -1,19 +1,16 @@
namespace CleanModelContextProtocol.Application.Authors;

using System.Threading.Tasks;
using Entities;

public interface IAuthorsRepository
{
public Task<List<Author>> GetAuthors(CancellationToken cancellationToken);

public Task<Author> GetAuthorById(Guid id, CancellationToken cancellationToken);

public Task<bool> AuthorExists(Guid id, CancellationToken cancellationToken);

public Task<(List<Author> Items, int TotalCount)> SearchAuthors(
string query,
public Task<(List<AuthorSummary> Items, int TotalCount)> GetAuthors(
string? query,
int offset,
int limit,
CancellationToken cancellationToken);

public Task<Author?> GetAuthorById(Guid id, CancellationToken cancellationToken);

public Task<bool> AuthorExists(Guid id, CancellationToken cancellationToken);
}
Original file line number Diff line number Diff line change
@@ -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<GetAuthorsQuery, List<Author>>
public class GetAuthorsHandler(IAuthorsRepository repository) : IRequestHandler<GetAuthorsQuery, Page<AuthorSummary>>
{
public async ValueTask<List<Author>> Handle(GetAuthorsQuery request, CancellationToken cancellationToken)
public async ValueTask<Page<AuthorSummary>> 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<AuthorSummary>(items, request.Offset, request.Limit, totalCount);
}
}
15 changes: 14 additions & 1 deletion src/Application/Authors/Queries/GetAuthors/GetAuthorsQuery.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,21 @@
namespace CleanModelContextProtocol.Application.Authors.Queries.GetAuthors;

using Common.Paging;
using Entities;
using Mediator;

public class GetAuthorsQuery : IRequest<List<Author>>
/// <summary>
/// Lists authors one page at a time, optionally only those whose name contains a search term. Each author comes with
/// their review count and average stars rather than their reviews, which <see cref="GetAuthorById.GetAuthorByIdQuery"/> returns.
/// </summary>
public class GetAuthorsQuery : IRequest<Page<AuthorSummary>>
{
/// <summary>The words to look for in the first, last or full name, ignoring case. Leave empty to list every author.</summary>
public string? Query { get; init; }

/// <summary>The number of results to skip, 0 for the first page.</summary>
public int Offset { get; init; }

/// <summary>The largest number of results to return, from 1 to 50.</summary>
public int Limit { get; init; } = Paging.DefaultLimit;
}
Original file line number Diff line number Diff line change
@@ -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<SearchAuthorsQuery>
public class GetAuthorsValidator : AbstractValidator<GetAuthorsQuery>
{
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();
}
}
Loading
Loading