Add static resources to EverythingServer sample (#361)

* Add static resources
* Apply suggestions from PR review

---------

Co-authored-by: Stephen Halter <halter73@gmail.com>
This commit is contained in:
Mike Kistler 2025-04-28 21:15:37 -05:00 • committed by GitHub
commit 2eeb61f4fa
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 27 additions and 4 deletions

View file

@ -38,13 +38,23 @@ builder.Services
.WithTools<TinyImageTool>() .WithTools<TinyImageTool>()
.WithPrompts<ComplexPromptType>() .WithPrompts<ComplexPromptType>()
.WithPrompts<SimplePromptType>() .WithPrompts<SimplePromptType>()
.WithListResourcesHandler(async (ctx, ct) =>
{
return new ListResourcesResult
{
Resources =
[
new ModelContextProtocol.Protocol.Types.Resource { Name = "Direct Text Resource", Description = "A direct text resource", MimeType = "text/plain", Uri = "test://direct/text/resource" },
]
};
})
.WithListResourceTemplatesHandler(async (ctx, ct) => .WithListResourceTemplatesHandler(async (ctx, ct) =>
{ {
return new ListResourceTemplatesResult return new ListResourceTemplatesResult
{ {
ResourceTemplates = ResourceTemplates =
[ [
new ResourceTemplate { Name = "Static Resource", Description = "A static resource with a numeric ID", UriTemplate = "test://static/resource/{id}" } new ResourceTemplate { Name = "Template Resource", Description = "A template resource with a numeric ID", UriTemplate = "test://template/resource/{id}" }
] ]
}; };
}) })
@ -52,12 +62,25 @@ builder.Services
{ {
var uri = ctx.Params?.Uri; var uri = ctx.Params?.Uri;
if (uri is null || !uri.StartsWith("test://static/resource/")) if (uri == "test://direct/text/resource")
{
return new ReadResourceResult
{
Contents = [new TextResourceContents
{
Text = "This is a direct resource",
MimeType = "text/plain",
Uri = uri,
}]
};
}
if (uri is null || !uri.StartsWith("test://template/resource/"))
{ {
throw new NotSupportedException($"Unknown resource: {uri}"); throw new NotSupportedException($"Unknown resource: {uri}");
} }
int index = int.Parse(uri["test://static/resource/".Length..]) - 1; int index = int.Parse(uri["test://template/resource/".Length..]) - 1;
if (index < 0 || index >= ResourceGenerator.Resources.Count) if (index < 0 || index >= ResourceGenerator.Resources.Count)
{ {

View file

@ -6,7 +6,7 @@ static class ResourceGenerator
{ {
private static readonly List<Resource> _resources = Enumerable.Range(1, 100).Select(i => private static readonly List<Resource> _resources = Enumerable.Range(1, 100).Select(i =>
{ {
var uri = $"test://static/resource/{i}"; var uri = $"test://template/resource/{i}";
if (i % 2 != 0) if (i % 2 != 0)
{ {
return new Resource return new Resource