Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
7f7306f
Run the MCP Inspector in Docker Compose, pointed at the server
stphnwlsh Oct 28, 2026
709abbc
Merge branch 'main' into feature/docker-mcp-inspector
stphnwlsh Oct 28, 2026
0231b12
feat: give every MCP tool agent-ready metadata
stphnwlsh Oct 28, 2026
b294ae3
feat: return typed, structured results from every MCP tool
stphnwlsh Oct 28, 2026
9a0cf69
feat: add search and paging queries to the Application layer
stphnwlsh Oct 28, 2026
e0a1f9e
Merge branch 'feature/search-and-paging' into feature/mcp-intent-tools
stphnwlsh Oct 28, 2026
7f0dff5
feat: reshape the MCP tools around what agents need to do
stphnwlsh Oct 28, 2026
8c13519
fix: pattern-match the optional review filters
stphnwlsh Oct 28, 2026
caa42fa
fix: guard the tool name before building the not-found hint
stphnwlsh Oct 28, 2026
c76b486
Merge branch 'feature/mcp-tool-metadata' into feature/mcp-structured-…
stphnwlsh Oct 28, 2026
1061a36
Merge branch 'feature/search-and-paging' into feature/mcp-intent-tools
stphnwlsh Oct 28, 2026
a1384f3
Merge branch 'feature/mcp-structured-output' into feature/mcp-intent-…
stphnwlsh Oct 28, 2026
7703bb5
feat: add resources, prompts and completions to the MCP server
stphnwlsh Oct 28, 2026
01330ee
test: assert the average stars without dereferencing the nullable
stphnwlsh Oct 28, 2026
286d247
Merge branch 'feature/mcp-intent-tools' into feature/mcp-resources-pr…
stphnwlsh Oct 28, 2026
721569b
Merge branch 'main' into feature/mcp-structured-output
stphnwlsh Oct 28, 2026
82c7338
Merge branch 'feature/mcp-structured-output' into feature/mcp-intent-…
stphnwlsh Oct 28, 2026
6c14f29
Merge branch 'feature/mcp-intent-tools' into feature/mcp-resources-pr…
stphnwlsh Oct 28, 2026
7adb732
Merge remote-tracking branch 'origin/main' into feature/mcp-intent-tools
stphnwlsh Oct 28, 2026
7c67d67
Merge branch 'feature/mcp-intent-tools' into feature/mcp-resources-pr…
stphnwlsh Oct 28, 2026
356e643
Merge remote-tracking branch 'origin/main' into feature/mcp-resources…
stphnwlsh Oct 28, 2026
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
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,12 +75,14 @@ The one deliberate break from Clean Architecture is that the Presentation projec

