Skip to content

builder.Services.AddHttpClient<...>() doesnt work with the class marked as [McpServerToolType] directly #685

Description

@RodgeFu

Describe the bug
I have created a simple McpServerTool class whose ctor takes a HttpClient as parameter like below:

    [McpServerToolType]
    public sealed class PetsService
    {
        private readonly HttpClient _httpClient;

        public PetsService(HttpClient httpClient)
        {
            _httpClient= httpClient;
        }

        [McpServerTool]
        [Description("List all pets")]
        public async Task<Page_Pets> ListPetsAsync(
            int? limit, string? continuationToken, CancellationToken cancellationToken = default
        )
        {...}
    }

Then in the Program.cs, I want to inject the HttpClient like below, but it seems not work:

            builder.Services.AddHttpClient<PetsService>(client =>
            {
                client.BaseAddress = new Uri("https://localhost:7387/pets");
            });

And when I am trying things around, I found if I create a wrapper class of HttpClient (i.e. HttpClientWrapper whose ctor takes HttpClient) and use that as the parameter of my McpServerTool class's ctor, then adding builder.Services.AddHttpClient<HttpClientWrapper>(...), the injection can work properly when the HttpClientWrapper is instantiated.

So is it supported to inject HttpClient against the class marked as "McpServerToolType" directly? Or did I do it in a wrong way? thanks.

Expected behavior
AddHttpClient<...>(...) can work with the class marked as "McpServerToolType" directly.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions