-
Notifications
You must be signed in to change notification settings - Fork 728
Add RegisterTools API to McpClient for pre-populating tool cache #1590
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
Merged
tarekgh
merged 13 commits into
modelcontextprotocol:main
from
tarekgh:feature/register-tools-api
May 26, 2026
Merged
Changes from 3 commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
1451702
Add RegisterTools API to McpClient for pre-populating tool cache
2a15504
Merge branch 'main' into feature/register-tools-api
tarekgh dfbfdca
Fix API compat: change RegisterTools from abstract to virtual
7a817b3
Rename RegisterTools to AddKnownTools
c437f60
Address PR feedback: add RemoveKnownTools/ClearKnownTools, validate-t…
bebef8a
Make RemoveKnownTools validate-then-commit for atomicity
d45480b
Add conceptual docs for AddKnownTools/RemoveKnownTools/ClearKnownTools
46c65dc
Base virtual methods throw NotSupportedException instead of no-op
65c33d2
Document sticky registration and escape hatch in AddKnownTools docs
2bf9085
Add missing test cases for edge cases
b3929c5
Add LogDebug on tool cache miss during tools/call
495f48a
Merge remote-tracking branch 'upstream/main' into feature/register-to…
c8b87d0
Change cache-miss log to Warning, gate to HTTP transport only
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
236 changes: 236 additions & 0 deletions
236
tests/ModelContextProtocol.AspNetCore.Tests/RegisterToolsHeaderTests.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,236 @@ | ||
| using Microsoft.AspNetCore.Builder; | ||
| using Microsoft.AspNetCore.Http; | ||
| using Microsoft.AspNetCore.Http.Json; | ||
| using Microsoft.Extensions.DependencyInjection; | ||
| using ModelContextProtocol.AspNetCore.Tests.Utils; | ||
| using ModelContextProtocol.Client; | ||
| using ModelContextProtocol.Protocol; | ||
| using ModelContextProtocol.Tests.Utils; | ||
| using System.Collections.Concurrent; | ||
| using System.Text.Json; | ||
|
|
||
| namespace ModelContextProtocol.AspNetCore.Tests; | ||
|
|
||
| /// <summary> | ||
| /// Tests that <see cref="McpClient.RegisterTools"/> allows sending Mcp-Param-* headers | ||
| /// without a prior <see cref="McpClient.ListToolsAsync"/> call. | ||
| /// </summary> | ||
| public class RegisterToolsHeaderTests(ITestOutputHelper outputHelper) : KestrelInMemoryTest(outputHelper), IAsyncDisposable | ||
| { | ||
| private WebApplication? _app; | ||
|
|
||
| /// <summary> | ||
| /// Captured headers from tools/call requests, keyed by JSON-RPC request id. | ||
| /// </summary> | ||
| private readonly ConcurrentDictionary<string, Dictionary<string, string>> _capturedHeaders = new(); | ||
|
|
||
| private async Task StartAsync() | ||
| { | ||
| Builder.Services.Configure<JsonOptions>(options => | ||
| { | ||
| options.SerializerOptions.TypeInfoResolverChain.Add(McpJsonUtilities.DefaultOptions.TypeInfoResolver!); | ||
| }); | ||
| _app = Builder.Build(); | ||
|
|
||
| _app.MapPost("/mcp", (JsonRpcMessage message, HttpContext context) => | ||
| { | ||
| if (message is not JsonRpcRequest request) | ||
| { | ||
| return Results.Accepted(); | ||
| } | ||
|
|
||
| if (request.Method == "initialize") | ||
| { | ||
| return Results.Json(new JsonRpcResponse | ||
| { | ||
| Id = request.Id, | ||
| Result = JsonSerializer.SerializeToNode(new InitializeResult | ||
| { | ||
| ProtocolVersion = "DRAFT-2026-v1", | ||
| Capabilities = new() { Tools = new() }, | ||
| ServerInfo = new Implementation { Name = "header-capture-test", Version = "1.0" }, | ||
| }, McpJsonUtilities.DefaultOptions) | ||
| }); | ||
| } | ||
|
|
||
| if (request.Method == "tools/call") | ||
| { | ||
| // Capture all Mcp-Param-* headers from the incoming HTTP request | ||
| var paramHeaders = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); | ||
| foreach (var header in context.Request.Headers) | ||
| { | ||
| if (header.Key.StartsWith("Mcp-Param-", StringComparison.OrdinalIgnoreCase)) | ||
| { | ||
| paramHeaders[header.Key] = header.Value.ToString(); | ||
| } | ||
| } | ||
|
|
||
| _capturedHeaders[request.Id.ToString()!] = paramHeaders; | ||
|
|
||
| var parameters = JsonSerializer.Deserialize(request.Params, McpJsonUtilities.DefaultOptions.GetTypeInfo(typeof(CallToolRequestParams))) as CallToolRequestParams; | ||
|
|
||
| return Results.Json(new JsonRpcResponse | ||
| { | ||
| Id = request.Id, | ||
| Result = JsonSerializer.SerializeToNode(new CallToolResult | ||
| { | ||
| Content = [new TextContentBlock { Text = $"ok" }], | ||
| }, McpJsonUtilities.DefaultOptions), | ||
| }); | ||
| } | ||
|
|
||
| if (request.Method == "tools/list") | ||
| { | ||
| return Results.Json(new JsonRpcResponse | ||
| { | ||
| Id = request.Id, | ||
| Result = JsonSerializer.SerializeToNode(new ListToolsResult | ||
| { | ||
| Tools = [], | ||
| }, McpJsonUtilities.DefaultOptions), | ||
| }); | ||
| } | ||
|
|
||
| return Results.Accepted(); | ||
| }); | ||
|
|
||
| await _app.StartAsync(TestContext.Current.CancellationToken); | ||
|
|
||
| HttpClient.DefaultRequestHeaders.Accept.Add(new("application/json")); | ||
| HttpClient.DefaultRequestHeaders.Accept.Add(new("text/event-stream")); | ||
| } | ||
|
|
||
| public async ValueTask DisposeAsync() | ||
| { | ||
| if (_app is not null) | ||
| { | ||
| await _app.DisposeAsync(); | ||
| } | ||
| base.Dispose(); | ||
| } | ||
|
|
||
| private static Tool CreateToolWithHeaders() | ||
| { | ||
| var schemaJson = """ | ||
| { | ||
| "type": "object", | ||
| "properties": { | ||
| "region": { | ||
| "type": "string", | ||
| "x-mcp-header": "Region" | ||
| }, | ||
| "priority": { | ||
| "type": "integer", | ||
| "x-mcp-header": "Priority" | ||
| } | ||
| }, | ||
| "required": ["region", "priority"] | ||
| } | ||
| """; | ||
|
|
||
| return new Tool | ||
| { | ||
| Name = "my_tool", | ||
| InputSchema = JsonDocument.Parse(schemaJson).RootElement.Clone(), | ||
| }; | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task RegisterTools_ThenCallTool_SendsMcpParamHeaders_WithoutListToolsAsync() | ||
| { | ||
| await StartAsync(); | ||
|
|
||
| await using var transport = new HttpClientTransport(new() | ||
| { | ||
| Endpoint = new("http://localhost:5000/mcp"), | ||
| TransportMode = HttpTransportMode.StreamableHttp, | ||
| }, HttpClient, LoggerFactory); | ||
|
|
||
| await using var client = await McpClient.CreateAsync(transport, loggerFactory: LoggerFactory, | ||
| cancellationToken: TestContext.Current.CancellationToken); | ||
|
|
||
| // Register the tool WITHOUT calling ListToolsAsync first — this is the core scenario from issue #1577 | ||
| client.RegisterTools([CreateToolWithHeaders()]); | ||
|
|
||
| // Call the tool | ||
| var result = await client.CallToolAsync( | ||
| "my_tool", | ||
| new Dictionary<string, object?> { ["region"] = "us-west-2", ["priority"] = 42 }, | ||
| cancellationToken: TestContext.Current.CancellationToken); | ||
|
|
||
| Assert.NotNull(result); | ||
|
|
||
| // Verify that Mcp-Param-* headers were captured by the server | ||
| Assert.Single(_capturedHeaders); | ||
| var headers = _capturedHeaders.Values.First(); | ||
| Assert.True(headers.ContainsKey("Mcp-Param-Region"), "Expected Mcp-Param-Region header to be sent"); | ||
| Assert.Equal("us-west-2", headers["Mcp-Param-Region"]); | ||
| Assert.True(headers.ContainsKey("Mcp-Param-Priority"), "Expected Mcp-Param-Priority header to be sent"); | ||
| Assert.Equal("42", headers["Mcp-Param-Priority"]); | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task CallToolWithoutRegisterOrList_DoesNotSendMcpParamHeaders() | ||
| { | ||
| await StartAsync(); | ||
|
|
||
| await using var transport = new HttpClientTransport(new() | ||
| { | ||
| Endpoint = new("http://localhost:5000/mcp"), | ||
| TransportMode = HttpTransportMode.StreamableHttp, | ||
| }, HttpClient, LoggerFactory); | ||
|
|
||
| await using var client = await McpClient.CreateAsync(transport, loggerFactory: LoggerFactory, | ||
| cancellationToken: TestContext.Current.CancellationToken); | ||
|
|
||
| // Call the tool without RegisterTools or ListToolsAsync — no Mcp-Param-* headers should be sent | ||
| var result = await client.CallToolAsync( | ||
| "my_tool", | ||
| new Dictionary<string, object?> { ["region"] = "us-west-2", ["priority"] = 42 }, | ||
| cancellationToken: TestContext.Current.CancellationToken); | ||
|
|
||
| Assert.NotNull(result); | ||
|
|
||
| // Verify that NO Mcp-Param-* headers were sent | ||
| Assert.Single(_capturedHeaders); | ||
| var headers = _capturedHeaders.Values.First(); | ||
| Assert.Empty(headers); | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task RegisterTools_SurvivesListToolsAsync_HeadersStillSent() | ||
| { | ||
| await StartAsync(); | ||
|
|
||
| await using var transport = new HttpClientTransport(new() | ||
| { | ||
| Endpoint = new("http://localhost:5000/mcp"), | ||
| TransportMode = HttpTransportMode.StreamableHttp, | ||
| }, HttpClient, LoggerFactory); | ||
|
|
||
| await using var client = await McpClient.CreateAsync(transport, loggerFactory: LoggerFactory, | ||
| cancellationToken: TestContext.Current.CancellationToken); | ||
|
|
||
| // Register the tool first | ||
| client.RegisterTools([CreateToolWithHeaders()]); | ||
|
|
||
| // Call ListToolsAsync — server returns empty list, but registered tool should survive | ||
| await client.ListToolsAsync(cancellationToken: TestContext.Current.CancellationToken); | ||
|
|
||
| // Call the registered tool — Mcp-Param-* headers should still be sent | ||
| var result = await client.CallToolAsync( | ||
| "my_tool", | ||
| new Dictionary<string, object?> { ["region"] = "eu-central-1", ["priority"] = 99 }, | ||
| cancellationToken: TestContext.Current.CancellationToken); | ||
|
|
||
| Assert.NotNull(result); | ||
|
|
||
| // Verify headers were sent | ||
| Assert.Single(_capturedHeaders); | ||
| var headers = _capturedHeaders.Values.First(); | ||
| Assert.True(headers.ContainsKey("Mcp-Param-Region"), "Expected Mcp-Param-Region header after ListToolsAsync"); | ||
| Assert.Equal("eu-central-1", headers["Mcp-Param-Region"]); | ||
| Assert.True(headers.ContainsKey("Mcp-Param-Priority"), "Expected Mcp-Param-Priority header after ListToolsAsync"); | ||
| Assert.Equal("99", headers["Mcp-Param-Priority"]); | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.