Skip to content

Commit 8c0e97a

Browse files
committed
Tweaks
1 parent f92222d commit 8c0e97a

File tree

3 files changed

+12
-142
lines changed

3 files changed

+12
-142
lines changed

samples/AspNetCoreMcpPerSessionTools/Program.cs

Lines changed: 2 additions & 70 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@
1515
{
1616
// Determine tool category from route parameters
1717
var toolCategory = GetToolCategoryFromRoute(httpContext);
18-
var sessionInfo = GetSessionInfo(httpContext);
1918

2019
// Get the tool collection that we can modify per session
2120
var toolCollection = mcpOptions.Capabilities?.Tools?.ToolCollection;
@@ -51,11 +50,6 @@
5150
break;
5251
}
5352
}
54-
55-
// Optional: Log the session configuration for debugging
56-
var logger = httpContext.RequestServices.GetRequiredService<ILogger<Program>>();
57-
logger.LogInformation("Configured MCP session for category '{ToolCategory}' from {SessionInfo}, {ToolCount} tools available",
58-
toolCategory, sessionInfo, toolCollection?.Count ?? 0);
5953
};
6054
})
6155
.WithTools<ClockTool>()
@@ -75,47 +69,9 @@
7569

7670
var app = builder.Build();
7771

78-
// Add middleware to log requests for demo purposes
79-
app.Use(async (context, next) =>
80-
{
81-
var logger = context.RequestServices.GetRequiredService<ILogger<Program>>();
82-
var toolCategory = GetToolCategoryFromRoute(context);
83-
var sessionInfo = GetSessionInfo(context);
84-
85-
logger.LogInformation("Request for category '{ToolCategory}' from {SessionInfo}: {Method} {Path}",
86-
toolCategory, sessionInfo, context.Request.Method, context.Request.Path);
87-
88-
await next();
89-
});
90-
9172
// Map MCP with route parameter for tool category filtering
9273
app.MapMcp("/{toolCategory?}");
9374

94-
// Add endpoints to test different tool categories
95-
app.MapGet("/", () => Results.Text(
96-
"MCP Per-Session Tools Demo\n" +
97-
"=========================\n" +
98-
"Available endpoints:\n" +
99-
"- /clock - MCP server with clock/time tools\n" +
100-
"- /calculator - MCP server with calculation tools\n" +
101-
"- /userinfo - MCP server with session/system info tools\n" +
102-
"- /all - MCP server with all tools (default)\n" +
103-
"\n" +
104-
"Test routes:\n" +
105-
"- /test-category/{category} - Test category detection\n"
106-
));
107-
108-
app.MapGet("/test-category/{toolCategory?}", (string? toolCategory, HttpContext context) =>
109-
{
110-
var detectedCategory = GetToolCategoryFromRoute(context);
111-
var sessionInfo = GetSessionInfo(context);
112-
113-
return Results.Text($"Tool Category: {detectedCategory ?? "all (default)"}\n" +
114-
$"Session Info: {sessionInfo}\n" +
115-
$"Route Parameter: {toolCategory ?? "none"}\n" +
116-
$"Message: MCP session would be configured for '{detectedCategory ?? "all"}' tools");
117-
});
118-
11975
app.Run();
12076

12177
// Helper methods for route-based tool category detection
@@ -126,33 +82,9 @@
12682
{
12783
return string.IsNullOrEmpty(category) ? "all" : category;
12884
}
129-
130-
// Fallback: try to extract from path
131-
var path = context.Request.Path.Value?.Trim('/');
132-
if (!string.IsNullOrEmpty(path))
133-
{
134-
var segments = path.Split('/');
135-
if (segments.Length > 0)
136-
{
137-
var firstSegment = segments[0].ToLower();
138-
if (firstSegment is "clock" or "calculator" or "userinfo" or "all")
139-
{
140-
return firstSegment;
141-
}
142-
}
143-
}
144-
145-
// Default to "all" if no category specified
146-
return "all";
147-
}
14885

149-
static string GetSessionInfo(HttpContext context)
150-
{
151-
var userAgent = context.Request.Headers.UserAgent.ToString();
152-
var clientInfo = !string.IsNullOrEmpty(userAgent) ? userAgent[..Math.Min(userAgent.Length, 20)] + "..." : "Unknown";
153-
var remoteIp = context.Connection.RemoteIpAddress?.ToString() ?? "unknown";
154-
155-
return $"{clientInfo} ({remoteIp})";
86+
// Default to "all" if no category specified or empty
87+
return "all";
15688
}
15789

