Skip to content

Commit 8b8d6c9

Browse files
author
jb.muscat
committed
✅Update AspNetCore sample to showcase ToolFilter
1 parent 57859ec commit 8b8d6c9

File tree

3 files changed

+35
-1
lines changed

3 files changed

+35
-1
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
using ModelContextProtocol.Core;
2+
using ModelContextProtocol.Protocol;
3+
using ModelContextProtocol.Server;
4+
5+
namespace AspNetCoreSseServer.Attributes;
6+
7+
public class LimitCalls(int maxCalls, int order = 0) : ToolFilter(order)
8+
{
9+
private int _callCount;
10+
11+
public override ValueTask<CallToolResult>? OnToolCalling(Tool tool, RequestContext<CallToolRequestParams> context)
12+
{
13+
_callCount++;
14+
Console.Out.WriteLine($"Tool: {tool.Name} called {_callCount} time(s)");
15+
16+
if (_callCount <= maxCalls)
17+
return null; //do nothing
18+
19+
return new ValueTask<CallToolResult>(new CallToolResult()
20+
{
21+
Content = [new TextContentBlock { Text = $"This tool can only be called {maxCalls} time(s)" }]
22+
});
23+
}
24+
25+
public override bool OnToolListed(Tool tool, RequestContext<ListToolsRequestParams> context)
26+
{
27+
var configuration = context.Services?.GetService<IConfiguration>();
28+
var hide = configuration?["hide-tools-above-limit"] == "True";
29+
return hide && _callCount <= maxCalls;
30+
}
31+
}

samples/AspNetCoreSseServer/Tools/EchoTool.cs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
11
using ModelContextProtocol.Server;
22
using System.ComponentModel;
3+
using AspNetCoreSseServer.Attributes;
34

45
namespace TestServerWithHosting.Tools;
56

67
[McpServerToolType]
78
public sealed class EchoTool
89
{
910
[McpServerTool, Description("Echoes the input back to the client.")]
11+
[LimitCalls(maxCalls: 10)]
1012
public static string Echo(string message)
1113
{
1214
return "hello " + message;

samples/AspNetCoreSseServer/appsettings.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,5 +5,6 @@
55
"Microsoft.AspNetCore": "Warning"
66
}
77
},
8-
"AllowedHosts": "*"
8+
"AllowedHosts": "*",
9+
"hide-tools-above-limit": true
910
}

0 commit comments

Comments
 (0)