Skip to content

AIFunctionFactory: ExcludeFromSchema is dropped under concurrent first-time creation (ParameterInfo reference-keyed cache race) #7675

Closed

Description

@jredgard

Where it belongs

Microsoft.Extensions.AI.Abstractions (AIFunctionFactory), repo dotnet/extensions. Reproduced on
10.5.2 and 10.8.3. Not an MCP SDK defect: the MCP C# SDK is how we met it, because
McpServerTool.Create uses ConfigureParameterBinding/ExcludeFromSchema to keep DI service
parameters out of a tool's JSON schema — but the repro below references no MCP package at all.

Symptom

A parameter marked ExcludeFromSchema = true appears in the generated schema's properties and
required — the exact schema the factory would have produced had the parameter never been marked.
For an MCP server that means a tool advertises its injected service as a required argument:

{"type":"object","properties":{
   "thing":{"type":"object","properties":{"value":{"type":["string","null"]}}},
   "name":{"description":"n","type":"string"},
   "aspect":{"description":"a","type":["string","null"],"default":null}},
 "required":["thing","name"]}

Repro

One file, one package, no MCP. Leaks 5–14 of 512 on every run here (.NET 10, 32-core Linux).

<PackageReference Include="Microsoft.Extensions.AI.Abstractions" Version="10.8.3" />
using System.ComponentModel;
using System.Reflection;
using System.Text.Json;
using Microsoft.Extensions.AI;

MethodInfo[] methods = typeof(Tools).GetMethods(BindingFlags.Public | BindingFlags.Static);
IThing thing = new Thing();
int leaks = 0;

Parallel.For(0, 64, _ =>
{
    foreach (MethodInfo method in methods)
    {
        JsonElement schema = Schema(method, thing);
        if (schema.TryGetProperty("required", out JsonElement required)
            && required.EnumerateArray().Any(e => e.GetString() == "thing"))
        {
            Interlocked.Increment(ref leaks);
        }
    }
});

static JsonElement Schema(MethodInfo method, IThing service)
{
    AIFunctionFactoryOptions options = new()
    {
        ConfigureParameterBinding = p => p.ParameterType == typeof(IThing)
            ? new AIFunctionFactoryOptions.ParameterBindingOptions
            {
                ExcludeFromSchema = true,
                BindParameter = (_, _) => service,
            }
            : default,
    };
    return AIFunctionFactory.Create(method, target: null, options).JsonSchema;
}

Console.WriteLine($"excluded parameter present in required: {leaks} of {64 * methods.Length}");

public interface IThing { string Value { get; } }
public sealed class Thing : IThing { public string Value => "thing"; }

public static class Tools
{
    public static string One(IThing thing, [Description("q")] string query, [Description("o")] string? optional = null)
        => $"{thing.Value}{query}{optional}";
    public static string Two(IThing thing, [Description("o")] string? optional = null) => $"{thing.Value}{optional}";
    public static string Three(IThing thing, [Description("n")] string name) => $"{thing.Value}{name}";
    public static string Four(IThing thing, [Description("n")] string name, [Description("a")] string? aspect = null)
        => $"{thing.Value}{name}{aspect}";
    public static string Five(IThing thing, [Description("q")] string query, [Description("f")] string framework)
        => $"{thing.Value}{query}{framework}";
    public static string Six(IThing thing, [Description("c")] string? category = null) => $"{thing.Value}{category}";
    public static string Seven(IThing thing, [Description("t")] string? topic = null) => $"{thing.Value}{topic}";
    public static string Eight(IThing thing) => thing.Value;
}

Two details of that repro are load-bearing, and both are things a real MCP host does:

  • Schema is a separate method taking the service as a parameter. Inline the options construction
    into the Parallel.For body, closing over the outer thing, and the compiler caches the
    ConfigureParameterBinding delegate in a single closure instance — the descriptor cache then hits
    and the leak disappears (0 of 512 in 23 runs). A fresh closure per call is what makes it miss, and
    McpServerTool.Create necessarily builds one: it has to close over the per-call options.
  • Eight methods rather than one, only so the window is hit within a run or two. One method
    reproduces it too, less often.

Insert foreach (MethodInfo m in methods) { _ = m.GetParameters(); } before Parallel.For and it
stops: 0 of 512 in 10 runs, everything else unchanged.

Root cause

ReflectionAIFunctionDescriptor's constructor builds

Dictionary<ParameterInfo, AIFunctionFactoryOptions.ParameterBindingOptions> boundParameters

