Skip to content

Per User (Client) 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
wants to merge 13 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
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>
111 changes: 111 additions & 0 deletions samples/AspNetCoreMcpPerSessionTools/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
using OpenTelemetry;
using OpenTelemetry.Metrics;
using OpenTelemetry.Trace;
using AspNetCoreMcpPerSessionTools.Tools;
using ModelContextProtocol.Server;

var builder = WebApplication.CreateBuilder(args);

// 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 = GetToolCategoryFromRoute(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 the requested category
switch (toolCategory?.ToLower())
{
case "clock":
// Clock category gets time/date tools
AddToolsForType<ClockTool>(toolCollection);
break;

case "calculator":
// Calculator category gets mathematical tools
AddToolsForType<CalculatorTool>(toolCollection);
break;

case "userinfo":
// UserInfo category gets session and system information tools
AddToolsForType<UserInfoTool>(toolCollection);
break;

case "all":
default:
// Default or "all" category gets all tools
AddToolsForType<ClockTool>(toolCollection);
AddToolsForType<CalculatorTool>(toolCollection);
AddToolsForType<UserInfoTool>(toolCollection);
break;
}
}
};
})
.WithTools<ClockTool>()
.WithTools<CalculatorTool>()
.WithTools<UserInfoTool>();

// 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();

// Map MCP with route parameter for tool category filtering
app.MapMcp("/{toolCategory?}");

app.Run();

// Helper methods for route-based tool category detection
static string? GetToolCategoryFromRoute(HttpContext context)
{
// Try to get tool category from route values
if (context.Request.RouteValues.TryGetValue("toolCategory", out var categoryObj) && categoryObj is string category)
{
return string.IsNullOrEmpty(category) ? "all" : category;
}

// Default to "all" if no category specified or empty
return "all";
}

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}");
}
}
}
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"
}
}
}
}
113 changes: 113 additions & 0 deletions samples/AspNetCoreMcpPerSessionTools/README.md
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 samples/AspNetCoreMcpPerSessionTools/Tools/CalculatorTool.cs
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}";
}
}
40 changes: 40 additions & 0 deletions samples/AspNetCoreMcpPerSessionTools/Tools/ClockTool.cs
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)";
}
}
Loading
Loading