Skip to content

Rename AspNetCoreMcpServerPerUserTools to AspNetCoreMcpPerSessionTools with route-based filtering #2

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

Merged
merged 3 commits into from
Aug 22, 2025
Merged
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
179 changes: 179 additions & 0 deletions samples/AspNetCoreMcpPerSessionTools/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
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);
var sessionInfo = GetSessionInfo(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;
}
}

// Optional: Log the session configuration for debugging
var logger = httpContext.RequestServices.GetRequiredService<ILogger<Program>>();
logger.LogInformation("Configured MCP session for category '{ToolCategory}' from {SessionInfo}, {ToolCount} tools available",
toolCategory, sessionInfo, toolCollection?.Count ?? 0);
};
})
.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();

// Add middleware to log requests for demo purposes
app.Use(async (context, next) =>
{
var logger = context.RequestServices.GetRequiredService<ILogger<Program>>();
var toolCategory = GetToolCategoryFromRoute(context);
var sessionInfo = GetSessionInfo(context);

logger.LogInformation("Request for category '{ToolCategory}' from {SessionInfo}: {Method} {Path}",
toolCategory, sessionInfo, context.Request.Method, context.Request.Path);

await next();
});

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

// Add endpoints to test different tool categories
app.MapGet("/", () => Results.Text(
"MCP Per-Session Tools Demo\n" +
"=========================\n" +
"Available endpoints:\n" +
"- /clock - MCP server with clock/time tools\n" +
"- /calculator - MCP server with calculation tools\n" +
"- /userinfo - MCP server with session/system info tools\n" +
"- /all - MCP server with all tools (default)\n" +
"\n" +
"Test routes:\n" +
"- /test-category/{category} - Test category detection\n"
));

app.MapGet("/test-category/{toolCategory?}", (string? toolCategory, HttpContext context) =>
{
var detectedCategory = GetToolCategoryFromRoute(context);
var sessionInfo = GetSessionInfo(context);

return Results.Text($"Tool Category: {detectedCategory ?? "all (default)"}\n" +
$"Session Info: {sessionInfo}\n" +
$"Route Parameter: {toolCategory ?? "none"}\n" +
$"Message: MCP session would be configured for '{detectedCategory ?? "all"}' tools");
});

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;
}

// Fallback: try to extract from path
var path = context.Request.Path.Value?.Trim('/');
if (!string.IsNullOrEmpty(path))
{
var segments = path.Split('/');
if (segments.Length > 0)
{
var firstSegment = segments[0].ToLower();
if (firstSegment is "clock" or "calculator" or "userinfo" or "all")
{
return firstSegment;
}
}
}

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

static string GetSessionInfo(HttpContext context)
{
var userAgent = context.Request.Headers.UserAgent.ToString();
var clientInfo = !string.IsNullOrEmpty(userAgent) ? userAgent[..Math.Min(userAgent.Length, 20)] + "..." : "Unknown";
var remoteIp = context.Connection.RemoteIpAddress?.ToString() ?? "unknown";

return $"{clientInfo} ({remoteIp})";
}

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}");
}
}
}
184 changes: 184 additions & 0 deletions samples/AspNetCoreMcpPerSessionTools/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
# 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 MCP SDK's `ConfigureSessionOptions` callback. Instead of using authentication headers, this approach uses URL routes to determine which tools are available to each MCP session, making it easy to test different tool configurations.

## Features

- **Route-Based Tool Filtering**: Different routes expose different tool sets
- **Three Tool Categories**:
- **Clock**: Time and date related tools (`/clock`)
- **Calculator**: Mathematical calculation tools (`/calculator`)
- **UserInfo**: Session and system information tools (`/userinfo`)
- **Dynamic Tool Loading**: Tools are filtered per session based on the route used to connect
- **Easy Testing**: Simple URL-based testing without complex authentication setup
- **Comprehensive Logging**: Logs session configuration and tool access for monitoring

## Tool Categories

### Clock Tools (`/clock`)
- **GetTime**: Gets the current server time
- **GetDate**: Gets the current date in various formats
- **ConvertTimeZone**: Converts time between timezones (simulated)

### Calculator Tools (`/calculator`)
- **Calculate**: Performs basic arithmetic operations (+, -, *, /)
- **CalculatePercentage**: Calculates percentage of a number
- **SquareRoot**: Calculates square root of a number

### UserInfo Tools (`/userinfo`)
- **GetSessionInfo**: Gets information about the current MCP session
- **GetSystemInfo**: Gets system information about the server
- **EchoWithContext**: Echoes messages with session context
- **GetConnectionInfo**: Gets basic connection information

## 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: GetSessionInfo, GetSystemInfo, EchoWithContext, GetConnectionInfo

### Testing All Tools
Connect your MCP client to: `https://localhost:5001/all` or `https://localhost:5001/`
- Available tools: All tools from all categories

### Browser Testing
You can also test the route detection in a browser:
- `https://localhost:5001/` - Shows available endpoints
- `https://localhost:5001/test-category/clock` - Tests clock category detection
- `https://localhost:5001/test-category/calculator` - Tests calculator category detection
- `https://localhost:5001/test-category/userinfo` - Tests userinfo category detection

## 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
}
```

### 4. Dynamic Tool Loading
The `AddToolsForType<T>` helper method uses reflection to discover and add all tools from a specific tool type to the session's tool collection.

## Key Benefits

- **Easy Testing**: No need to manage authentication tokens or headers
- **Clear Separation**: Each tool category is isolated and can be tested independently
- **Flexible Architecture**: Easy to add new tool categories or modify existing ones
- **Production Ready**: The same technique can be extended for production scenarios with proper routing logic
- **Observable**: Built-in logging shows exactly which tools are configured for each session

## Adapting for Production

For production use, you might want to:

1. **Add Authentication**: Combine route-based filtering with proper authentication
2. **Database-Driven Categories**: Load tool categories and permissions from a database
3. **User-Specific Routing**: Use user information to determine allowed categories
4. **Advanced Routing**: Support nested categories or query parameters
5. **Rate Limiting**: Add rate limiting per tool category
6. **Caching**: Cache tool collections for better performance

## Related Issues

- [#714](https://github.com/modelcontextprotocol/csharp-sdk/issues/714) - Support varying tools/resources per user
- [#237](https://github.com/modelcontextprotocol/csharp-sdk/issues/237) - Session-specific tool configuration
- [#476](https://github.com/modelcontextprotocol/csharp-sdk/issues/476) - Dynamic tool management
- [#612](https://github.com/modelcontextprotocol/csharp-sdk/issues/612) - Per-session resource filtering

## Learn More

- [Model Context Protocol Specification](https://modelcontextprotocol.io/)
- [ASP.NET Core MCP Integration](../../src/ModelContextProtocol.AspNetCore/README.md)
- [MCP C# SDK Documentation](https://modelcontextprotocol.github.io/csharp-sdk/)
Loading