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 McpServer is used to create an McpServer, 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 McpServer and that respects any CancelledNotificationParamss sent by the client for this operation's RequestId.
- IServiceProvider parameters are bound from the RequestContext<TParams> for this request.
- McpServer parameters 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 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 TextContentBlock and a BlobResourceContents for each Microsoft.Extensions.AI.DataContent. |
| IEnumerable<T> of string | Converted to a list containing a TextResourceContents, one for each string. |
| ReadResourceResult | Returned directly without modification. |
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
Metadata
Gets the metadata for this resource 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.
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
functionAIFunctionThe function to wrap.
optionsMcpServerResourceCreateOptionsOptional 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 McpServer.
Exceptions
- ArgumentNullException
functionis 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
methodDelegateThe method to be represented via the created McpServerResource.
optionsMcpServerResourceCreateOptionsOptional options used in the creation of the McpServerResource to control its behavior.
Returns
- McpServerResource
The created McpServerResource for invoking
method.
Exceptions
- ArgumentNullException
methodis 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
methodMethodInfoThe instance method to be represented via the created Microsoft.Extensions.AI.AIFunction.
createTargetFuncFunc<RequestContext<ReadResourceRequestParams>, 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.optionsMcpServerResourceCreateOptionsOptional 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
methodis 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
methodMethodInfoThe method to be represented via the created McpServerResource.
targetobjectThe instance if
methodis an instance method; otherwise, null.optionsMcpServerResourceCreateOptionsOptional options used in the creation of the McpServerResource to control its behavior.
Returns
- McpServerResource
The created McpServerResource for invoking
method.
Exceptions
- ArgumentNullException
methodis null.- ArgumentException
methodis an instance method buttargetis null.
IsMatch(string)
Evaluates whether the uri matches the ProtocolResourceTemplate
and can be used as the Uri passed to ReadAsync(RequestContext<ReadResourceRequestParams>, CancellationToken).
public abstract bool IsMatch(string uri)
Parameters
uristringThe URI being evaluated for this resource.
Returns
- bool
true if the
urimatches the ProtocolResourceTemplate; otherwise, false.
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
requestRequestContext<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.
cancellationTokenCancellationTokenThe 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.
Exceptions
- ArgumentNullException
requestis null.- InvalidOperationException
The Uri did not match the ProtocolResourceTemplate for this resource, the resource implementation returned null, or the resource implementation returned 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.