How to add new tools by code, in addition to tools obtained by class reflection [MpcServerToolType] #1169
Replies: 2 comments
|
I am basically trying to use where tools is a dynamic content. I can add an array of custom defined tools, with this constructor: Instead of performing a reflection on a static class, i would like to call a standard class with this signature string ToolExecute(string ToolName, Dictionary<string, object> ToolArguments) How do i complete the schema in order to publish all required input parameters, with AI descriptions, and get them serialized for calling my single static ToolExecute() that will dispatch the tool invokation using the tool name and generic arguments ? |
|
For externally defined tools, create a small using System.Text.Json;
using ModelContextProtocol.Protocol;
using ModelContextProtocol.Server;
sealed record ExternalTool(string Name, string Description, JsonElement InputSchema);
sealed class ExternalMcpTool(
ExternalTool definition,
Func<string, IDictionary<string, JsonElement>, CancellationToken,
ValueTask<CallToolResult>> dispatch) : McpServerTool
{
public override Tool ProtocolTool { get; } = new()
{
Name = definition.Name,
Description = definition.Description,
InputSchema = definition.InputSchema
};
public override IReadOnlyList<object> Metadata => [];
public override ValueTask<CallToolResult> InvokeAsync(
RequestContext<CallToolRequestParams> request,
CancellationToken cancellationToken = default) =>
dispatch(
ProtocolTool.Name,
request.Params.Arguments ?? new Dictionary<string, JsonElement>(),
cancellationToken);
}Then register those alongside the reflected tools: var externalTools = definitions.Select(d =>
(McpServerTool)new ExternalMcpTool(d, ToolExecuteAsync));
services.AddMcpServer()
.WithToolsFromAssembly()
.WithTools(externalTools);
If the definitions themselves change after startup, use the SDK's dynamic primitive collection and emit |
Uh oh!
There was an error while loading. Please reload this page.
Pre-submission Checklist
Question Category
Your Question
I'm using MCP Server with Http transport (self hosted), just adding these few lines
builder.Services.AddMcpServer()
.WithHttpTransport()
.WithToolsFromAssembly();
This works like a charm, importing all decorated classes as tools. CLaude desktop sees them and can invoke them.
Now i would like to add at startup also some more "dynamic" tools, in the sense that i cannot write a decorated class with static methods, but i need to add a generic handler in order to register some custom tools (taken from an external dictionary source), and provide a generic invoke where tool execution are routed at runtime.
How can i do so ?
Can i mix static class tools and dynamic tools while initializing ?
Maybe somewhere into documentation i can find this pattern, but i didn't succeed.
Regards,
Paolo Italy
All reactions