Class McpServerResource
- Namespace
- ModelContextProtocol.Server
- Assembly
- ModelContextProtocol.Core.dll
Represents an invocable resource used by Model Context Protocol clients and servers.
public abstract class McpServerResource : IMcpServerPrimitive
- Inheritance
-
McpServerResource
- Implements
- Derived
- Inherited Members
Remarks
McpServerResource is an abstract base class that represents an MCP resource for use in the server (as opposed to Resource or ResourceTemplate, which provide the protocol representations of a resource). Instances of McpServerResource can be added into a IServiceCollection to be picked up automatically when McpServerFactory is used to create an IMcpServer, or added into a McpServerPrimitiveCollection<T>.
Most commonly, McpServerResource instances are created using the static McpServerResource.Create methods. These methods enable creating an McpServerResource for a method, specified via a Delegate or MethodInfo, and are what are used implicitly by WithResourcesFromAssembly and McpServerBuilderExtensions.WithResources. The McpServerResource.Create methods create McpServerResource instances capable of working with a large variety of .NET method signatures, automatically handling how parameters are marshaled into the method from the URI received from the MCP client, and how the return value is marshaled back into the ReadResourceResult that's then serialized and sent back to the client.
McpServerResource is used to represent both direct resources (e.g. "resource://example") and templated resources (e.g. "resource://example/{id}").
Read resource requests do not contain separate arguments, only a URI. However, for templated resources, portions of that URI may be considered as arguments and may be bound to parameters. Further, resource methods may accept parameters that will be bound to arguments based on their type.
- CancellationToken parameters are automatically bound to a CancellationToken provided by the IMcpServer and that respects any CancelledNotifications sent by the client for this operation's RequestId.
- IServiceProvider parameters are bound from the RequestContext<TParams> for this request.
- IMcpServer parameters are bound directly to the IMcpServer 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 bound to an IProgress<T> instance manufactured to forward progress notifications from the resource 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 McpServerResource is constructed, it may be passed an IServiceProvider via Services. Any parameter that can be satisfied by that IServiceProvider according to IServiceProviderIsService will be resolved from the IServiceProvider provided to the resource invocation rather than from the argument collection.
- Any parameter attributed with FromKeyedServicesAttribute will similarly be resolved from the IServiceProvider provided to the resource invocation rather than from the argument collection.
- All other parameters are bound from the data in the URI.
Return values from a method are used to create the ReadResourceResult that is sent back to the client:
ResourceContents | Wrapped in a list containing the single ResourceContents. |
Microsoft.Extensions.AI.TextContent | Converted to a list containing a single TextResourceContents. |
Microsoft.Extensions.AI.DataContent | Converted to a list containing a single BlobResourceContents. |
string | Converted to a list containing a single TextResourceContents. |
IEnumerable<T> of ResourceContents | Returned directly as a list of ResourceContents. |
IEnumerable<T> of Microsoft.Extensions.AI.AIContent | Converted to a list containing a TextResourceContents for each Microsoft.Extensions.AI.TextContent and a BlobResourceContents for each Microsoft.Extensions.AI.DataContent. |
IEnumerable<T> of string | Converted to a list containing a TextResourceContents, one for each string. |
Other returned types will result in an InvalidOperationException being thrown.
Constructors
McpServerResource()
Initializes a new instance of the McpServerResource class.
protected McpServerResource()
Properties
IsTemplated
Gets whether this resource is a URI template with parameters as opposed to a direct resource.
public bool IsTemplated { get; }
Property Value
ProtocolResource
Gets the protocol Resource type for this instance.
public virtual Resource? ProtocolResource { get; }
Property Value
Remarks
The ProtocolResourceTemplate property represents the underlying resource template definition as defined in the Model Context Protocol specification. It contains metadata like the resource templates's URI template, name, and description.
ProtocolResourceTemplate
Gets the protocol ResourceTemplate type for this instance.
public abstract ResourceTemplate ProtocolResourceTemplate { get; }
Property Value
Remarks
The ProtocolResourceTemplate property represents the underlying resource template definition as defined in the Model Context Protocol specification. It contains metadata like the resource templates's URI template, name, and description.
Every valid resource URI is a valid resource URI template, and thus this property always returns an instance. In contrast, the ProtocolResource property may return null if the resource template contains a parameter, in which case the resource template URI is not a valid resource URI.
Methods
Create(AIFunction, McpServerResourceCreateOptions?)
Creates an McpServerResource that wraps the specified Microsoft.Extensions.AI.AIFunction.
public static McpServerResource Create(AIFunction function, McpServerResourceCreateOptions? options = null)
Parameters
function
AIFunctionThe function to wrap.
options
McpServerResourceCreateOptionsOptional options used in the creation of the McpServerResource to control its behavior.
Returns
Remarks
Unlike the other overloads of Create, the McpServerResource created by Create(AIFunction, McpServerResourceCreateOptions?) does not provide all of the special parameter handling for MCP-specific concepts, like IMcpServer.
Exceptions
- ArgumentNullException
function
is null.
Create(Delegate, McpServerResourceCreateOptions?)
Creates an McpServerResource instance for a method, specified via a Delegate instance.
public static McpServerResource Create(Delegate method, McpServerResourceCreateOptions? options = null)
Parameters
method
DelegateThe method to be represented via the created McpServerResource.
options
McpServerResourceCreateOptionsOptional options used in the creation of the McpServerResource to control its behavior.
Returns
- McpServerResource
The created McpServerResource for invoking
method
.
Exceptions
- ArgumentNullException
method
is null.
Create(MethodInfo, Func<RequestContext<ReadResourceRequestParams>, object>, McpServerResourceCreateOptions?)
Creates an McpServerResource 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 McpServerResource Create(MethodInfo method, Func<RequestContext<ReadResourceRequestParams>, object> createTargetFunc, McpServerResourceCreateOptions? options = null)
Parameters
method
MethodInfoThe instance method to be represented via the created Microsoft.Extensions.AI.AIFunction.
createTargetFunc
Func<RequestContext<ReadResourceRequestParams>, object>Callback used on each function invocation to create an instance of the type on which the instance method
method
will be invoked. If the returned instance is IAsyncDisposable or IDisposable, it will be disposed of after method completes its invocation.options
McpServerResourceCreateOptionsOptional options used in the creation of the McpServerResource to control its behavior.
Returns
- McpServerResource
The created Microsoft.Extensions.AI.AIFunction for invoking
method
.
Exceptions
- ArgumentNullException
method
is null.
Create(MethodInfo, object?, McpServerResourceCreateOptions?)
Creates an McpServerResource instance for a method, specified via a Delegate instance.
public static McpServerResource Create(MethodInfo method, object? target = null, McpServerResourceCreateOptions? options = null)
Parameters
method
MethodInfoThe method to be represented via the created McpServerResource.
target
objectThe instance if
method
is an instance method; otherwise, null.options
McpServerResourceCreateOptionsOptional options used in the creation of the McpServerResource to control its behavior.
Returns
- McpServerResource
The created McpServerResource for invoking
method
.
Exceptions
- ArgumentNullException
method
is null.- ArgumentException
method
is an instance method buttarget
is null.
ReadAsync(RequestContext<ReadResourceRequestParams>, CancellationToken)
Gets the resource, rendering it with the provided request parameters and returning the resource result.
public abstract ValueTask<ReadResourceResult?> ReadAsync(RequestContext<ReadResourceRequestParams> request, CancellationToken cancellationToken = default)
Parameters
request
RequestContext<ReadResourceRequestParams>The request context containing information about the resource invocation, including any arguments passed to the resource. This object provides access to both the request parameters and the server context.
cancellationToken
CancellationTokenThe CancellationToken to monitor for cancellation requests. The default is None.
Returns
- ValueTask<ReadResourceResult>
A ValueTask<TResult> representing the asynchronous operation, containing a ReadResourceResult with the resource content and messages. If and only if this McpServerResource doesn't match the Uri, the method returns null.
Exceptions
- ArgumentNullException
request
is null.- InvalidOperationException
The resource implementation returned null or an unsupported result type.
ToString()
Returns a string that represents the current object.
public override string ToString()
Returns
- string
A string that represents the current object.