-
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.
Open
Changes from all 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
20 changes: 20 additions & 0 deletions
20
samples/AspNetCoreMcpPerSessionTools/AspNetCoreMcpPerSessionTools.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,20 @@ | ||
<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.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,89 @@ | ||
using AspNetCoreMcpPerSessionTools.Tools; | ||
using ModelContextProtocol.Server; | ||
using System.Collections.Concurrent; | ||
using System.Reflection; | ||
|
||
var builder = WebApplication.CreateBuilder(args); | ||
|
||
// Create and populate the tool dictionary at startup | ||
var toolDictionary = new ConcurrentDictionary<string, McpServerTool[]>(); | ||
PopulateToolDictionary(toolDictionary); | ||
|
||
// Register all MCP server tools - they will be filtered per session based on route | ||
builder.Services.AddMcpServer() | ||
.WithHttpTransport(options => | ||
{ | ||
// Configure per-session options to filter tools based on route category | ||
options.ConfigureSessionOptions = async (httpContext, mcpOptions, cancellationToken) => | ||
{ | ||
// Determine tool category from route parameters | ||
var toolCategory = httpContext.Request.RouteValues["toolCategory"]?.ToString()?.ToLower() ?? "all"; | ||
|
||
// Get pre-populated tools for the requested category | ||
if (toolDictionary.TryGetValue(toolCategory, out var tools)) | ||
{ | ||
mcpOptions.Capabilities = new(); | ||
mcpOptions.Capabilities.Tools = new(); | ||
var toolCollection = mcpOptions.Capabilities.Tools.ToolCollection = new(); | ||
|
||
foreach (var tool in tools) | ||
{ | ||
toolCollection.Add(tool); | ||
} | ||
} | ||
}; | ||
}) | ||
.WithTools<ClockTool>() | ||
.WithTools<CalculatorTool>() | ||
.WithTools<UserInfoTool>(); | ||
|
||
var app = builder.Build(); | ||
|
||
// Map MCP with route parameter for tool category filtering | ||
app.MapMcp("/{toolCategory?}"); | ||
|
||
app.Run(); | ||
|
||
// Helper method to populate the tool dictionary at startup | ||
static void PopulateToolDictionary(ConcurrentDictionary<string, McpServerTool[]> toolDictionary) | ||
{ | ||
// Get tools for each category | ||
var clockTools = GetToolsForType<ClockTool>(); | ||
var calculatorTools = GetToolsForType<CalculatorTool>(); | ||
var userInfoTools = GetToolsForType<UserInfoTool>(); | ||
McpServerTool[] allTools = [.. clockTools, | ||
.. calculatorTools, | ||
.. userInfoTools]; | ||
|
||
// Populate the dictionary with tools for each category | ||
toolDictionary.TryAdd("clock", clockTools); | ||
toolDictionary.TryAdd("calculator", calculatorTools); | ||
toolDictionary.TryAdd("userinfo", userInfoTools); | ||
toolDictionary.TryAdd("all", allTools); | ||
} | ||
|
||
// Helper method to get tools for a specific type using reflection | ||
static McpServerTool[] GetToolsForType<[System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers( | ||
System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicMethods)] T>() | ||
{ | ||
var tools = new List<McpServerTool>(); | ||
var toolType = typeof(T); | ||
var methods = toolType.GetMethods(BindingFlags.Public | 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()); | ||
tools.Add(tool); | ||
} | ||
catch (Exception ex) | ||
{ | ||
// Log error but continue with other tools | ||
Console.WriteLine($"Failed to add tool {toolType.Name}.{method.Name}: {ex.Message}"); | ||
} | ||
} | ||
|
||
return [.. tools]; | ||
} |
13 changes: 13 additions & 0 deletions
13
samples/AspNetCoreMcpPerSessionTools/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" | ||
} | ||
} | ||
} | ||
} |
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,113 @@ | ||
# ASP.NET Core MCP Server with Per-Session Tool Filtering | ||
|
||
This sample demonstrates how to create an MCP (Model Context Protocol) server that provides different sets of tools based on route-based session configuration. This showcases the technique of using `ConfigureSessionOptions` to dynamically modify the `ToolCollection` based on route parameters for each MCP session. | ||
|
||
## Overview | ||
|
||
The sample demonstrates route-based tool filtering using the SDK's `ConfigureSessionOptions` callback. You could use any mechanism, routing is just one way to achieve this. The point of the sample is to show how an MCP server can dynamically adjust the available tools for each session based on arbitrary criteria, in this case, the URL route. | ||
|
||
## Route-Based Configuration | ||
|
||
The server uses route parameters to determine which tools to make available: | ||
|
||
- `GET /clock` - MCP server with only clock/time tools | ||
- `GET /calculator` - MCP server with only calculation tools | ||
- `GET /userinfo` - MCP server with only session/system info tools | ||
- `GET /all` or `GET /` - MCP server with all tools (default) | ||
|
||
## Running the Sample | ||
|
||
1. Navigate to the sample directory: | ||
```bash | ||
cd samples/AspNetCoreMcpPerSessionTools | ||
``` | ||
|
||
2. Run the server: | ||
```bash | ||
dotnet run | ||
``` | ||
|
||
3. The server will start on `https://localhost:5001` (or the port shown in the console) | ||
|
||
## Testing Tool Categories | ||
|
||
### Testing Clock Tools | ||
Connect your MCP client to: `https://localhost:5001/clock` | ||
- Available tools: GetTime, GetDate, ConvertTimeZone | ||
|
||
### Testing Calculator Tools | ||
Connect your MCP client to: `https://localhost:5001/calculator` | ||
- Available tools: Calculate, CalculatePercentage, SquareRoot | ||
|
||
### Testing UserInfo Tools | ||
Connect your MCP client to: `https://localhost:5001/userinfo` | ||
- Available tools: GetUserInfo | ||
|
||
### Testing All Tools | ||
Connect your MCP client to: `https://localhost:5001/all` or `https://localhost:5001/` | ||
- Available tools: All tools from all categories | ||
|
||
## How It Works | ||
|
||
### 1. Tool Registration | ||
All tools are registered during startup using the normal MCP tool registration: | ||
|
||
```csharp | ||
builder.Services.AddMcpServer() | ||
.WithTools<ClockTool>() | ||
.WithTools<CalculatorTool>() | ||
.WithTools<UserInfoTool>(); | ||
``` | ||
|
||
### 2. Route-Based Session Filtering | ||
The key technique is using `ConfigureSessionOptions` to modify the tool collection per session based on the route: | ||
|
||
```csharp | ||
.WithHttpTransport(options => | ||
{ | ||
options.ConfigureSessionOptions = async (httpContext, mcpOptions, cancellationToken) => | ||
{ | ||
var toolCategory = GetToolCategoryFromRoute(httpContext); | ||
var toolCollection = mcpOptions.Capabilities?.Tools?.ToolCollection; | ||
|
||
if (toolCollection != null) | ||
{ | ||
// Clear all tools and add back only those for this category | ||
toolCollection.Clear(); | ||
|
||
switch (toolCategory?.ToLower()) | ||
{ | ||
case "clock": | ||
AddToolsForType<ClockTool>(toolCollection); | ||
break; | ||
case "calculator": | ||
AddToolsForType<CalculatorTool>(toolCollection); | ||
break; | ||
case "userinfo": | ||
AddToolsForType<UserInfoTool>(toolCollection); | ||
break; | ||
default: | ||
// All tools for default/all category | ||
AddToolsForType<ClockTool>(toolCollection); | ||
AddToolsForType<CalculatorTool>(toolCollection); | ||
AddToolsForType<UserInfoTool>(toolCollection); | ||
break; | ||
} | ||
} | ||
}; | ||
}) | ||
``` | ||
|
||
### 3. Route Parameter Detection | ||
The `GetToolCategoryFromRoute` method extracts the tool category from the URL route: | ||
|
||
```csharp | ||
static string? GetToolCategoryFromRoute(HttpContext context) | ||
{ | ||
if (context.Request.RouteValues.TryGetValue("toolCategory", out var categoryObj) && categoryObj is string category) | ||
{ | ||
return string.IsNullOrEmpty(category) ? "all" : category; | ||
} | ||
return "all"; // Default | ||
} | ||
``` |
81 changes: 81 additions & 0 deletions
81
samples/AspNetCoreMcpPerSessionTools/Tools/CalculatorTool.cs
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,81 @@ | ||
using ModelContextProtocol.Server; | ||
using System.ComponentModel; | ||
|
||
namespace AspNetCoreMcpPerSessionTools.Tools; | ||
|
||
/// <summary> | ||
/// Calculator tools for mathematical operations | ||
/// </summary> | ||
[McpServerToolType] | ||
public sealed class CalculatorTool | ||
{ | ||
[McpServerTool, Description("Performs basic arithmetic calculations (addition, subtraction, multiplication, division).")] | ||
public static string Calculate([Description("Mathematical expression to evaluate (e.g., '5 + 3', '10 - 2', '4 * 6', '15 / 3')")] string expression) | ||
{ | ||
try | ||
{ | ||
// Simple calculator for demo purposes - supports basic operations | ||
expression = expression.Trim(); | ||
|
||
if (expression.Contains("+")) | ||
{ | ||
var parts = expression.Split('+'); | ||
if (parts.Length == 2 && double.TryParse(parts[0].Trim(), out var a) && double.TryParse(parts[1].Trim(), out var b)) | ||
{ | ||
return $"{expression} = {a + b}"; | ||
} | ||
} | ||
else if (expression.Contains("-")) | ||
{ | ||
var parts = expression.Split('-'); | ||
if (parts.Length == 2 && double.TryParse(parts[0].Trim(), out var a) && double.TryParse(parts[1].Trim(), out var b)) | ||
{ | ||
return $"{expression} = {a - b}"; | ||
} | ||
} | ||
else if (expression.Contains("*")) | ||
{ | ||
var parts = expression.Split('*'); | ||
if (parts.Length == 2 && double.TryParse(parts[0].Trim(), out var a) && double.TryParse(parts[1].Trim(), out var b)) | ||
{ | ||
return $"{expression} = {a * b}"; | ||
} | ||
} | ||
else if (expression.Contains("/")) | ||
{ | ||
var parts = expression.Split('/'); | ||
if (parts.Length == 2 && double.TryParse(parts[0].Trim(), out var a) && double.TryParse(parts[1].Trim(), out var b)) | ||
{ | ||
if (b == 0) | ||
return "Error: Division by zero"; | ||
return $"{expression} = {a / b}"; | ||
} | ||
} | ||
|
||
return $"Cannot evaluate expression: {expression}. Supported operations: +, -, *, / (e.g., '5 + 3')"; | ||
} | ||
catch (Exception ex) | ||
{ | ||
return $"Error evaluating '{expression}': {ex.Message}"; | ||
} | ||
} | ||
|
||
[McpServerTool, Description("Calculates percentage of a number.")] | ||
public static string CalculatePercentage( | ||
[Description("The number to calculate percentage of")] double number, | ||
[Description("The percentage value")] double percentage) | ||
{ | ||
var result = (number * percentage) / 100; | ||
return $"{percentage}% of {number} = {result}"; | ||
} | ||
|
||
[McpServerTool, Description("Calculates the square root of a number.")] | ||
public static string SquareRoot([Description("The number to find square root of")] double number) | ||
{ | ||
if (number < 0) | ||
return "Error: Cannot calculate square root of negative number"; | ||
|
||
var result = Math.Sqrt(number); | ||
return $"√{number} = {result}"; | ||
} | ||
} |
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,40 @@ | ||
using ModelContextProtocol.Server; | ||
using System.ComponentModel; | ||
|
||
namespace AspNetCoreMcpPerSessionTools.Tools; | ||
|
||
/// <summary> | ||
/// Clock-related tools for time and date operations | ||
/// </summary> | ||
[McpServerToolType] | ||
public sealed class ClockTool | ||
{ | ||
[McpServerTool, Description("Gets the current server time in various formats.")] | ||
public static string GetTime() | ||
{ | ||
return $"Current server time: {DateTime.Now:yyyy-MM-dd HH:mm:ss} UTC"; | ||
} | ||
|
||
[McpServerTool, Description("Gets the current date in a specific format.")] | ||
public static string GetDate([Description("Date format (e.g., 'yyyy-MM-dd', 'MM/dd/yyyy')")] string format = "yyyy-MM-dd") | ||
{ | ||
try | ||
{ | ||
return $"Current date: {DateTime.Now.ToString(format)}"; | ||
} | ||
catch (FormatException) | ||
{ | ||
return $"Invalid format '{format}'. Using default: {DateTime.Now:yyyy-MM-dd}"; | ||
} | ||
} | ||
|
||
[McpServerTool, Description("Converts time between timezones.")] | ||
public static string ConvertTimeZone( | ||
[Description("Source timezone (e.g., 'UTC', 'EST')")] string fromTimeZone = "UTC", | ||
[Description("Target timezone (e.g., 'PST', 'GMT')")] string toTimeZone = "PST") | ||
{ | ||
// Simplified timezone conversion for demo purposes | ||
var now = DateTime.Now; | ||
return $"Time conversion from {fromTimeZone} to {toTimeZone}: {now:HH:mm:ss} (simulated)"; | ||
} | ||
} |
23 changes: 23 additions & 0 deletions
23
samples/AspNetCoreMcpPerSessionTools/Tools/UserInfoTool.cs
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,23 @@ | ||
using ModelContextProtocol.Server; | ||
using System.ComponentModel; | ||
|
||
namespace AspNetCoreMcpPerSessionTools.Tools; | ||
|
||
/// <summary> | ||
/// User information tools | ||
/// </summary> | ||
[McpServerToolType] | ||
public sealed class UserInfoTool | ||
{ | ||
[McpServerTool, Description("Gets information about the current user in the MCP session.")] | ||
public static string GetUserInfo() | ||
{ | ||
// Dummy user information for demonstration purposes | ||
return $"User Information:\n" + | ||
$"- User ID: {Guid.NewGuid():N}[..8] (simulated)\n" + | ||
$"- Username: User{new Random().Next(1, 1000)}\n" + | ||
$"- Roles: User, Guest\n" + | ||
$"- Last Login: {DateTime.Now.AddMinutes(-new Random().Next(1, 60)):HH:mm:ss}\n" + | ||
$"- Account Status: Active"; | ||
} | ||
} |
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.