Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@
<PackageVersion Include="Microsoft.Extensions.TimeProvider.Testing" Version="10.1.0" />
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="18.8.1" />
<PackageVersion Include="Moq" Version="4.20.72" />
<PackageVersion Include="Ollama" Version="1.15.2-dev.5" />
<PackageVersion Include="OpenTelemetry" Version="1.17.0" />
<PackageVersion Include="OpenTelemetry.Exporter.InMemory" Version="1.17.0" />
<PackageVersion Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="1.17.0" />
Expand Down
1 change: 1 addition & 0 deletions src/ModelContextProtocol.Core/McpJsonUtilities.cs
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,7 @@ internal static bool IsValidToolOutputSchema(JsonElement element) =>
// Other MCP Types
[JsonSerializable(typeof(IDictionary<string, object>))]
[JsonSerializable(typeof(IReadOnlyDictionary<string, object>))]
[JsonSerializable(typeof(List<object>))]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we know which MEAI provider produces List<object> here? FunctionInvokingChatClient forwards the provider's arguments unchanged, and MEAI's OpenAI adapter parses JSON arrays as JsonElement, which we already handle. This test constructs List<object> directly, so it doesn't establish that this is a general MEAI array gap. Could we identify the provider and cover its path?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Found tryAGI/Ollama: ConvertJsonValue in OllamaClient.ChatClient.cs uses .ToList() for JSON arrays. The same reporter filed tryAGI/Ollama#215 for read_multiple_files. Added real-provider AOT coverage through FunctionInvokingChatClient and MCP; removing the registration fails the new test, and Release/Debug pass with it.

— girishkvs's Copilot 🤖

[JsonSerializable(typeof(ProgressToken))]
[JsonSerializable(typeof(JsonElement))]
[JsonSerializable(typeof(Implementation))]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,9 @@
<TrimmerRootAssembly Include="ModelContextProtocol.Extensions.Apps" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.AI" />
<PackageReference Include="Ollama" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
using System.Net;
using System.Text;
using System.Text.Json;
using Microsoft.Extensions.AI;
using ModelContextProtocol.Client;

internal sealed class OllamaProviderArrayRegression
{
public async Task RunAsync(McpClientTool tool)
{
foreach (bool streaming in new[] { false, true })
{
await VerifyAsync(tool, streaming, """["one","two"]""", ["one", "two"]);
await VerifyAsync(tool, streaming, "[]", []);
}
}

private async Task VerifyAsync(McpClientTool tool, bool streaming, string itemsJson, string[] expectedItems)
{
using var handler = new ToolCallResponseHandler(itemsJson, streaming);
using var http = new HttpClient(handler);
using var provider = new Ollama.OllamaClient(
httpClient: http,
baseUri: new Uri("http://127.0.0.1:11434"),
disposeHttpClient: false);
using var client = new ObservingFunctionClient(provider)
{
MaximumConsecutiveErrorsPerRequest = 0,
};
var messages = new[] { new ChatMessage(ChatRole.User, "Join the supplied items.") };
var options = new ChatOptions { ModelId = "mcp-array-regression", Tools = [tool] };
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(30));
var expectedResult = $"Joined: {string.Join(',', expectedItems)}";
using var json = JsonDocument.Parse(itemsJson);
var controlResult = await tool.InvokeAsync(new() { ["items"] = json.RootElement.Clone() }, timeout.Token);
if (controlResult is not TextContent controlText ||
controlText.Text != expectedResult)
{
throw new InvalidOperationException("The already-supported JsonElement array control failed.");
}

if (streaming)
{
await foreach (var _ in client.GetStreamingResponseAsync(messages, options, timeout.Token))
{
}
}
else
{
await client.GetResponseAsync(messages, options, timeout.Token);
}

if (client.InvocationCount != 1 ||
handler.RequestCount != 1 ||
client.Items is null ||
!client.Items.SequenceEqual(expectedItems) ||
client.Result != expectedResult)
{
throw new InvalidOperationException(
$"Ollama array regression failed: streaming={streaming}, expectedItems={expectedItems.Length}, " +
$"invocations={client.InvocationCount}, requests={handler.RequestCount}, result={client.Result}.");
}

Console.WriteLine($"Ollama provider array passed: streaming={streaming}, count={expectedItems.Length}.");
}

private sealed class ObservingFunctionClient(IChatClient provider) : FunctionInvokingChatClient(provider)
{
public int InvocationCount { get; private set; }
public string[]? Items { get; private set; }
public string? Result { get; private set; }

protected override async ValueTask<object?> InvokeFunctionAsync(
FunctionInvocationContext context, CancellationToken cancellationToken)
{
InvocationCount++;
if (!context.Arguments.TryGetValue("items", out var value) ||
value is not List<object> items ||
items.Any(item => item is not string) ||
!ReferenceEquals(value, context.CallContent.Arguments?["items"]))
{
throw new InvalidOperationException("The real provider did not supply an unchanged List<object> argument.");
}

Items = items.Cast<string>().ToArray();
try
{
var result = await base.InvokeFunctionAsync(context, cancellationToken);
Result = (result as TextContent)?.Text;
return result;
}
finally
{
// The regression ends at MCP invocation, not the provider's later tool-result formatting.
context.Terminate = true;
}
}
}

private sealed class ToolCallResponseHandler(string itemsJson, bool streaming) : HttpMessageHandler
{
public int RequestCount { get; private set; }

protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
if (request.Content is null ||
request.Method != HttpMethod.Post ||
request.RequestUri?.AbsolutePath != "/api/chat" ||
++RequestCount != 1)
{
throw new InvalidOperationException("Unexpected provider request.");
}

using var document = JsonDocument.Parse(await request.Content.ReadAsStringAsync(cancellationToken));
if (document.RootElement.GetProperty("model").GetString() != "mcp-array-regression" ||
document.RootElement.GetProperty("stream").GetBoolean() != streaming)
{
throw new InvalidOperationException("The provider request did not match the scenario.");
}

var response = """
{"model":"mcp-array-regression","created_at":"2026-08-28T16:00:00Z","message":{"role":"assistant","content":"","tool_calls":[{"function":{"name":"Join","arguments":{"items":__ITEMS__}}}]},"done":true,"done_reason":"stop","eval_count":1,"prompt_eval_count":1}
""".Replace("__ITEMS__", itemsJson, StringComparison.Ordinal);
return new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(
response + "\n", Encoding.UTF8, streaming ? "application/x-ndjson" : "application/json"),
};
}
}
}
23 changes: 23 additions & 0 deletions tests/ModelContextProtocol.AotCompatibility.TestApp/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,26 @@
throw new Exception($"Unexpected result: {result}");
}

var join = tools.FirstOrDefault(t => t.Name == "Join");
if (join is null)
{
throw new Exception("Expected the Join tool.");
}

await new OllamaProviderArrayRegression().RunAsync(join);

result = await join.InvokeAsync(new() { ["items"] = new List<object> { "one", "two" } });
if (result is null || !result.ToString()!.Contains("Joined: one,two"))
{
throw new Exception($"Unexpected populated array result: {result}");
}

result = await join.InvokeAsync(new() { ["items"] = new List<object>() });
if (result is null || !result.ToString()!.Contains("Joined: "))
{
throw new Exception($"Unexpected empty array result: {result}");
}

Console.WriteLine("Success!");

[McpServerToolType]
Expand All @@ -49,4 +69,7 @@ internal sealed class AotTools
[McpServerTool(Name = "Echo")]
[McpAppUi(ResourceUri = "ui://aot/echo")]
public static string Echo(string arg) => $"Echo: {arg}";

[McpServerTool(Name = "Join")]
public static string Join(string[] items) => $"Joined: {string.Join(',', items)}";
}