Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
30 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
366dbfb
feat: add optional OAuth protection for the MCP endpoint
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
51cb4ea
Merge branch 'feature/mcp-resources-prompts' into feature/mcp-auth
stphnwlsh Oct 28, 2026
9cb8125
test: dispose the HTTP content and responses in the auth tests
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
9987b01
Merge branch 'feature/mcp-resources-prompts' into feature/mcp-auth
stphnwlsh Oct 28, 2026
c2c2aa8
Merge remote-tracking branch 'origin/main' into feature/mcp-auth
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
e37a92d
Merge branch 'feature/mcp-resources-prompts' into feature/mcp-auth
stphnwlsh Oct 28, 2026
356e643
Merge remote-tracking branch 'origin/main' into feature/mcp-resources…
stphnwlsh Oct 28, 2026
70c4fcd
Merge remote-tracking branch 'origin/feature/mcp-resources-prompts' i…
stphnwlsh Oct 28, 2026
f4196c8
Merge remote-tracking branch 'origin/main' into feature/mcp-auth
stphnwlsh Oct 28, 2026
d356153
test: cover AuthenticationSettings binding
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
54 changes: 54 additions & 0 deletions .template.config/template.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,60 @@
"displayName": "The name of the author of the solution.",
"defaultValue": "Stephen Walsh",
"replaces": "Stephen Walsh"
},
"authority": {
"type": "parameter",
"datatype": "string",
"displayName": "The OAuth authorization server that issues access tokens. Leave empty to run the MCP endpoint without authentication.",
"defaultValue": ""
},
"audience": {
"type": "parameter",
"datatype": "string",
"displayName": "The audience access tokens must be issued for, usually the server's own URL.",
"defaultValue": ""
},
"authorityValue": {
"type": "generated",
"generator": "join",
"replaces": "\"Authority\": \"\"",
"parameters": {
"symbols": [
{
"type": "const",
"value": "\"Authority\": \""
},
{
"type": "ref",
"value": "authority"
},
{
"type": "const",
"value": "\""
}
]
}
},
"audienceValue": {
"type": "generated",
"generator": "join",
"replaces": "\"Audience\": \"\"",
"parameters": {
"symbols": [
{
"type": "const",
"value": "\"Audience\": \""
},
{
"type": "ref",
"value": "audience"
},
{
"type": "const",
"value": "\""
}
]
}
}
}
}
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,16 @@ dotnet new install CleanModelContextProtocol.Template
dotnet new cleanmodelcontextprotocol --name {YOUR_SOLUTION_NAMESPACE} --authorName "{YOUR_NAME}"
```

### Protect the server with OAuth (optional)

The server runs without authentication unless you give it an authorization server. Pass one when you create the solution, or set `Authentication:Authority` and `Authentication:Audience` in `appsettings.json` later.

``` bash
dotnet new cleanmodelcontextprotocol --name {YOUR_SOLUTION_NAMESPACE} --authority https://{YOUR_AUTHORIZATION_SERVER} --audience https://{YOUR_SERVER_URL}
```

With an authority set, `/mcp` needs a bearer token issued for the audience, and the server publishes [protected resource metadata](https://modelcontextprotocol.io/specification/latest/basic/authorization) at `/.well-known/oauth-protected-resource/mcp` so MCP clients can find the authorization server and sign in. List the scopes clients should ask for in `Authentication:Scopes`.

## Running the project

``` bash
Expand Down Expand Up @@ -78,6 +88,7 @@ The one deliberate break from Clean Architecture is that the Presentation projec
- 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
- 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
Expand Down
27 changes: 27 additions & 0 deletions src/Presentation/Authentication/AuthenticationSettings.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
namespace CleanModelContextProtocol.Presentation.Authentication;

using Microsoft.Extensions.Configuration;