from key.Method.GetParameters(), and the IncludeParameter delegate it installs looks each
parameter up in that dictionary by reference — ParameterInfo does not override Equals. The
schema generator calls IncludeParameter with ParameterInfo instances from its own
GetParameters() call.

MethodInfo.GetParameters() does not guarantee the same instances across concurrent first calls. The
runtime builds the cached array lazily and racing threads each materialise their own; one wins the
cache and the losers hold objects that will never be reference-equal to it. A thread holding a losing
array misses its own lookup, ExcludeFromSchema is silently ignored, and the parameter lands in the
schema.

Directly observed, no factory involved — 64 threads calling GetParameters()[0] on a cold
MethodInfo, counting distinct instances by ReferenceEquals:

calls=64 distinct ParameterInfo instances for parameter 0: 5
calls=64 distinct ParameterInfo instances for parameter 0: 1
calls=64 distinct ParameterInfo instances for parameter 0: 5
calls=64 distinct ParameterInfo instances for parameter 0: 5
calls=64 distinct ParameterInfo instances for parameter 0: 7

Once the cache settles it is 1 forever, which is why this is a startup phenomenon and why the
descriptor cache normally hides it: a caller whose ConfigureParameterBinding delegate is stable
builds one descriptor and reuses it, so only the very first creation is exposed. A caller who hands
in a fresh delegate every time — every MCP host — rebuilds the descriptor on every creation and stays
exposed for as long as the parameter caches are still cold.

Numbers

64 parallel iterations over 8 methods, each creation asserting the service parameter is absent from
required. Through McpServerTool.Create: mixed passes Services on half the creations, uniform
on all, shared reuses one options object, single uses one method, serial is the same work
sequentially. meai is the repro above. Each column is one run.

mode MCP 1.4.1 (MEAI 10.5.2) MCP 2.0.0 (MEAI 10.8.3)
mixed (of 256) 5, 5, 4, 1, 5 4, 4, 2, 2, 1
uniform (of 512) 7, 5, 13 7, 7, 6
shared (of 512) — 4, 12, 4
single (of 64) — 3, 6, 5
serial (of 512) — 0, 0, 0
meai, no MCP (of 512) — 7, 8, 10, 5, 6, 14, 8, 11
meai + cached delegate — 0 × 23 runs
meai + GetParameters() warm-up — 0 × 10 runs

The MCP SDK's own major version made no difference: 2.0.0 leaks at the same rate as 1.4.1, which is
expected once the defect is a layer below both.

Suggested fix

Stop keying the lookup on ParameterInfo identity. Either give the dictionary a comparer over
(Member.Module, Member.MetadataToken, Position), or — cheaper — key it on Position and check the
declaring member, since IncludeParameter is only ever called with parameters of the method the
descriptor was built for. Either makes the binding independent of which GetParameters() array a
thread happens to hold.

Anything else that maps a MemberInfo or ParameterInfo to per-method state by reference has the
same exposure and is worth the same grep.

Workaround for callers

Touch GetParameters() on every method before creating functions concurrently, or create them
sequentially once. AlgorithmMcp does neither in production — the host builds its tools once through
DI, and host-served schemas were verified correct — and serialises its test suite instead
(tests/AlgorithmMcp.Tests/AssemblyInfo.cs).

What this got wrong twice

A15 said the trigger was "concurrent creation with differing service views" — half the creations
passing McpServerToolCreateOptions.Services and half not — on the strength of a control run where
every creation passed services and leaked 0 of 512. That control does not hold up: the all-services
mode leaks at the same rate as the mixed one, and so does a single method with a single shared
options object. Differing views was an artifact of the original harness. The framing mattered: it
pointed at the MCP SDK when the defect is a layer down, and it implied a caller could stay safe by
keeping its service views uniform, which is false.

The first draft of this report then published a repro that does not reproduce. It was written by
simplifying the working harness — and one of the simplifications, inlining the options construction so
the lambda captured nothing, is exactly the condition that makes the descriptor cache hit and the
leak vanish. It ran 0 of 512 twenty-three times before the difference was found. The simplification
was not cosmetic; it removed the trigger. Nothing here is published now without having been run
verbatim from this file.

Activity

  1. self-assigned this
    on Aug 3, 2026
  2. added
    bug
    area-ai
    and removed on Aug 3, 2026
  3. added a commit that references this issue on Aug 4, 2026
    e4af6cf
  4. locked and limited conversation to collaborators on Sep 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area-aibug

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions