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
7 changes: 4 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ dotnet new cleanmodelcontextprotocol --name {YOUR_SOLUTION_NAMESPACE} --author "
docker compose up -d
```

Then open the MCP endpoint (connect with an MCP client such as the [MCP Inspector](https://github.com/modelcontextprotocol/inspector)) at <http://localhost:8080>. See [docs/RUN.md](docs/RUN.md) for every way to run it.
Then open the [MCP Inspector](https://github.com/modelcontextprotocol/inspector) at <http://localhost:6274>. It's already pointed at the MCP endpoint (<http://localhost:8080/mcp>), so connect and open **Tools** to browse and run them. See [docs/RUN.md](docs/RUN.md) for every way to run it.

The `Dockerfile` has stages for testing, publishing and running, so you can build just the part you need. You can also stamp a version into the assembly.

Expand Down Expand Up @@ -79,11 +79,12 @@ The one deliberate break from Clean Architecture is that the Presentation projec

## Features

- MCP server using the [MCP C# SDK](https://github.com/modelcontextprotocol/csharp-sdk)
- MCP server using the [MCP C# SDK](https://github.com/modelcontextprotocol/csharp-sdk), stateless Streamable HTTP at `/mcp`
- Tools named by resource (`movies_list`, `reviews_create`) with titles, read-only, destructive and idempotent hints, and descriptions written for agents
- Logging using [Serilog](https://github.com/serilog/serilog), with [Seq](https://datalust.co/seq) when running in Docker
- Mediator pattern using [Mediator](https://github.com/martinothamar/Mediator)
- Validation using [FluentValidation](https://github.com/FluentValidation/FluentValidation) in an Application pipeline behaviour
- Tool errors mapped from Application exceptions by a single call-tool filter
- Tool errors mapped from Application exceptions by a single call-tool filter, with messages that tell the agent how to recover
- Object mapping using [Mapperly](https://mapperly.riok.app)
- In-memory data using [Entity Framework Core](https://learn.microsoft.com/ef/core/providers/in-memory/) seeded with [Bogus](https://github.com/bchavez/Bogus)
- Testing using [xUnit](https://xunit.net), [Shouldly](https://github.com/shouldly/shouldly) and [NSubstitute](https://github.com/nsubstitute/NSubstitute), with coverage from [Coverlet](https://github.com/coverlet-coverage/coverlet)
Expand Down
9 changes: 9 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,15 @@ services:
- cleanmodelcontextprotocol_network
depends_on:
- seq
inspector:
image: ghcr.io/modelcontextprotocol/inspector:2.12.0
command: ["--web", "--transport", "http", "--server-url", "http://api:8080/mcp"]
ports:
- "127.0.0.1:6274:6274"
networks:
- cleanmodelcontextprotocol_network
depends_on:
- api
seq:
image: datalust/seq:latest
ports:
Expand Down
5 changes: 3 additions & 2 deletions docs/RUN.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,14 @@ dotnet run --project ./src/Presentation

## Docker Compose

`docker-compose.yml` starts the app and a Seq container for logs.
`docker-compose.yml` starts the app, the [MCP Inspector](https://github.com/modelcontextprotocol/inspector) already pointed at it, and a Seq container for logs.

``` bash
docker compose up -d --build
```

- App: <http://localhost:8080> (MCP endpoint (connect with an MCP client such as the [MCP Inspector](https://github.com/modelcontextprotocol/inspector)))
- 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>

To shut the containers down:
Expand Down
22 changes: 18 additions & 4 deletions src/Presentation/Errors/ToolErrorFilter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,19 +20,19 @@ public static McpRequestHandler<CallToolRequestParams, CallToolResult> Filter(Mc
}
catch (Exception exception) when (exception is not OperationCanceledException)
{
return ToResult(exception);
return ToResult(exception, request?.Params?.Name);
}
};
}

public static CallToolResult ToResult(Exception exception)
public static CallToolResult ToResult(Exception exception, string toolName = null)
{
var message = exception switch
{
ValidationException validationException => "Validation Failed: " + string.Join(" ", validationException.Errors
.Select(e => $"{e.PropertyName}: {e.ErrorMessage}")
.Distinct()),
NotFoundException => $"Not Found: {exception.Message}",
.Distinct()) + " Correct the arguments and call the tool again.",
NotFoundException => $"Not Found: {exception.Message}{ListToolHint(toolName)}",
_ => "Error: An error occurred while processing your request."
};

Expand All @@ -42,4 +42,18 @@ public static CallToolResult ToResult(Exception exception)
Content = [new TextContentBlock { Text = message }]
};
}

private static string ListToolHint(string toolName)
{
if (toolName is null)
{
return string.Empty;
}

var separator = toolName.IndexOf('_');

return separator > 0
? $" Check the ids, using {toolName[..separator]}_list or the other list tools to find valid ones."
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed
: string.Empty;
}
}
24 changes: 13 additions & 11 deletions src/Presentation/Extensions/WebApplicationBuilderExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -61,28 +61,30 @@ public static WebApplicationBuilder ConfigureApplicationBuilder(this WebApplicat
{
options.ServerInfo = new()
{
Name = "Clean Model Context Protocol",
Description = "A demonstration of the Clean Model Context Protocol in a .NET application",
Title = "Clean Model Context Protocol - Presentation Layer",
Name = "clean-model-context-protocol",
Title = "Clean Model Context Protocol",
Description = "Movies, the authors who review them, and their star ratings, served by a Clean Architecture .NET MCP server.",
Version = assembly?.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion ?? string.Empty,
WebsiteUrl = "https://github.com/stphnwlsh/CleanModelContextProtocol",
Icons =
[
new()
{
Source = "images/Icon.png",
Source = "https://raw.githubusercontent.com/stphnwlsh/CleanModelContextProtocol/main/icon.png",
MimeType = "image/png"
}
],
};
options.ServerInstructions = "You are a helpful assistant for handling requests related to movies, " +
"authors, and reviews. Use the available tools to retrieve information about movies, authors, and " +
"reviews based on the queries you receive. Always ensure that your responses are accurate and relevant " +
"to the user's request. Return the full sets of data anc convert them into tabulated markdown formats " +
"for display where sensible. Some datasets involve a number of sub objects, please calculate a count of " +
"that data for better formatting.";
options.ServerInstructions = """
This server holds a catalogue of movies, the authors who review them, and their reviews.
A review links one author to one movie with a star rating from 1 (worst) to 5 (best).
Every movie, author and review is identified by a GUID id. Ids are never guessable, so look them up
with movies_list, authors_list or reviews_list before calling a tool that needs one.
To change a review use reviews_update, which overwrites the author, movie and stars together.
reviews_delete can't be undone, so confirm with the user before calling it.
""";
})
.WithHttpTransport()
.WithHttpTransport(options => options.Stateless = true)
.WithToolsFromAssembly()
.WithRequestFilters(filters => filters.AddCallToolFilter(ToolErrorFilter.Filter));

Expand Down
2 changes: 1 addition & 1 deletion src/Presentation/Extensions/WebApplicationExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public static WebApplication ConfigureApplication(this WebApplication app)

#region Model Context Protocol

_ = app.MapMcp();
_ = app.MapMcp("/mcp");

#endregion Model Context Protocol

Expand Down
3 changes: 1 addition & 2 deletions src/Presentation/Properties/launchSettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@
"profiles": {
"CleanModelContextProtocol": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "swagger",
"launchBrowser": false,
"applicationUrl": "https://localhost:7032;http://localhost:5032",
"environmentVariables": {
"DOTNET_ENVIRONMENT": "local"
Expand Down
17 changes: 10 additions & 7 deletions src/Presentation/Tools/AuthorTools.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,22 +9,25 @@ namespace CleanModelContextProtocol.Presentation.Tools;
[McpServerToolType]
public static class AuthorTools
{
[McpServerTool(Name = "GetAllAuthors", ReadOnly = true)]
[Description("Get all authors in the system")]
public static async Task<string> GetAllAuthors(ISender sender)
[McpServerTool(Name = "authors_list", Title = "List authors", ReadOnly = true, Idempotent = true, OpenWorld = false)]
[Description("List every author who has written reviews, with their id, first and last name, and the reviews they have written. " +
"Use this to find an author's id before calling authors_get, reviews_create or reviews_update.")]
public static async Task<string> ListAuthors(ISender sender)
{
var result = await sender.Send(new Queries.GetAuthors.GetAuthorsQuery());

return JsonSerializer.Serialize(result);
}

[McpServerTool(Name = "GetAuthorById", ReadOnly = true)]
[Description("Get a specific author by their unique ID")]
public static async Task<string> GetAuthorById(ISender sender, [Description("The GUID of the author")] Guid id)
[McpServerTool(Name = "authors_get", Title = "Get author", ReadOnly = true, Idempotent = true, OpenWorld = false)]
[Description("Get one author by id, including every review they have written and the movie each review is for.")]
public static async Task<string> GetAuthor(
ISender sender,
[Description("The author's id (a GUID). Use authors_list to find it.")] Guid authorId)
{
return JsonSerializer.Serialize(await sender.Send(new Queries.GetAuthorById.GetAuthorByIdQuery
{
Id = id
Id = authorId
}));
}
}
17 changes: 10 additions & 7 deletions src/Presentation/Tools/MovieTools.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,22 +9,25 @@ namespace CleanModelContextProtocol.Presentation.Tools;
[McpServerToolType]
public static class MovieTools
{
[McpServerTool(Name = "GetAllMovies", ReadOnly = true)]
[Description("Get all movies in the system")]
public static async Task<string> GetAllMovies(ISender sender)
[McpServerTool(Name = "movies_list", Title = "List movies", ReadOnly = true, Idempotent = true, OpenWorld = false)]
[Description("List every movie with its id, title and reviews. " +
"Use this to find a movie's id before calling movies_get, reviews_create or reviews_update.")]
public static async Task<string> ListMovies(ISender sender)
{
var result = await sender.Send(new Queries.GetMovies.GetMoviesQuery());

return JsonSerializer.Serialize(result);
}

[McpServerTool(Name = "GetMovieById", ReadOnly = true)]
[Description("Get a specific movie by its unique ID")]
public static async Task<string> GetMovieById(ISender sender, [Description("The GUID of the movie")] Guid id)
[McpServerTool(Name = "movies_get", Title = "Get movie", ReadOnly = true, Idempotent = true, OpenWorld = false)]
[Description("Get one movie by id, including every review of it with the star rating and the author who wrote it.")]
public static async Task<string> GetMovie(
ISender sender,
[Description("The movie's id (a GUID). Use movies_list to find it.")] Guid movieId)
{
return JsonSerializer.Serialize(await sender.Send(new Queries.GetMovieById.GetMovieByIdQuery
{
Id = id
Id = movieId
}));
}
}
53 changes: 29 additions & 24 deletions src/Presentation/Tools/ReviewTools.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,33 +10,35 @@ namespace CleanModelContextProtocol.Presentation.Tools;
[McpServerToolType]
public static class ReviewTools
{
[McpServerTool(Name = "GetAllReviews", ReadOnly = true)]
[Description("Get all reviews in the system")]
public static async Task<string> GetAllReviews(ISender sender)
[McpServerTool(Name = "reviews_list", Title = "List reviews", ReadOnly = true, Idempotent = true, OpenWorld = false)]
[Description("List every review with its id, star rating (1 to 5), the movie it is for and the author who wrote it.")]
public static async Task<string> ListReviews(ISender sender)
{
var result = await sender.Send(new Queries.GetReviews.GetReviewsQuery());

return JsonSerializer.Serialize(result);
}

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

[McpServerTool(Name = "CreateReview")]
[Description("Create a new review linking an author and a movie")]
[McpServerTool(Name = "reviews_create", Title = "Create review", ReadOnly = false, Destructive = false, Idempotent = false, OpenWorld = false)]
[Description("Create a review of a movie by an author with a star rating from 1 to 5, and return the new review. " +
"Each call creates another review, so don't retry a call that succeeded.")]
public static async Task<string> CreateReview(
ISender sender,
[Description("The GUID of the author writing the review")] Guid authorId,
[Description("The GUID of the movie being reviewed")] Guid movieId,
[Description("Star rating for the movie (e.g. 1-5)")] int stars)
[Description("The id of the author writing the review. Use authors_list to find it.")] Guid authorId,
[Description("The id of the movie being reviewed. Use movies_list to find it.")] Guid movieId,
[Description("The star rating, a whole number from 1 (worst) to 5 (best).")] int stars)
{
var result = await sender.Send(new Commands.CreateReview.CreateReviewCommand
{
Expand All @@ -48,18 +50,19 @@ public static async Task<string> CreateReview(
return JsonSerializer.Serialize(result);
}

[McpServerTool(Name = "UpdateReview")]
[Description("Update an existing review")]
[McpServerTool(Name = "reviews_update", Title = "Update review", ReadOnly = false, Destructive = true, Idempotent = true, OpenWorld = false)]
[Description("Replace an existing review's author, movie and star rating. Every field is overwritten, " +
"so pass the current author and movie ids when you only want to change the stars.")]
public static async Task<string> UpdateReview(
ISender sender,
[Description("The GUID of the review to update")] Guid id,
[Description("The GUID of the author writing the review")] Guid authorId,
[Description("The GUID of the movie being reviewed")] Guid movieId,
[Description("Star rating for the movie (e.g. 1-5)")] int stars)
[Description("The id of the review to update. Use reviews_list to find it.")] Guid reviewId,
[Description("The id of the author writing the review. Use authors_list to find it.")] Guid authorId,
[Description("The id of the movie being reviewed. Use movies_list to find it.")] Guid movieId,
[Description("The star rating, a whole number from 1 (worst) to 5 (best).")] int stars)
{
_ = await sender.Send(new Commands.UpdateReview.UpdateReviewCommand
{
Id = id,
Id = reviewId,
AuthorId = authorId,
MovieId = movieId,
Stars = stars
Expand All @@ -68,13 +71,15 @@ public static async Task<string> UpdateReview(
return "Review updated successfully";
}

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

return "Review deleted successfully";
Expand Down
4 changes: 2 additions & 2 deletions src/Presentation/Tools/VersionTools.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ namespace CleanModelContextProtocol.Presentation.Tools;
[McpServerToolType]
public static class VersionTools
{
[McpServerTool(Name = "GetVersion", ReadOnly = true)]
[Description("Get the current application version details")]
[McpServerTool(Name = "server_get_version", Title = "Get server version", ReadOnly = true, Idempotent = true, OpenWorld = false)]
[Description("Get the version of this server: the file version and the informational version, which includes the commit it was built from.")]
public static async Task<string> GetVersion(ISender sender)
{
var result = await sender.Send(new Queries.GetVersion.GetVersionQuery());
Expand Down
Loading
Loading