Skip to content
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ The one deliberate break from Clean Architecture is that the Presentation projec
- Logging using [Serilog](https://github.com/serilog/serilog), with [Seq](https://datalust.co/seq) when running in Docker
- Mediator pattern using [Mediator](https://github.com/martinothamar/Mediator)
- Validation using [FluentValidation](https://github.com/FluentValidation/FluentValidation) in an Application pipeline behaviour
- Typed tool results published with an output schema and returned as structured content as well as JSON text
- Tool errors mapped from Application exceptions by a single call-tool filter, with messages that tell the agent how to recover
- Object mapping using [Mapperly](https://mapperly.riok.app)
- In-memory data using [Entity Framework Core](https://learn.microsoft.com/ef/core/providers/in-memory/) seeded with [Bogus](https://github.com/bchavez/Bogus)
Expand Down
17 changes: 7 additions & 10 deletions src/Presentation/Extensions/WebApplicationBuilderExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ namespace CleanModelContextProtocol.Presentation.Extensions;
using CleanModelContextProtocol.Presentation.Serialization;
using Infrastructure;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http.Json;
using Microsoft.Extensions.DependencyInjection;
using ModelContextProtocol;
using Serilog;

[ExcludeFromCodeCoverage]
Expand All @@ -34,15 +34,12 @@ public static WebApplicationBuilder ConfigureApplicationBuilder(this WebApplicat

#region Serialisation

_ = builder.Services.Configure<JsonOptions>(opt =>
var serializerOptions = new JsonSerializerOptions(McpJsonUtilities.DefaultOptions)
{
opt.SerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
opt.SerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
opt.SerializerOptions.PropertyNameCaseInsensitive = true;
opt.SerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
opt.SerializerOptions.Converters.Add(new JsonStringEnumConverter(JsonNamingPolicy.CamelCase));
opt.SerializerOptions.TypeInfoResolverChain.Insert(0, AppJsonSerializerContext.Default);
});
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
};
serializerOptions.TypeInfoResolverChain.Insert(0, AppJsonSerializerContext.Default);

#endregion Serialisation

Expand Down Expand Up @@ -85,7 +82,7 @@ A review links one author to one movie with a star rating from 1 (worst) to 5 (b
""";
})
.WithHttpTransport(options => options.Stateless = true)
.WithToolsFromAssembly()
.WithToolsFromAssembly(serializerOptions: serializerOptions)
.WithRequestFilters(filters => filters.AddCallToolFilter(ToolErrorFilter.Filter));

#endregion Model Context Protocol
Expand Down
12 changes: 12 additions & 0 deletions src/Presentation/Models/DeletedReview.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
namespace CleanModelContextProtocol.Presentation.Models;

using System.ComponentModel;

/// <summary>
/// The result of deleting a review.
/// </summary>
/// <param name="ReviewId">The id of the review that was deleted.</param>
/// <param name="Deleted">Whether the review was deleted.</param>
public record DeletedReview(
[property: Description("The id of the review that was deleted.")] Guid ReviewId,
[property: Description("Whether the review was deleted.")] bool Deleted);
2 changes: 2 additions & 0 deletions src/Presentation/Serialization/AppJsonSerializerContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ namespace CleanModelContextProtocol.Presentation.Serialization;
using Application.Movies.Entities;
using Application.Reviews.Entities;
using Application.Versions.Entities;
using CleanModelContextProtocol.Presentation.Models;

/// <summary>
/// JSON serialization context for compile-time source generation.
Expand All @@ -26,6 +27,7 @@ namespace CleanModelContextProtocol.Presentation.Serialization;
[JsonSerializable(typeof(ReviewedMovie))]
[JsonSerializable(typeof(Version))]
[JsonSerializable(typeof(List<Version>))]
[JsonSerializable(typeof(DeletedReview))]
public partial class AppJsonSerializerContext : JsonSerializerContext
{
}
18 changes: 8 additions & 10 deletions src/Presentation/Tools/AuthorTools.cs
Original file line number Diff line number Diff line change
@@ -1,33 +1,31 @@
namespace CleanModelContextProtocol.Presentation.Tools;

using System.ComponentModel;
using System.Text.Json;
using Mediator;
using ModelContextProtocol.Server;
using Entities = Application.Authors.Entities;
using Queries = Application.Authors.Queries;

[McpServerToolType]
public static class AuthorTools
{
[McpServerTool(Name = "authors_list", Title = "List authors", ReadOnly = true, Idempotent = true, OpenWorld = false)]
[McpServerTool(Name = "authors_list", Title = "List authors", ReadOnly = true, Idempotent = true, OpenWorld = false, UseStructuredContent = true)]
[Description("List every author who has written reviews, with their id, first and last name, and the reviews they have written. " +
"Use this to find an author's id before calling authors_get, reviews_create or reviews_update.")]
public static async Task<string> ListAuthors(ISender sender)
public static async Task<List<Entities.Author>> ListAuthors(ISender sender)
{
var result = await sender.Send(new Queries.GetAuthors.GetAuthorsQuery());

return JsonSerializer.Serialize(result);
return await sender.Send(new Queries.GetAuthors.GetAuthorsQuery());
}

[McpServerTool(Name = "authors_get", Title = "Get author", ReadOnly = true, Idempotent = true, OpenWorld = false)]
[McpServerTool(Name = "authors_get", Title = "Get author", ReadOnly = true, Idempotent = true, OpenWorld = false, UseStructuredContent = true)]
[Description("Get one author by id, including every review they have written and the movie each review is for.")]
public static async Task<string> GetAuthor(
public static async Task<Entities.Author> GetAuthor(
ISender sender,
[Description("The author's id (a GUID). Use authors_list to find it.")] Guid authorId)
{
return JsonSerializer.Serialize(await sender.Send(new Queries.GetAuthorById.GetAuthorByIdQuery
return await sender.Send(new Queries.GetAuthorById.GetAuthorByIdQuery
{
Id = authorId
}));
});
}
}
18 changes: 8 additions & 10 deletions src/Presentation/Tools/MovieTools.cs
Original file line number Diff line number Diff line change
@@ -1,33 +1,31 @@
namespace CleanModelContextProtocol.Presentation.Tools;

using System.ComponentModel;
using System.Text.Json;
using Mediator;
using ModelContextProtocol.Server;
using Entities = Application.Movies.Entities;
using Queries = Application.Movies.Queries;

[McpServerToolType]
public static class MovieTools
{
[McpServerTool(Name = "movies_list", Title = "List movies", ReadOnly = true, Idempotent = true, OpenWorld = false)]
[McpServerTool(Name = "movies_list", Title = "List movies", ReadOnly = true, Idempotent = true, OpenWorld = false, UseStructuredContent = true)]
[Description("List every movie with its id, title and reviews. " +
"Use this to find a movie's id before calling movies_get, reviews_create or reviews_update.")]
public static async Task<string> ListMovies(ISender sender)
public static async Task<List<Entities.Movie>> ListMovies(ISender sender)
{
var result = await sender.Send(new Queries.GetMovies.GetMoviesQuery());

return JsonSerializer.Serialize(result);
return await sender.Send(new Queries.GetMovies.GetMoviesQuery());
}

[McpServerTool(Name = "movies_get", Title = "Get movie", ReadOnly = true, Idempotent = true, OpenWorld = false)]
[McpServerTool(Name = "movies_get", Title = "Get movie", ReadOnly = true, Idempotent = true, OpenWorld = false, UseStructuredContent = true)]
[Description("Get one movie by id, including every review of it with the star rating and the author who wrote it.")]
public static async Task<string> GetMovie(
public static async Task<Entities.Movie> GetMovie(
ISender sender,
[Description("The movie's id (a GUID). Use movies_list to find it.")] Guid movieId)
{
return JsonSerializer.Serialize(await sender.Send(new Queries.GetMovieById.GetMovieByIdQuery
return await sender.Send(new Queries.GetMovieById.GetMovieByIdQuery
{
Id = movieId
}));
});
}
}
46 changes: 23 additions & 23 deletions src/Presentation/Tools/ReviewTools.cs
Original file line number Diff line number Diff line change
@@ -1,59 +1,56 @@
namespace CleanModelContextProtocol.Presentation.Tools;

using System.ComponentModel;
using System.Text.Json;
using CleanModelContextProtocol.Presentation.Models;
using Mediator;
using ModelContextProtocol.Server;
using Commands = Application.Reviews.Commands;
using Entities = Application.Reviews.Entities;
using Queries = Application.Reviews.Queries;

[McpServerToolType]
public static class ReviewTools
{
[McpServerTool(Name = "reviews_list", Title = "List reviews", ReadOnly = true, Idempotent = true, OpenWorld = false)]
[McpServerTool(Name = "reviews_list", Title = "List reviews", ReadOnly = true, Idempotent = true, OpenWorld = false, UseStructuredContent = true)]
[Description("List every review with its id, star rating (1 to 5), the movie it is for and the author who wrote it.")]
public static async Task<string> ListReviews(ISender sender)
public static async Task<List<Entities.Review>> ListReviews(ISender sender)
{
var result = await sender.Send(new Queries.GetReviews.GetReviewsQuery());

return JsonSerializer.Serialize(result);
return await sender.Send(new Queries.GetReviews.GetReviewsQuery());
}

[McpServerTool(Name = "reviews_get", Title = "Get review", ReadOnly = true, Idempotent = true, OpenWorld = false)]
[McpServerTool(Name = "reviews_get", Title = "Get review", ReadOnly = true, Idempotent = true, OpenWorld = false, UseStructuredContent = true)]
[Description("Get one review by id, with its star rating, the movie it is for and the author who wrote it.")]
public static async Task<string> GetReview(
public static async Task<Entities.Review> GetReview(
ISender sender,
[Description("The review's id (a GUID). Use reviews_list to find it.")] Guid reviewId)
{
return JsonSerializer.Serialize(await sender.Send(new Queries.GetReviewById.GetReviewByIdQuery
return await sender.Send(new Queries.GetReviewById.GetReviewByIdQuery
{
Id = reviewId
}));
});
}

[McpServerTool(Name = "reviews_create", Title = "Create review", ReadOnly = false, Destructive = false, Idempotent = false, OpenWorld = false)]
[McpServerTool(Name = "reviews_create", Title = "Create review", ReadOnly = false, Destructive = false, Idempotent = false, OpenWorld = false, UseStructuredContent = true)]
[Description("Create a review of a movie by an author with a star rating from 1 to 5, and return the new review. " +
"Each call creates another review, so don't retry a call that succeeded.")]
public static async Task<string> CreateReview(
public static async Task<Entities.Review> CreateReview(
ISender sender,
[Description("The id of the author writing the review. Use authors_list to find it.")] Guid authorId,
[Description("The id of the movie being reviewed. Use movies_list to find it.")] Guid movieId,
[Description("The star rating, a whole number from 1 (worst) to 5 (best).")] int stars)
{
var result = await sender.Send(new Commands.CreateReview.CreateReviewCommand
return await sender.Send(new Commands.CreateReview.CreateReviewCommand
{
AuthorId = authorId,
MovieId = movieId,
Stars = stars
});

return JsonSerializer.Serialize(result);
}

[McpServerTool(Name = "reviews_update", Title = "Update review", ReadOnly = false, Destructive = true, Idempotent = true, OpenWorld = false)]
[McpServerTool(Name = "reviews_update", Title = "Update review", ReadOnly = false, Destructive = true, Idempotent = true, OpenWorld = false, UseStructuredContent = true)]
[Description("Replace an existing review's author, movie and star rating. Every field is overwritten, " +
"so pass the current author and movie ids when you only want to change the stars.")]
public static async Task<string> UpdateReview(
"so pass the current author and movie ids when you only want to change the stars. Returns the updated review.")]
public static async Task<Entities.Review> UpdateReview(
ISender sender,
[Description("The id of the review to update. Use reviews_list to find it.")] Guid reviewId,
[Description("The id of the author writing the review. Use authors_list to find it.")] Guid authorId,
Expand All @@ -68,20 +65,23 @@ public static async Task<string> UpdateReview(
Stars = stars
});

return "Review updated successfully";
return await sender.Send(new Queries.GetReviewById.GetReviewByIdQuery
{
Id = reviewId
});
}

[McpServerTool(Name = "reviews_delete", Title = "Delete review", ReadOnly = false, Destructive = true, Idempotent = true, OpenWorld = false)]
[McpServerTool(Name = "reviews_delete", Title = "Delete review", ReadOnly = false, Destructive = true, Idempotent = true, OpenWorld = false, UseStructuredContent = true)]
[Description("Permanently delete a review. This can't be undone, so confirm with the user first.")]
public static async Task<string> DeleteReview(
public static async Task<DeletedReview> DeleteReview(
ISender sender,
[Description("The id of the review to delete. Use reviews_list to find it.")] Guid reviewId)
{
_ = await sender.Send(new Commands.DeleteReview.DeleteReviewCommand
var deleted = await sender.Send(new Commands.DeleteReview.DeleteReviewCommand
{
Id = reviewId
});

return "Review deleted successfully";
return new DeletedReview(reviewId, deleted);
}
}
14 changes: 4 additions & 10 deletions src/Presentation/Tools/VersionTools.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,16 @@ namespace CleanModelContextProtocol.Presentation.Tools;
using System.ComponentModel;
using Mediator;
using ModelContextProtocol.Server;
using Entities = Application.Versions.Entities;
using Queries = Application.Versions.Queries;

[McpServerToolType]
public static class VersionTools
{
[McpServerTool(Name = "server_get_version", Title = "Get server version", ReadOnly = true, Idempotent = true, OpenWorld = false)]
[McpServerTool(Name = "server_get_version", Title = "Get server version", ReadOnly = true, Idempotent = true, OpenWorld = false, UseStructuredContent = true)]
[Description("Get the version of this server: the file version and the informational version, which includes the commit it was built from.")]
public static async Task<string> GetVersion(ISender sender)
public static async Task<Entities.Version> GetVersion(ISender sender)
{
var result = await sender.Send(new Queries.GetVersion.GetVersionQuery());

return $"""
| Property | Value |
| --- | --- |
| File Version | {result.FileVersion} |
| Informational Version | {result.InformationalVersion} |
""";
return await sender.Send(new Queries.GetVersion.GetVersionQuery());
}
}
17 changes: 8 additions & 9 deletions tests/Presentation.Tests.Integration/Tools/ReviewToolTests.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
namespace CleanModelContextProtocol.Presentation.Tests.Integration.Tools;

using CleanModelContextProtocol.Presentation.Models;
using Extensions;
using ModelContextProtocol;
using ModelContextProtocol.Protocol;
Expand Down Expand Up @@ -121,7 +122,7 @@ public async Task CreateReview_ShouldReturn_Review()
}

[Fact]
public async Task UpdateReview_ShouldReturn_Success()
public async Task UpdateReview_ShouldReturn_Review()
{
// Arrange
var authorResult = await this.Client.CallToolAsync("authors_list");
Expand All @@ -148,12 +149,7 @@ public async Task UpdateReview_ShouldReturn_Success()
var text = result.Content.OfType<TextContentBlock>().First().Text;

// Assert
text.ShouldBe("Review updated successfully");

var validateResult = await this.Client.CallToolAsync("reviews_get",
new Dictionary<string, object> { ["reviewId"] = existingReview.Id });
var validateText = validateResult.Content.OfType<TextContentBlock>().First().Text;
var updatedReview = validateText.Deserialize<Entities.Review>();
var updatedReview = text.Deserialize<Entities.Review>();

_ = updatedReview.ShouldNotBeNull();

Expand All @@ -171,7 +167,7 @@ public async Task UpdateReview_ShouldReturn_Success()
}

[Fact]
public async Task DeleteReview_ShouldReturn_Success()
public async Task DeleteReview_ShouldReturn_Result()
{
// Arrange
var reviewsResult = await this.Client.CallToolAsync("reviews_list");
Expand All @@ -184,7 +180,10 @@ public async Task DeleteReview_ShouldReturn_Success()
var text = result.Content.OfType<TextContentBlock>().First().Text;

// Assert
text.ShouldBe("Review deleted successfully");
var deleted = text.Deserialize<DeletedReview>();

deleted.ReviewId.ShouldBe(existingReview.Id);
deleted.Deleted.ShouldBeTrue();

var validateResult = await this.Client.CallToolAsync("reviews_get",
new Dictionary<string, object> { ["reviewId"] = existingReview.Id });
Expand Down
2 changes: 2 additions & 0 deletions tests/Presentation.Tests.Integration/Tools/ToolListTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ public async Task ListTools_ShouldDescribe_Tool(string name, string title, bool
tool.Annotations.DestructiveHint.ShouldBe(destructive);
}

_ = tool.OutputSchema.ShouldNotBeNull();

foreach (var property in tool.InputSchema.GetProperty("properties").EnumerateObject())
{
property.Value.GetProperty("description").GetString().ShouldNotBeNullOrWhiteSpace();
Expand Down
14 changes: 9 additions & 5 deletions tests/Presentation.Tests.Integration/Tools/VersionToolTests.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
namespace CleanModelContextProtocol.Presentation.Tests.Integration.Tools;

using Extensions;
using ModelContextProtocol.Protocol;
using Shouldly;
using Xunit;
Expand All @@ -13,12 +14,15 @@ public async Task GetVersion_ShouldReturn_Version()
var result = await this.Client.CallToolAsync("server_get_version");
var text = result.Content.OfType<TextContentBlock>().First().Text;

var version = text.Deserialize<Application.Versions.Entities.Version>();

// Assert
_ = text.ShouldNotBeNull();
_ = text.ShouldBeOfType<string>();
_ = version.ShouldNotBeNull();

version.FileVersion.ShouldNotBeNullOrWhiteSpace();
version.InformationalVersion.ShouldNotBeNullOrWhiteSpace();

text.ShouldNotBeNullOrWhiteSpace();
text.ShouldContain("File Version");
text.ShouldContain("Informational Version");
_ = result.StructuredContent.ShouldNotBeNull();
result.StructuredContent.Value.GetProperty("fileVersion").GetString().ShouldBe(version.FileVersion);
}
}
Loading
Loading