-
Notifications
You must be signed in to change notification settings - Fork 689
Expand file tree
/
Copy pathProgram.cs
More file actions
125 lines (112 loc) · 4.83 KB
/
Program.cs
File metadata and controls
125 lines (112 loc) · 4.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using ModelContextProtocol.Protocol;
using ModelContextProtocol.Server;
using ModelContextProtocol.AspNetCore.Authentication;
using ProtectedMcpServer.Tools;
using System.Net.Http.Headers;
using System.Security.Claims;
using System.Threading.RateLimiting;
var builder = WebApplication.CreateBuilder(args);
var serverUrl = "http://localhost:7071/";
var inMemoryOAuthServerUrl = "https://localhost:7029";
const int maxConcurrentToolCallsPerUser = 10;
builder.Services.AddAuthentication(options =>
{
options.DefaultChallengeScheme = McpAuthenticationDefaults.AuthenticationScheme;
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
// Configure to validate tokens from our in-memory OAuth server
options.Authority = inMemoryOAuthServerUrl;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidAudience = serverUrl, // Validate that the audience matches the resource metadata as suggested in RFC 8707
ValidIssuer = inMemoryOAuthServerUrl,
NameClaimType = "name",
RoleClaimType = "roles"
};
options.Events = new JwtBearerEvents
{
OnTokenValidated = context =>
{
var name = context.Principal?.Identity?.Name ?? "unknown";
var email = context.Principal?.FindFirstValue("preferred_username") ?? "unknown";
Console.WriteLine($"Token validated for: {name} ({email})");
return Task.CompletedTask;
},
OnAuthenticationFailed = context =>
{
Console.WriteLine($"Authentication failed: {context.Exception.Message}");
return Task.CompletedTask;
},
OnChallenge = context =>
{
Console.WriteLine($"Challenging client to authenticate with Entra ID");
return Task.CompletedTask;
}
};
})
.AddMcp(options =>
{
options.ResourceMetadata = new()
{
ResourceDocumentation = "https://docs.example.com/api/weather",
AuthorizationServers = { inMemoryOAuthServerUrl },
ScopesSupported = ["mcp:tools"],
};
});
builder.Services.AddAuthorization();
builder.Services.AddHttpContextAccessor();
builder.Services.AddSingleton<PartitionedRateLimiter<RequestContext<CallToolRequestParams>>>(_ =>
PartitionedRateLimiter.Create<RequestContext<CallToolRequestParams>, string>(context =>
RateLimitPartition.GetConcurrencyLimiter(
context.User?.FindFirstValue(ClaimTypes.NameIdentifier) ??
context.User?.Identity?.Name ??
context.JsonRpcMessage.Context?.RelatedTransport?.SessionId ??
"anonymous",
_ => new ConcurrencyLimiterOptions
{
PermitLimit = maxConcurrentToolCallsPerUser,
QueueProcessingOrder = QueueProcessingOrder.OldestFirst,
QueueLimit = 0
})));
builder.Services.AddMcpServer()
.WithRequestFilters(filters => filters.AddCallToolFilter(next => async (request, cancellationToken) =>
{
var services = request.Services ?? throw new InvalidOperationException("Request context does not have an associated service provider.");
var toolCallConcurrencyLimiter = services.GetRequiredService<PartitionedRateLimiter<RequestContext<CallToolRequestParams>>>();
using var lease = await toolCallConcurrencyLimiter.AcquireAsync(request, 1, cancellationToken).ConfigureAwait(false);
if (!lease.IsAcquired)
{
return new CallToolResult
{
IsError = true,
Content = [new TextContentBlock { Text = $"Maximum concurrent tool calls ({maxConcurrentToolCallsPerUser}) exceeded. Try again after in-progress calls complete." }]
};
}
return await next(request, cancellationToken).ConfigureAwait(false);
}))
.WithTools<WeatherTools>()
.WithHttpTransport();
// Configure HttpClientFactory for weather.gov API
builder.Services.AddHttpClient("WeatherApi", client =>
{
client.BaseAddress = new Uri("https://api.weather.gov");
client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("weather-tool", "1.0"));
});
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
// Use the default MCP policy name that we've configured
app.MapMcp().RequireAuthorization();
Console.WriteLine($"Starting MCP server with authorization at {serverUrl}");
Console.WriteLine($"Using in-memory OAuth server at {inMemoryOAuthServerUrl}");
Console.WriteLine($"Protected Resource Metadata URL: {serverUrl}.well-known/oauth-protected-resource");
Console.WriteLine("Press Ctrl+C to stop the server");
app.Run(serverUrl);