-
Notifications
You must be signed in to change notification settings - Fork 495
Per RouteValue Tools Sample #724
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
PederHP
wants to merge
18
commits into
modelcontextprotocol:main
Choose a base branch
from
PederHP:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+398
−0
Open
Changes from 7 commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
000dc23
Initial plan
Copilot a6f9154
Initial plan for per-user tool filtering sample
Copilot e094e35
Add ASP.NET Core MCP server sample with per-user tool filtering
Copilot f448824
Add demonstration script for per-user tool filtering sample
Copilot 3ad2194
Delete dotnet-install.sh
PederHP aa88dc7
Delete samples/AspNetCoreMcpServerPerUserTools/demo.sh
PederHP 774c752
Merge pull request #1 from PederHP/copilot/fix-a0ca257f-b665-488b-a76…
PederHP d5a647e
Initial plan
Copilot a2a9499
Rename AspNetCoreMcpServerPerUserTools to AspNetCoreMcpPerSessionTool…
Copilot 8d79c6e
Fix namespace references in appsettings.json
Copilot f92222d
Merge pull request #2 from PederHP/copilot/fix-98a8182b-5c5d-4882-a04…
PederHP 8c0e97a
Tweaks
PederHP c4ad110
README tweaks
PederHP e2ba19d
Apply suggestions from code review
PederHP 33fbfab
Refactor reflection to happen once only
PederHP a2ffda9
Added WithTools back in to easily init capabilities
PederHP 48bd4ea
Simplify sample
PederHP 663919c
Merge branch 'main' into main
PederHP File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
21 changes: 21 additions & 0 deletions
21
samples/AspNetCoreMcpServerPerUserTools/AspNetCoreMcpServerPerUserTools.csproj
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
<Project Sdk="Microsoft.NET.Sdk.Web"> | ||
|
||
<PropertyGroup> | ||
<TargetFramework>net9.0</TargetFramework> | ||
<Nullable>enable</Nullable> | ||
<ImplicitUsings>enable</ImplicitUsings> | ||
<PublishAot>true</PublishAot> | ||
</PropertyGroup> | ||
|
||
<ItemGroup> | ||
<ProjectReference Include="..\..\src\ModelContextProtocol.AspNetCore\ModelContextProtocol.AspNetCore.csproj" /> | ||
</ItemGroup> | ||
|
||
<ItemGroup> | ||
<PackageReference Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" /> | ||
<PackageReference Include="OpenTelemetry.Extensions.Hosting" /> | ||
<PackageReference Include="OpenTelemetry.Instrumentation.AspNetCore" /> | ||
<PackageReference Include="OpenTelemetry.Instrumentation.Http" /> | ||
</ItemGroup> | ||
|
||
</Project> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,172 @@ | ||
using OpenTelemetry; | ||
using OpenTelemetry.Metrics; | ||
using OpenTelemetry.Trace; | ||
using AspNetCoreMcpServerPerUserTools.Tools; | ||
using ModelContextProtocol.Server; | ||
|
||
var builder = WebApplication.CreateBuilder(args); | ||
|
||
// Register all MCP server tools - they will be filtered per user later | ||
builder.Services.AddMcpServer() | ||
.WithHttpTransport(options => | ||
{ | ||
// Configure per-session options to filter tools based on user permissions | ||
options.ConfigureSessionOptions = async (httpContext, mcpOptions, cancellationToken) => | ||
{ | ||
// Determine user role from headers (in real apps, use proper authentication) | ||
var userRole = GetUserRole(httpContext); | ||
var userId = GetUserId(httpContext); | ||
|
||
// Get the tool collection that we can modify per session | ||
var toolCollection = mcpOptions.Capabilities?.Tools?.ToolCollection; | ||
if (toolCollection != null) | ||
{ | ||
// Clear all tools first | ||
toolCollection.Clear(); | ||
|
||
// Add tools based on user role | ||
switch (userRole) | ||
{ | ||
case "admin": | ||
// Admins get all tools | ||
AddToolsForType<PublicTool>(toolCollection); | ||
AddToolsForType<UserTool>(toolCollection); | ||
AddToolsForType<AdminTool>(toolCollection); | ||
break; | ||
|
||
case "user": | ||
// Regular users get public and user tools | ||
AddToolsForType<PublicTool>(toolCollection); | ||
AddToolsForType<UserTool>(toolCollection); | ||
break; | ||
|
||
default: | ||
// Anonymous/public users get only public tools | ||
AddToolsForType<PublicTool>(toolCollection); | ||
break; | ||
} | ||
} | ||
|
||
// Optional: Log the session configuration for debugging | ||
var logger = httpContext.RequestServices.GetRequiredService<ILogger<Program>>(); | ||
logger.LogInformation("Configured MCP session for user {UserId} with role {UserRole}, {ToolCount} tools available", | ||
userId, userRole, toolCollection?.Count ?? 0); | ||
}; | ||
}) | ||
.WithTools<PublicTool>() | ||
.WithTools<UserTool>() | ||
.WithTools<AdminTool>(); | ||
|
||
// Add OpenTelemetry for observability | ||
builder.Services.AddOpenTelemetry() | ||
.WithTracing(b => b.AddSource("*") | ||
.AddAspNetCoreInstrumentation() | ||
.AddHttpClientInstrumentation()) | ||
.WithMetrics(b => b.AddMeter("*") | ||
.AddAspNetCoreInstrumentation() | ||
.AddHttpClientInstrumentation()) | ||
.WithLogging() | ||
.UseOtlpExporter(); | ||
|
||
var app = builder.Build(); | ||
|
||
// Add middleware to log requests for demo purposes | ||
app.Use(async (context, next) => | ||
{ | ||
var logger = context.RequestServices.GetRequiredService<ILogger<Program>>(); | ||
var userRole = GetUserRole(context); | ||
var userId = GetUserId(context); | ||
|
||
logger.LogInformation("Request from User {UserId} with Role {UserRole}: {Method} {Path}", | ||
userId, userRole, context.Request.Method, context.Request.Path); | ||
|
||
await next(); | ||
}); | ||
|
||
app.MapMcp(); | ||
|
||
// Add a simple endpoint to test authentication headers | ||
app.MapGet("/test-auth", (HttpContext context) => | ||
{ | ||
var userRole = GetUserRole(context); | ||
var userId = GetUserId(context); | ||
|
||
return Results.Text($"UserId: {userId}\nRole: {userRole}\nMessage: You are authenticated as {userId} with role {userRole}"); | ||
}); | ||
|
||
app.Run(); | ||
|
||
// Helper methods for authentication - in production, use proper authentication/authorization | ||
static string GetUserRole(HttpContext context) | ||
{ | ||
// Check for X-User-Role header first | ||
if (context.Request.Headers.TryGetValue("X-User-Role", out var roleHeader)) | ||
{ | ||
var role = roleHeader.ToString().ToLowerInvariant(); | ||
if (role is "admin" or "user" or "public") | ||
{ | ||
return role; | ||
} | ||
} | ||
|
||
// Check for Authorization header pattern (Bearer token simulation) | ||
if (context.Request.Headers.TryGetValue("Authorization", out var authHeader)) | ||
{ | ||
var auth = authHeader.ToString(); | ||
if (auth.StartsWith("Bearer admin-", StringComparison.OrdinalIgnoreCase)) | ||
return "admin"; | ||
if (auth.StartsWith("Bearer user-", StringComparison.OrdinalIgnoreCase)) | ||
return "user"; | ||
if (auth.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase)) | ||
return "public"; | ||
} | ||
|
||
// Default to public access | ||
return "public"; | ||
} | ||
|
||
static string GetUserId(HttpContext context) | ||
{ | ||
// Check for X-User-Id header first | ||
if (context.Request.Headers.TryGetValue("X-User-Id", out var userIdHeader)) | ||
{ | ||
return userIdHeader.ToString(); | ||
} | ||
|
||
// Extract from Authorization header if present | ||
if (context.Request.Headers.TryGetValue("Authorization", out var authHeader)) | ||
{ | ||
var auth = authHeader.ToString(); | ||
if (auth.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase)) | ||
{ | ||
var token = auth["Bearer ".Length..]; | ||
return token.Contains('-') ? token : $"user-{token}"; | ||
} | ||
} | ||
|
||
// Generate anonymous ID | ||
return $"anonymous-{Guid.NewGuid():N}"[..16]; | ||
} | ||
|
||
static void AddToolsForType<[System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers( | ||
System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicMethods)]T>( | ||
McpServerPrimitiveCollection<McpServerTool> toolCollection) | ||
{ | ||
var toolType = typeof(T); | ||
var methods = toolType.GetMethods(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static) | ||
.Where(m => m.GetCustomAttributes(typeof(McpServerToolAttribute), false).Any()); | ||
|
||
foreach (var method in methods) | ||
{ | ||
try | ||
{ | ||
var tool = McpServerTool.Create(method, target: null, new McpServerToolCreateOptions()); | ||
toolCollection.Add(tool); | ||
} | ||
catch (Exception ex) | ||
{ | ||
// Log error but continue with other tools | ||
Console.WriteLine($"Failed to add tool {toolType.Name}.{method.Name}: {ex.Message}"); | ||
} | ||
} | ||
} |
13 changes: 13 additions & 0 deletions
13
samples/AspNetCoreMcpServerPerUserTools/Properties/launchSettings.json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
{ | ||
"profiles": { | ||
"http": { | ||
"commandName": "Project", | ||
"dotnetRunMessages": true, | ||
"launchBrowser": false, | ||
"applicationUrl": "http://localhost:3001", | ||
"environmentVariables": { | ||
"ASPNETCORE_ENVIRONMENT": "Development" | ||
} | ||
} | ||
} | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.