15890
static void AddToolsForType<[System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(

samples/AspNetCoreMcpPerSessionTools/README.md

Lines changed: 0 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -147,38 +147,3 @@ static string? GetToolCategoryFromRoute(HttpContext context)
147147
return "all"; // Default
148148
}
149149
```
150-
151-
### 4. Dynamic Tool Loading
152-
The `AddToolsForType<T>` helper method uses reflection to discover and add all tools from a specific tool type to the session's tool collection.
153-
154-
## Key Benefits
155-
156-
- **Easy Testing**: No need to manage authentication tokens or headers
157-
- **Clear Separation**: Each tool category is isolated and can be tested independently
158-
- **Flexible Architecture**: Easy to add new tool categories or modify existing ones
159-
- **Production Ready**: The same technique can be extended for production scenarios with proper routing logic
160-
- **Observable**: Built-in logging shows exactly which tools are configured for each session
161-
162-
## Adapting for Production
163-
164-
For production use, you might want to:
165-
166-
1. **Add Authentication**: Combine route-based filtering with proper authentication
167-
2. **Database-Driven Categories**: Load tool categories and permissions from a database
168-
3. **User-Specific Routing**: Use user information to determine allowed categories
169-
4. **Advanced Routing**: Support nested categories or query parameters
170-
5. **Rate Limiting**: Add rate limiting per tool category
171-
6. **Caching**: Cache tool collections for better performance
172-
173-
## Related Issues
174-
175-
- [#714](https://github.com/modelcontextprotocol/csharp-sdk/issues/714) - Support varying tools/resources per user
176-
- [#237](https://github.com/modelcontextprotocol/csharp-sdk/issues/237) - Session-specific tool configuration
177-
- [#476](https://github.com/modelcontextprotocol/csharp-sdk/issues/476) - Dynamic tool management
178-
- [#612](https://github.com/modelcontextprotocol/csharp-sdk/issues/612) - Per-session resource filtering
179-
180-
## Learn More
181-
182-
- [Model Context Protocol Specification](https://modelcontextprotocol.io/)
183-
- [ASP.NET Core MCP Integration](../../src/ModelContextProtocol.AspNetCore/README.md)
184-
- [MCP C# SDK Documentation](https://modelcontextprotocol.github.io/csharp-sdk/)

samples/AspNetCoreMcpPerSessionTools/Tools/UserInfoTool.cs

Lines changed: 10 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -4,47 +4,20 @@
44
namespace AspNetCoreMcpPerSessionTools.Tools;
55

66
/// <summary>
7-
/// User information and session-related tools
7+
/// User information tools
88
/// </summary>
99
[McpServerToolType]
1010
public sealed class UserInfoTool
1111
{
12-
[McpServerTool, Description("Gets information about the current MCP session.")]
13-
public static string GetSessionInfo()
12+
[McpServerTool, Description("Gets information about the current user in the MCP session.")]
13+
public static string GetUserInfo()
1414
{
15-
return $"MCP Session Information:\n" +
16-
$"- Session ID: {Guid.NewGuid():N}[..8] (simulated)\n" +
17-
$"- Session Start: {DateTime.Now.AddMinutes(-new Random().Next(1, 60)):HH:mm:ss}\n" +
18-
$"- Protocol Version: MCP 2025-06-18\n" +
19-
$"- Transport: HTTP";
20-
}
21-
22-
[McpServerTool, Description("Gets system information about the server environment.")]
23-
public static string GetSystemInfo()
24-
{
25-
return $"System Information:\n" +
26-
$"- Server Time: {DateTime.Now:yyyy-MM-dd HH:mm:ss} UTC\n" +
27-
$"- Platform: {Environment.OSVersion.Platform}\n" +
28-
$"- Runtime: .NET {Environment.Version}\n" +
29-
$"- Processor Count: {Environment.ProcessorCount}\n" +
30-
$"- Working Set: {Environment.WorkingSet / (1024 * 1024):F1} MB";
31-
}
32-
33-
[McpServerTool, Description("Echoes back the provided message with session context.")]
34-
public static string EchoWithContext(
35-
[Description("Message to echo back")] string message)
36-
{
37-
return $"[Session Echo] {DateTime.Now:HH:mm:ss}: {message}";
38-
}
39-
40-
[Description("Gets basic connection information about the client.")]
41-
[McpServerTool]
42-
public static string GetConnectionInfo()
43-
{
44-
return $"Connection Information:\n" +
45-
$"- Connection Type: HTTP MCP Transport\n" +
46-
$"- Connected At: {DateTime.Now.AddMinutes(-new Random().Next(1, 30)):HH:mm:ss}\n" +
47-
$"- Status: Active\n" +
48-
$"- Messages Exchanged: {new Random().Next(1, 100)} (simulated)";
15+
// Dummy user information for demonstration purposes
16+
return $"User Information:\n" +
17+
$"- User ID: {Guid.NewGuid():N}[..8] (simulated)\n" +
18+
$"- Username: User{new Random().Next(1, 1000)}\n" +
19+
$"- Roles: User, Guest\n" +
20+
$"- Last Login: {DateTime.Now.AddMinutes(-new Random().Next(1, 60)):HH:mm:ss}\n" +
21+
$"- Account Status: Active";
4922
}
5023
}

0 commit comments

Comments
 (0)