Skip to content

Using WithReadResourceHandler should work if you only provide WithListResourceTemplatesHandler #123

Closed
@aaronpowell

Description

@aaronpowell

There are two ways to define resources, static resources or template resources, but only one way to define a handler.

If you want to use templated resources, it will fail to start the server with this error:

Resources capability was enabled, but ListResources and/or ReadResource handlers were not specified.

Here's sample code:

builder.Services
    .AddMcpServer()
    .WithStdioServerTransport()
    .WithListResourceTemplatesHandler((ctx, ct) =>
    {
        return Task.FromResult(new ListResourceTemplatesResult
        {
            ResourceTemplates =
            [
                new ResourceTemplate { Name = "Static Resource", Description = "A static resource with a numeric ID", UriTemplate = "test://static/resource/{id}" }
            ]
        });
    })
    .WithReadResourceHandler((ctx, ct) =>
    {
        var uri = ctx.Params?.Uri;

        if (uri is null || !uri.StartsWith("test://static/resource/"))
        {
            throw new NotSupportedException($"Unknown resource: {uri}");
        }

        int index = int.Parse(uri["test://static/resource/".Length..]) - 1;

        if (index < 0 || index >= ResourceGenerator.Resources.Count)
        {
            throw new NotSupportedException($"Unknown resource: {uri}");
        }

        var resource = ResourceGenerator.Resources[index];

        return Task.FromResult(new ReadResourceResult
        {
            Contents = [new ResourceContents
                {
                    Uri = resource.Uri,
                    MimeType = resource.MimeType,
                    Blob = resource.Description,
                    Text = resource.Description
                }
            ]
        });
    });

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions