-
Notifications
You must be signed in to change notification settings - Fork 546
Respect DI while creating target object #688
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
dogukandemir
wants to merge
1
commit into
modelcontextprotocol:main
from
dogukandemir:bugfix/respect-di-while-creating-target-object
+85
−9
Closed
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
58 changes: 58 additions & 0 deletions
58
...lContextProtocol.Tests/Configuration/McpServerBuilderExtensionsCreateTargetHelperTests.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,58 @@ | ||
| using Microsoft.Extensions.DependencyInjection; | ||
| using ModelContextProtocol.Client; | ||
| using ModelContextProtocol.Protocol; | ||
| using ModelContextProtocol.Server; | ||
| using System.ComponentModel; | ||
|
|
||
| namespace ModelContextProtocol.Tests.Configuration; | ||
|
|
||
| public class McpServerBuilderExtensionsCreateTargetHelperTests(ITestOutputHelper testOutputHelper) | ||
| : ClientServerTestBase(testOutputHelper) | ||
| { | ||
| private const string ToolName = "Pets Service"; | ||
| private const string BaseAddress = "https://localhost:7387/pets"; | ||
|
|
||
| protected override void ConfigureServices(ServiceCollection services, IMcpServerBuilder mcpServerBuilder) | ||
| { | ||
| mcpServerBuilder.WithTools<PetsService>(); | ||
|
|
||
| services.AddHttpClient<PetsService>(client => | ||
| { | ||
| client.BaseAddress = new Uri(BaseAddress); | ||
| }); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Verifies that a typed HttpClient registered in DI is correctly injected into a server tool | ||
| /// and used by the tool implementation. This test covers the scenario described in | ||
| /// https://github.com/modelcontextprotocol/csharp-sdk/issues/685. | ||
| /// </summary> | ||
| [Fact] | ||
| public async Task Typed_HttpClient_Is_Used_By_Tool() | ||
| { | ||
| // Arrange | ||
| await using var client = await CreateMcpClientForServer(); | ||
|
|
||
| // Act | ||
| var result = await client.CallToolAsync(ToolName, cancellationToken: TestContext.Current.CancellationToken); | ||
|
|
||
| // Assert | ||
| Assert.NotNull(result.Content); | ||
| Assert.NotEmpty(result.Content); | ||
|
|
||
| var text = (result.Content[0] as TextContentBlock)?.Text; | ||
| Assert.Equal(BaseAddress, text); | ||
| } | ||
|
|
||
| [McpServerToolType] | ||
| private sealed class PetsService(HttpClient httpClient) | ||
| { | ||
| [McpServerTool(Name = ToolName)] | ||
| [Description("List all pets")] | ||
| public string GetBaseAddress() | ||
| { | ||
| // Returning HttpClient.BaseAddress for verification | ||
| return httpClient.BaseAddress?.ToString() ?? string.Empty; | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@stephentoub and I previously discussed whether or not we should try to resolve [McpServerToolType]'s directly from the DI container before using ActivatorUtilites. This is not something we do for ASP.NET Core MVC Controllers, but it is something we do for SignalR Hubs.
I can't find the conversation right now, but I remember recommending against resolving the tool/resource/prompt type from DI, because resolving SignalR Hubs from DI has been a source of bugs in SignalR in the past, and I hadn't heard people ask for MVC Controllers to get resolved directly from DI either.
I didn't consider the typed AddHttpClient scenario specifically, but MCP handlers are no different than MVC Controllers in this regard. Just as with Controllers, you have to inject the typed client into your MCP handler rather than make the MCP handler a typed client itself.
However, unlike MVC and SignalR, MCP handlers don't have currently have stateful properties like
Controller.HttpContextorHub.Clients.Caller. As it stands, it could be a perf optimization to register your handlers as singletons. The downside would be if we introduced a new handler base type in the future to make things likeIMcpServermore discoverable inside handlers.If we decide to go with this change, I think this could be simplified to the following since we always immediately resolve the service if it exists, and we're not trying to throw if the type is missing.
GitHub appears to be messing with the diff, but the above should replace lines 793-797.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I almost forgot we merged #570 which allows you to inject the current IMcpServer into constructors and not just the handler method. If someone were to inject an IMcpServer into their MCP handler type and register it as a singleton, they would run into problems.