/// <summary>
/// OAuth settings for protecting the MCP endpoint. Leave the authority empty to run the server without authentication.
/// </summary>
public class AuthenticationSettings
{
public const string SectionName = "Authentication";

/// <summary>The OAuth authorization server that issues access tokens, such as https://login.example.com.</summary>
public string Authority { get; init; }

/// <summary>The audience access tokens must be issued for. This is usually the server's own URL.</summary>
public string Audience { get; init; }

/// <summary>The scopes clients should ask for, published in the protected resource metadata.</summary>
public List<string> Scopes { get; init; } = [];

public bool Enabled => !string.IsNullOrWhiteSpace(this.Authority);

public static AuthenticationSettings FromConfiguration(IConfiguration configuration)
{
return configuration.GetSection(SectionName).Get<AuthenticationSettings>() ?? new AuthenticationSettings();
}
}
33 changes: 33 additions & 0 deletions src/Presentation/Extensions/WebApplicationBuilderExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,15 @@ namespace CleanModelContextProtocol.Presentation.Extensions;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using Application;
using CleanModelContextProtocol.Presentation.Authentication;
using CleanModelContextProtocol.Presentation.Completions;
using CleanModelContextProtocol.Presentation.Errors;
using CleanModelContextProtocol.Presentation.Serialization;
using Infrastructure;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using ModelContextProtocol.AspNetCore.Authentication;
using Serilog;

[ExcludeFromCodeCoverage]
Expand Down Expand Up @@ -38,6 +41,36 @@ public static WebApplicationBuilder ConfigureApplicationBuilder(this WebApplicat

#endregion Project Dependencies

#region Authentication

var authentication = AuthenticationSettings.FromConfiguration(builder.Configuration);

if (authentication.Enabled)
{
_ = builder.Services
.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = McpAuthenticationDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.Authority = authentication.Authority;
options.Audience = authentication.Audience;
options.MapInboundClaims = false;
})
.AddMcp(options => options.ResourceMetadata = new()
{
Resource = authentication.Audience,
AuthorizationServers = [authentication.Authority],
ScopesSupported = authentication.Scopes,
ResourceName = "Clean Model Context Protocol"
});
_ = builder.Services.AddAuthorization();
}

#endregion Authentication

#region Model Context Protocol

_ = builder.Services
Expand Down
10 changes: 9 additions & 1 deletion src/Presentation/Extensions/WebApplicationExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
namespace CleanModelContextProtocol.Presentation.Extensions;

using System.Diagnostics.CodeAnalysis;
using CleanModelContextProtocol.Presentation.Authentication;
using Microsoft.AspNetCore.Builder;
using Serilog;

Expand All @@ -17,7 +18,14 @@ public static WebApplication ConfigureApplication(this WebApplication app)

#region Model Context Protocol

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

if (AuthenticationSettings.FromConfiguration(app.Configuration).Enabled)
{
_ = app.UseAuthentication();
_ = app.UseAuthorization();
_ = mcp.RequireAuthorization();
}

#endregion Model Context Protocol

Expand Down
1 change: 1 addition & 0 deletions src/Presentation/Presentation.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.14" />
<PackageReference Include="ModelContextProtocol.AspNetCore" Version="2.3.0" />
<PackageReference Include="Serilog.AspNetCore" Version="10.0.0" />
<PackageReference Include="Serilog.Enrichers.Environment" Version="3.0.1" />
Expand Down
5 changes: 5 additions & 0 deletions src/Presentation/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,10 @@
"Default": "None"
}
},
"Authentication": {
"Authority": "",
"Audience": "",
"Scopes": []
},
"AllowedHosts": "*"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
namespace CleanModelContextProtocol.Presentation.Tests.Integration.Authentication;

using System.Net;
using System.Net.Http.Headers;
using System.Security.Claims;
using System.Text;
using System.Text.Json;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.IdentityModel.Tokens;
using ModelContextProtocol.Client;
using ModelContextProtocol.Protocol;
using Shouldly;
using Xunit;