- MCP server using the [MCP C# SDK](https://github.com/modelcontextprotocol/csharp-sdk), stateless Streamable HTTP at `/mcp`
- Six task-shaped tools (`movies_search`, `movies_get`, `authors_search`, `reviews_list`, `reviews_write`, `reviews_delete`) with titles, read-only, destructive and idempotent hints, and descriptions written for agents
- Resources for each movie, author and review (`movies://{movieId}`, `authors://{authorId}`, `reviews://{reviewId}`) and the server version (`server://version`)
- Prompts for common jobs (`summarise_movie_reception`, `compare_movies`, `review_movie`) that embed the movies they're about, with completions that suggest movie titles and author names as you type
- Search with paging and small results by default: every list returns 10 items, a total count and a cursor, with names and average ratings next to ids
- Logging using [Serilog](https://github.com/serilog/serilog), with [Seq](https://datalust.co/seq) when running in Docker
- Mediator pattern using [Mediator](https://github.com/martinothamar/Mediator)
- Validation using [FluentValidation](https://github.com/FluentValidation/FluentValidation) in an Application pipeline behaviour
- Typed tool results published with an output schema and returned as structured content as well as JSON text
- Tool errors mapped from Application exceptions by a single call-tool filter, with messages that tell the agent how to recover
- Errors mapped from Application exceptions by request filters: tool errors tell the agent how to recover, and resources and prompts return MCP protocol errors such as resource not found
- Object mapping using [Mapperly](https://mapperly.riok.app)
- In-memory data using [Entity Framework Core](https://learn.microsoft.com/ef/core/providers/in-memory/) seeded with [Bogus](https://github.com/bchavez/Bogus)
- Testing using [xUnit](https://xunit.net), [Shouldly](https://github.com/shouldly/shouldly) and [NSubstitute](https://github.com/nsubstitute/NSubstitute), with coverage from [Coverlet](https://github.com/coverlet-coverage/coverlet)
Expand Down
78 changes: 78 additions & 0 deletions src/Presentation/Completions/CompletionHandler.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
namespace CleanModelContextProtocol.Presentation.Completions;

using Application.Common.Paging;
using Mediator;
using Microsoft.Extensions.DependencyInjection;
using ModelContextProtocol.Protocol;
using ModelContextProtocol.Server;
using AuthorQueries = Application.Authors.Queries;
using MovieQueries = Application.Movies.Queries;

/// <summary>
/// Suggests movie titles and author names as the user types a prompt argument.
/// </summary>
public static class CompletionHandler
{
private const int MaxQueryLength = 100;

public static async ValueTask<CompleteResult> Handle(RequestContext<CompleteRequestParams> context, CancellationToken cancellationToken)
{
return await Complete(context.Services.GetRequiredService<ISender>(), context.Params, cancellationToken);
}

public static async Task<CompleteResult> Complete(ISender sender, CompleteRequestParams request, CancellationToken cancellationToken)
{
var argument = request?.Argument;

if (request?.Ref is not PromptReference || argument is null || argument.Value?.Length > MaxQueryLength)
{
return Empty();
}

switch (argument.Name)
{
case "movieTitle" or "firstMovieTitle" or "secondMovieTitle":
{
var page = await sender.Send(new MovieQueries.SearchMovies.SearchMoviesQuery
{
Query = argument.Value,
Limit = Paging.MaxLimit
}, cancellationToken);

return Result([.. page.Items.Select(m => m.Title)], page.TotalCount);
}

case "authorName":
{
var page = await sender.Send(new AuthorQueries.SearchAuthors.SearchAuthorsQuery
{
Query = argument.Value,
Limit = Paging.MaxLimit
}, cancellationToken);

return Result([.. page.Items.Select(a => $"{a.FirstName} {a.LastName}".Trim())], page.TotalCount);
}

default:
return Empty();
}
}

private static CompleteResult Result(List<string> values, int total)
{
return new CompleteResult
{
Completion = new Completion
{
Values = values,
Total = total,
HasMore = total > values.Count
}
};
}

private static CompleteResult Empty()
{
return Result([], 0);
}
}
45 changes: 45 additions & 0 deletions src/Presentation/Errors/ProtocolErrorFilter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
namespace CleanModelContextProtocol.Presentation.Errors;

using CleanModelContextProtocol.Application.Common.Exceptions;
using FluentValidation;
using ModelContextProtocol;
using ModelContextProtocol.Server;

/// <summary>
/// Maps exceptions raised by the Application layer while reading a resource or getting a prompt to MCP protocol errors.
/// </summary>
public static class ProtocolErrorFilter
{
public static McpRequestHandler<TParams, TResult> Filter<TParams, TResult>(McpRequestHandler<TParams, TResult> next)
{
return async (request, cancellationToken) =>
{
try
{
return await next(request, cancellationToken);
}
catch (Exception exception) when (ToProtocolException(exception) is { } protocolException)
{
throw protocolException;
}
};
}

public static McpProtocolException ToProtocolException(Exception exception)
{
return exception switch
{
NotFoundException => new McpProtocolException(
$"Not Found: {exception.Message} Check the id: movies_search, authors_search and reviews_list return valid ones.",
exception,
McpErrorCode.ResourceNotFound),
ValidationException validationException => new McpProtocolException(
"Validation Failed: " + string.Join(" ", validationException.Errors
.Select(e => $"{e.PropertyName}: {e.ErrorMessage}")
.Distinct()),
exception,
McpErrorCode.InvalidParams),
_ => null
};
}
}
29 changes: 13 additions & 16 deletions src/Presentation/Extensions/WebApplicationBuilderExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,13 @@ namespace CleanModelContextProtocol.Presentation.Extensions;

using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Text.Json;
using System.Text.Json.Serialization;
using Application;
using CleanModelContextProtocol.Presentation.Completions;
using CleanModelContextProtocol.Presentation.Errors;
using CleanModelContextProtocol.Presentation.Serialization;
using Infrastructure;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using ModelContextProtocol;
using Serilog;

[ExcludeFromCodeCoverage]
Expand All @@ -32,17 +30,6 @@ public static WebApplicationBuilder ConfigureApplicationBuilder(this WebApplicat

#endregion Logging

#region Serialisation

var serializerOptions = new JsonSerializerOptions(McpJsonUtilities.DefaultOptions)
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
};
serializerOptions.TypeInfoResolverChain.Insert(0, AppJsonSerializerContext.Default);

#endregion Serialisation

#region Project Dependencies

_ = builder.Services.AddMediator(options => options.ServiceLifetime = ServiceLifetime.Scoped);
Expand Down Expand Up @@ -80,11 +67,21 @@ A review links one author to one movie with a star rating from 1 (worst) to 5 (b
so pass nextCursor back to continue rather than raising the limit.
reviews_write creates a review, or replaces one when you pass its reviewId.
reviews_delete can't be undone, so confirm with the user before calling it.
Each movie, author and review can also be read as a resource at movies://{id}, authors://{id} or
reviews://{id}, and server://version gives this server's version.
""";
})
.WithHttpTransport(options => options.Stateless = true)
.WithToolsFromAssembly(serializerOptions: serializerOptions)
.WithRequestFilters(filters => filters.AddCallToolFilter(ToolErrorFilter.Filter));
.WithToolsFromAssembly(serializerOptions: McpSerializer.Options)
.WithResourcesFromAssembly()
.WithPromptsFromAssembly(serializerOptions: McpSerializer.Options)
.WithCompleteHandler(CompletionHandler.Handle)
.WithRequestFilters(filters =>
{
filters.AddCallToolFilter(ToolErrorFilter.Filter);
filters.AddReadResourceFilter(ProtocolErrorFilter.Filter);
filters.AddGetPromptFilter(ProtocolErrorFilter.Filter);
});

#endregion Model Context Protocol

Expand Down
130 changes: 130 additions & 0 deletions src/Presentation/Prompts/MoviePrompts.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
namespace CleanModelContextProtocol.Presentation.Prompts;

using System.ComponentModel;
using CleanModelContextProtocol.Presentation.Models;
using CleanModelContextProtocol.Presentation.Serialization;
using Mediator;
using ModelContextProtocol.Protocol;
using ModelContextProtocol.Server;
using Queries = Application.Movies.Queries;

[McpServerPromptType]
public static class MoviePrompts
{
[McpServerPrompt(Name = "summarise_movie_reception", Title = "Summarise a movie's reception")]
[Description("Summarise how reviewers have received a movie: its average stars, how the ratings spread, and who liked it most and least.")]
public static async Task<GetPromptResult> SummariseMovieReception(
ISender sender,
[Description("The movie's title, or part of it.")] string movieTitle)
{
var movie = await FindMovie(sender, movieTitle);

var messages = new List<PromptMessage>
{
Text(movie is null
? $"Summarise how reviewers have received the movie \"{movieTitle}\". Find it with movies_search, get its reviews " +
"with movies_get, then give its average stars, how the ratings spread from 1 to 5, and which authors rated it highest and lowest."
: $"Summarise how reviewers have received \"{movie.Title}\", using the movie below. Give its average stars, " +
"how the ratings spread from 1 to 5, and which authors rated it highest and lowest.")
};

if (movie is not null)
{
messages.Add(Embed(movie));
}

return new GetPromptResult
{
Description = $"Summarise the reception of {movie?.Title ?? movieTitle}",
Messages = messages
};
}

[McpServerPrompt(Name = "compare_movies", Title = "Compare two movies")]
[Description("Compare how reviewers rated two movies, and say which one they preferred and by how much.")]
public static async Task<GetPromptResult> CompareMovies(
ISender sender,
[Description("The first movie's title, or part of it.")] string firstMovieTitle,
[Description("The second movie's title, or part of it.")] string secondMovieTitle)
{
var first = await FindMovie(sender, firstMovieTitle);
var second = await FindMovie(sender, secondMovieTitle);

var messages = new List<PromptMessage>
{
Text($"Compare how reviewers rated \"{first?.Title ?? firstMovieTitle}\" and \"{second?.Title ?? secondMovieTitle}\". " +
"Give each movie's average stars and number of reviews, note any authors who reviewed both, and say which movie " +
"reviewers preferred. Find any movie that isn't attached below with movies_search, then get it with movies_get.")
};

foreach (var movie in new[] { first, second }.OfType<MovieResult>())
{
messages.Add(Embed(movie));
}

return new GetPromptResult
{
Description = $"Compare {first?.Title ?? firstMovieTitle} with {second?.Title ?? secondMovieTitle}",
Messages = messages
};
}

[McpServerPrompt(Name = "review_movie", Title = "Review a movie")]
[Description("Write a review of a movie as one of the authors, checking the movie and author before saving it.")]
public static GetPromptResult ReviewMovie(
[Description("The movie's title, or part of it.")] string movieTitle,
[Description("The name of the author writing the review.")] string authorName)
{
return new GetPromptResult
{
Description = $"Review {movieTitle} as {authorName}",
Messages =
[
Text($"I want to review the movie \"{movieTitle}\" as the author \"{authorName}\". Find the movie with movies_search " +
"and the author with authors_search. If either search doesn't return exactly one clear match, show me the closest " +
"results and ask which one I meant. Ask me for a star rating from 1 to 5, then save the review with reviews_write " +
"and show me the saved review.")
]
};
}

private static async Task<MovieResult> FindMovie(ISender sender, string title)
{
var page = await sender.Send(new Queries.SearchMovies.SearchMoviesQuery
{
Query = title,
Limit = 5
});

var movie = page.Items.FirstOrDefault(m => string.Equals(m.Title, title?.Trim(), StringComparison.OrdinalIgnoreCase))
?? (page.TotalCount == 1 ? page.Items[0] : null);

return movie?.ToResult(includeReviews: true);
}

private static PromptMessage Text(string text)
{
return new PromptMessage
{
Role = Role.User,
Content = new TextContentBlock { Text = text }
};
}

private static PromptMessage Embed(MovieResult movie)
{
return new PromptMessage
{
Role = Role.User,
Content = new EmbeddedResourceBlock
{
Resource = new TextResourceContents
{
Uri = $"movies://{movie.Id}",
MimeType = "application/json",
Text = McpSerializer.Serialize(movie)
}
}
};
}
}
26 changes: 26 additions & 0 deletions src/Presentation/Resources/AuthorResources.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
namespace CleanModelContextProtocol.Presentation.Resources;

using System.ComponentModel;
using CleanModelContextProtocol.Presentation.Models;
using CleanModelContextProtocol.Presentation.Serialization;
using Mediator;
using ModelContextProtocol.Server;
using Queries = Application.Authors.Queries;

[McpServerResourceType]
public static class AuthorResources
{
[McpServerResource(UriTemplate = "authors://{authorId}", Name = "author", Title = "Author", MimeType = "application/json")]
[Description("An author with their review count, average stars and every review they have written, including each movie's title.")]
public static async Task<string> GetAuthor(
ISender sender,
[Description("The author's id (a GUID).")] Guid authorId)
{
var author = await sender.Send(new Queries.GetAuthorById.GetAuthorByIdQuery
{
Id = authorId
});

return McpSerializer.Serialize(author.ToResult(includeReviews: true));
}
}
26 changes: 26 additions & 0 deletions src/Presentation/Resources/MovieResources.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
namespace CleanModelContextProtocol.Presentation.Resources;

using System.ComponentModel;
using CleanModelContextProtocol.Presentation.Models;
using CleanModelContextProtocol.Presentation.Serialization;
using Mediator;
using ModelContextProtocol.Server;
using Queries = Application.Movies.Queries;

[McpServerResourceType]
public static class MovieResources
{
[McpServerResource(UriTemplate = "movies://{movieId}", Name = "movie", Title = "Movie", MimeType = "application/json")]
[Description("A movie with its review count, average stars and every review, including each author's name.")]
public static async Task<string> GetMovie(
ISender sender,
[Description("The movie's id (a GUID).")] Guid movieId)
{
var movie = await sender.Send(new Queries.GetMovieById.GetMovieByIdQuery
{
Id = movieId
});

return McpSerializer.Serialize(movie.ToResult(includeReviews: true));
}
}
Loading
Loading