Use WithResources in EverythingServer sample (#400)

This commit is contained in:
Stephen Toub 2025-05-10 06:13:42 -04:00 • committed by GitHub
commit 26c3622101
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -1,5 +1,6 @@
using EverythingServer;
using EverythingServer.Prompts;
using EverythingServer.Resources;
using EverythingServer.Tools;
using Microsoft.Extensions.AI;
using Microsoft.Extensions.DependencyInjection;
@ -14,8 +15,6 @@ using OpenTelemetry.Metrics;
using OpenTelemetry.Resources;
using OpenTelemetry.Trace;
#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
var builder = Host.CreateApplicationBuilder(args);
builder.Logging.AddConsole(consoleLogOptions =>
{
@ -38,82 +37,7 @@ builder.Services
.WithTools<TinyImageTool>()
.WithPrompts<ComplexPromptType>()
.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) =>
{
return new ListResourceTemplatesResult
{
ResourceTemplates =
[
new ResourceTemplate { Name = "Template Resource", Description = "A template resource with a numeric ID", UriTemplate = "test://template/resource/{id}" }
]
};
})
.WithReadResourceHandler(async (ctx, ct) =>
{
var uri = ctx.Params?.Uri;
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}");
}
int index = int.Parse(uri["test://template/resource/".Length..]) - 1;
if (index < 0 || index >= ResourceGenerator.Resources.Count)
{
throw new NotSupportedException($"Unknown resource: {uri}");
}
var resource = ResourceGenerator.Resources[index];
if (resource.MimeType == "text/plain")
{
return new ReadResourceResult
{
Contents = [new TextResourceContents
{
Text = resource.Description!,
MimeType = resource.MimeType,
Uri = resource.Uri,
}]
};
}
else
{
return new ReadResourceResult
{
Contents = [new BlobResourceContents
{
Blob = resource.Description!,
MimeType = resource.MimeType,
Uri = resource.Uri,
}]
};
}
})
.WithResources<SimpleResourceType>()
.WithSubscribeToResourcesHandler(async (ctx, ct) =>
{
var uri = ctx.Params?.Uri;