public class AuthenticationTests : IDisposable
{
private const string Authority = "https://login.example.com";
private const string Audience = "https://mcp.example.com";

private static readonly SymmetricSecurityKey SigningKey = new(Encoding.UTF8.GetBytes("a-test-signing-key-that-is-long-enough-for-hs256"));

private readonly ModelContextProtocolApplication application = new(
settings: new Dictionary<string, string>
{
["Authentication:Authority"] = Authority,
["Authentication:Audience"] = Audience,
["Authentication:Scopes:0"] = "mcp:tools"
},
configureServices: services => services.PostConfigure<JwtBearerOptions>(JwtBearerDefaults.AuthenticationScheme, options =>
{
options.Configuration = new OpenIdConnectConfiguration { Issuer = Authority };
options.TokenValidationParameters.IssuerSigningKey = SigningKey;
options.TokenValidationParameters.ValidIssuer = Authority;
}));

[Fact]
public async Task Mcp_WithoutToken_ShouldReturn_UnauthorizedWithResourceMetadata()
{
// Arrange
using var client = this.application.CreateClient();
using var content = new StringContent("{}", Encoding.UTF8, "application/json");

// Act
using var response = await client.PostAsync(new Uri("http://localhost/mcp"), content);

// Assert
response.StatusCode.ShouldBe(HttpStatusCode.Unauthorized);
response.Headers.WwwAuthenticate.ToString().ShouldContain("resource_metadata=\"http://localhost/.well-known/oauth-protected-resource/mcp\"");
}

[Fact]
public async Task ResourceMetadata_ShouldReturn_AuthorizationServer()
{
// Arrange
using var client = this.application.CreateClient();

// Act
using var response = await client.GetAsync(new Uri("http://localhost/.well-known/oauth-protected-resource/mcp"));

// Assert
response.StatusCode.ShouldBe(HttpStatusCode.OK);

using var metadata = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
metadata.RootElement.GetProperty("resource").GetString().ShouldBe(Audience);
metadata.RootElement.GetProperty("authorization_servers")[0].GetString().ShouldBe(Authority);
metadata.RootElement.GetProperty("scopes_supported")[0].GetString().ShouldBe("mcp:tools");
}

[Fact]
public async Task Mcp_WithWrongAudience_ShouldReturn_Unauthorized()
{
// Arrange
using var client = this.application.CreateClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", CreateToken("https://someone-else.example.com"));
using var content = new StringContent("{}", Encoding.UTF8, "application/json");

// Act
using var response = await client.PostAsync(new Uri("http://localhost/mcp"), content);

// Assert
response.StatusCode.ShouldBe(HttpStatusCode.Unauthorized);
}

[Fact]
public async Task Mcp_WithToken_ShouldList_Tools()
{
// Arrange
using var httpClient = this.application.CreateClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", CreateToken(Audience));

await using var client = await McpClient.CreateAsync(
new HttpClientTransport(
new HttpClientTransportOptions { Endpoint = new Uri("http://localhost/mcp") },
httpClient,
null,
false),
new McpClientOptions { ClientInfo = new Implementation { Name = "test-client", Version = "1.0" } });

// Act
var tools = await client.ListToolsAsync();

// Assert
tools.ShouldNotBeEmpty();
}

public void Dispose()
{
this.application.Dispose();
GC.SuppressFinalize(this);
}

private static string CreateToken(string audience)
{
return new JsonWebTokenHandler().CreateToken(new SecurityTokenDescriptor
{
Issuer = Authority,
Audience = audience,
Subject = new ClaimsIdentity([new Claim("sub", "test-user")]),
Expires = DateTime.UtcNow.AddMinutes(5),
SigningCredentials = new SigningCredentials(SigningKey, SecurityAlgorithms.HmacSha256)
});
}
}
Original file line number Diff line number Diff line change
@@ -1,14 +1,29 @@
namespace CleanModelContextProtocol.Presentation.Tests.Integration;

using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

internal sealed class ModelContextProtocolApplication(string environment = "local") : WebApplicationFactory<Program>
internal sealed class ModelContextProtocolApplication(
string environment = "local",
Dictionary<string, string> settings = null,
Action<IServiceCollection> configureServices = null) : WebApplicationFactory<Program>
{
protected override IHost CreateHost(IHostBuilder builder)
{
_ = builder.UseEnvironment(environment);

if (settings is not null)
{
_ = builder.ConfigureHostConfiguration(configuration => configuration.AddInMemoryCollection(settings));
}

if (configureServices is not null)
{
_ = builder.ConfigureServices(configureServices);
}

return base.CreateHost(builder);
}
}
Loading
Loading