Class McpServerTool
- Namespace
- ModelContextProtocol.Server
- Assembly
- ModelContextProtocol.Core.dll
Represents an invocable tool used by Model Context Protocol clients and servers.
public abstract class McpServerTool : IMcpServerPrimitive
- Inheritance
-
McpServerTool
- Implements
- Derived
- Inherited Members
Remarks
McpServerTool is an abstract base class that represents an MCP tool for use in the server (as opposed to Tool, which provides the protocol representation of a tool, and McpClientTool, which provides a client-side representation of a tool). Instances of McpServerTool can be added into a IServiceCollection to be picked up automatically when McpServer is used to create an McpServer, or added into a McpServerPrimitiveCollection<T>.
Most commonly, McpServerTool instances are created using the static McpServerTool.Create methods. These methods enable creating an McpServerTool for a method, specified via a Delegate or MethodInfo, and are what are used implicitly by WithToolsFromAssembly and WithTools. The McpServerTool.Create methods create McpServerTool instances capable of working with a large variety of .NET method signatures, automatically handling how parameters are marshaled into the method from the JSON received from the MCP client, and how the return value is marshaled back into the CallToolResult that's then serialized and sent back to the client.
By default, parameters are sourced from the Arguments dictionary, which is a collection of key/value pairs, and are represented in the JSON schema for the function, as exposed in the returned McpServerTool's ProtocolTool's InputSchema. Those parameters are deserialized from the JsonElement values in that collection. There are a few exceptions to this:
- CancellationToken parameters are automatically bound to a CancellationToken provided by the McpServer and that respects any CancelledNotificationParamss sent by the client for this operation's RequestId. The parameter is not included in the generated JSON schema.
- IServiceProvider parameters are bound from the RequestContext<TParams> for this request, and are not included in the JSON schema.
- McpServer parameters are not included in the JSON schema and are bound directly to the McpServer instance associated with this request's RequestContext<TParams>. Such parameters may be used to understand what server is being used to process the request, and to interact with the client issuing the request to that server.
- IProgress<T> parameters accepting ProgressNotificationValue values are not included in the JSON schema and are bound to an IProgress<T> instance manufactured to forward progress notifications from the tool to the client. If the client included a ProgressToken in their request, progress reports issued to this instance will propagate to the client as ProgressNotification notifications with that token. If the client did not include a ProgressToken, the instance will ignore any progress reports issued to it.
- When the McpServerTool is constructed, it may be passed an IServiceProvider via Services. Any parameter that can be satisfied by that IServiceProvider according to IServiceProviderIsService will not be included in the generated JSON schema and will be resolved from the IServiceProvider provided to InvokeAsync(RequestContext<CallToolRequestParams>, CancellationToken) rather than from the argument collection.
- Any parameter attributed with FromKeyedServicesAttribute will similarly be resolved from the IServiceProvider provided to InvokeAsync(RequestContext<CallToolRequestParams>, CancellationToken) rather than from the argument collection, and will not be included in the generated JSON schema.
All other parameters are deserialized from the JsonElements in the Arguments dictionary, using the JsonSerializerOptions supplied in SerializerOptions, or if none was provided, using DefaultOptions.
In general, the data supplied via the Arguments's dictionary is passed along from the caller and should thus be considered unvalidated and untrusted. To provide validated and trusted data to the invocation of the tool, consider having the tool be an instance method, referring to data stored in the instance, or using an instance or parameters resolved from the IServiceProvider to provide data to the method.
Return values from a method are used to create the CallToolResult that is sent back to the client:
| null | Returns an empty Content list. |
| Microsoft.Extensions.AI.AIContent | Converted to a single ContentBlock object using ModelContextProtocol.AIContentExtensions.ToContent(Microsoft.Extensions.AI.AIContent). |
| string | Converted to a single TextContentBlock object with its text set to the string value. |
| ContentBlock | Returned as a single-item ContentBlock list. |
| IEnumerable<T> of Microsoft.Extensions.AI.AIContent | Each Microsoft.Extensions.AI.AIContent is converted to a ContentBlock object using ModelContextProtocol.AIContentExtensions.ToContent(Microsoft.Extensions.AI.AIContent). |
| IEnumerable<T> of ContentBlock | Returned as the ContentBlock list. |
| CallToolResult | Returned directly without modification. |
| Other types | Serialized to JSON and returned as a single ContentBlock object with Type set to "text". |
Constructors
McpServerTool()
Initializes a new instance of the McpServerTool class.
protected McpServerTool()
Properties
Metadata
Gets the metadata for this tool instance.
public abstract IReadOnlyList<object> Metadata { get; }
Property Value
Remarks
Contains attributes from the associated MethodInfo and declaring class (if any), with class-level attributes appearing before method-level attributes.
ProtocolTool
Gets the protocol Tool type for this instance.
public abstract Tool ProtocolTool { get; }
Property Value
Methods
Create(AIFunction, McpServerToolCreateOptions?)
Creates an McpServerTool that wraps the specified Microsoft.Extensions.AI.AIFunction.
public static McpServerTool Create(AIFunction function, McpServerToolCreateOptions? options = null)
Parameters
functionAIFunctionThe function to wrap.
optionsMcpServerToolCreateOptionsOptional options used in the creation of the McpServerTool to control its behavior.
Returns
Remarks
Unlike the other overloads of Create, the McpServerTool created by Create(AIFunction, McpServerToolCreateOptions?) does not provide all of the special parameter handling for MCP-specific concepts, like McpServer.
Exceptions
- ArgumentNullException
functionis null.
Create(Delegate, McpServerToolCreateOptions?)
Creates an McpServerTool instance for a method, specified via a Delegate instance.
public static McpServerTool Create(Delegate method, McpServerToolCreateOptions? options = null)
Parameters
methodDelegateThe method to be represented via the created McpServerTool.
optionsMcpServerToolCreateOptionsOptional options used in the creation of the McpServerTool to control its behavior.
Returns
- McpServerTool
The created McpServerTool for invoking
method.
Exceptions
- ArgumentNullException
methodis null.
Create(MethodInfo, Func<RequestContext<CallToolRequestParams>, object>, McpServerToolCreateOptions?)
Creates an McpServerTool instance for a method, specified via an MethodInfo for and instance method, along with a Type representing the type of the target object to instantiate each time the method is invoked.
public static McpServerTool Create(MethodInfo method, Func<RequestContext<CallToolRequestParams>, object> createTargetFunc, McpServerToolCreateOptions? options = null)
Parameters
methodMethodInfoThe instance method to be represented via the created Microsoft.Extensions.AI.AIFunction.
createTargetFuncFunc<RequestContext<CallToolRequestParams>, object>Callback used on each function invocation to create an instance of the type on which the instance method
methodwill be invoked. If the returned instance is IAsyncDisposable or IDisposable, it will be disposed of after method completes its invocation.optionsMcpServerToolCreateOptionsOptional options used in the creation of the McpServerTool to control its behavior.
Returns
- McpServerTool
The created Microsoft.Extensions.AI.AIFunction for invoking
method.
Exceptions
- ArgumentNullException
methodis null.
Create(MethodInfo, object?, McpServerToolCreateOptions?)
Creates an McpServerTool instance for a method, specified via a Delegate instance.
public static McpServerTool Create(MethodInfo method, object? target = null, McpServerToolCreateOptions? options = null)
Parameters
methodMethodInfoThe method to be represented via the created McpServerTool.
targetobjectThe instance if
methodis an instance method; otherwise, null.optionsMcpServerToolCreateOptionsOptional options used in the creation of the McpServerTool to control its behavior.
Returns
- McpServerTool
The created McpServerTool for invoking
method.
Exceptions
- ArgumentNullException
methodis null.- ArgumentException
methodis an instance method buttargetis null.
InvokeAsync(RequestContext<CallToolRequestParams>, CancellationToken)
Invokes the McpServerTool.
public abstract ValueTask<CallToolResult> InvokeAsync(RequestContext<CallToolRequestParams> request, CancellationToken cancellationToken = default)
Parameters
requestRequestContext<CallToolRequestParams>The request information resulting in the invocation of this tool.
cancellationTokenCancellationTokenThe CancellationToken to monitor for cancellation requests. The default is None.
Returns
- ValueTask<CallToolResult>
The call response from invoking the tool.
Exceptions
- ArgumentNullException
requestis null.
ToString()
Returns a string that represents the current object.
public override string ToString()
Returns
- string
A string that represents the current object.