Skip to content

Commit 01e588e

Browse files
committed
Add support for running MCP server initialization code
Clients will typically invoke ListTools right after client initialization is complete. We don't attempt to run this code as a notification handler because those don't have access to the server instance and therefore are not very useful. Running just before tools list is a good spot for post-initialized and before things can actually start running. Note that doing elicitation in this context won't work, but other notifications/logging to the client should be perfectly functional at this stage.
1 parent a988a84 commit 01e588e

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

src/Smith/McpExtensions.cs

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
using System.Text.Json;
22
using Microsoft.Extensions.DependencyInjection;
3+
using ModelContextProtocol.Protocol;
34
using ModelContextProtocol.Server;
45

56
namespace Smith;
@@ -58,5 +59,33 @@ public IMcpServerBuilder WithTool(string name, string title, string description,
5859

5960
return builder;
6061
}
62+
63+
/// <summary>
64+
/// Run the specified initializer function before listing tools (after client initialized).
65+
/// </summary>
66+
/// <param name="initializer">An initializer that has access to the server instance.</param>
67+
public IMcpServerBuilder WithInitializer(Func<IMcpServer, CancellationToken, ValueTask> initializer)
68+
{
69+
// NOTE: we wrap existing list handler so we avoid breaking existing tools.
70+
builder.Services.Configure<McpServerHandlers>(handlers => handlers.ListToolsHandler =
71+
new InitializerListTools(initializer, handlers.ListToolsHandler).Execute);
72+
73+
return builder;
74+
}
75+
}
76+
77+
class InitializerListTools(
78+
Func<IMcpServer, CancellationToken, ValueTask> initializer,
79+
Func<RequestContext<ListToolsRequestParams>, CancellationToken, ValueTask<ListToolsResult>>? handler)
80+
{
81+
public async ValueTask<ListToolsResult> Execute(RequestContext<ListToolsRequestParams> request, CancellationToken token)
82+
{
83+
await initializer(request.Server, token);
84+
85+
if (handler != null)
86+
return await handler(request, token);
87+
88+
return new ListToolsResult();
89+
}
6190
}
6291
}

0 commit comments

Comments
 (0)