Skip to content

fix(event-handler): make Bedrock Agent Function tool classes and ASP.NET Core work under Native AOT - #1372

Merged
hjgraca merged 5 commits into
developfrom
fix/bedrock-aot-tools
Nov 25, 2026
Merged

hjgraca merged 5 commits into
developfrom
fix/bedrock-aot-tools

Conversation

@hjgraca

@hjgraca hjgraca commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Issue number: closes #1351

Summary

Changes

#1352 marked the reflection-based Bedrock tool APIs as not AOT compatible. This PR makes [BedrockFunctionType] tool classes and the ASP.NET Core package work under Native AOT. There are no public API additions.

 BedrockResolverExtensions
-  [RequiresUnreferencedCode] [RequiresDynamicCode]   RegisterTool<[DAM(PublicMethods)] T>()
+                                                     RegisterTool<[DAM(PublicMethods)] T>()
 BedrockMinimalApiExtensions (AspNetCore)
-  [RequiresUnreferencedCode] [RequiresDynamicCode]   MapBedrockToolType<[DAM(PublicMethods)] T>()
+                                                     MapBedrockToolType<[DAM(PublicMethods)] T>()
   [RequiresUnreferencedCode] [RequiresDynamicCode]   Tool(name, [description,] Delegate), Tool<TResult>(...), MapBedrockFunction(app, name, Delegate)   // unchanged, new message

How RegisterTool<T> works now:

 RegisterTool<T>()
   foreach public static method with [BedrockFunctionTool]          // kept by DAM(PublicMethods), with parameter names
-    Expression.GetDelegateType(...) + Delegate.CreateDelegate(...)   // Func<string, int, string>: no native code under AOT
-    Tool(name, description, Delegate)                                 // handler.Method + DynamicInvoke
+    RegisterBoundTool(name, ParameterMapper.GetToolParameters(method), args => method.Invoke(null, args))
       ParameterMapper.MapParameters((Type, name)[], request, context, services)   // shared with Delegate tools
       ResultConverter.ProcessResult<object>(result, ...)
  • Same binding as the Delegate path. Both paths use the same ParameterMapper code, now driven by (Type, name) pairs instead of a MethodInfo. Names match case-insensitively. The same types convert (string, int, long, double, bool, decimal, enums, arrays). Missing values become defaults. ILambdaContext, BedrockFunctionRequest and DI services bind by type, and custom types deserialize from InputText. Error messages are the same, and Task<T> results are awaited.
  • Custom types. The reflection-based JsonSerializer.Deserialize(string, Type, ...) fallback (used when no IJsonTypeInfoResolver is passed) now sits behind JsonSerializer.IsReflectionEnabledByDefault && RuntimeFeatureWrapper.IsDynamicCodeSupported, in a small [ExcludeFromCodeCoverage] helper. Neither analyzer recognizes that guard (net8.0 and net10.0), so the helper has justified [UnconditionalSuppressMessage] attributes, the same approach as fix(tracing): capture async responses under Native AOT and remove Powertools AOT warnings #1353. Under AOT the parameter is null unless the resolver has a JsonSerializerContext. Before, the same call threw inside a catch and also gave null.
  • ASP.NET Core endpoint. It was mapped with MapPost("/", async (HttpContext) => IResult), which goes through RequestDelegateFactory, and the response was written with reflection-based JSON. Both fail under AOT, and [UnconditionalSuppressMessage] attributes hid them. The endpoint is now a RequestDelegate, and the response, the 400 body and the ProblemDetails fallback use the package's source-generated context. An app-registered IProblemDetailsService is still used first, as ProblemHttpResult does.
  • Delegate tools. They can't work under AOT: ILC keeps no metadata for a lambda's method, so Delegate.Method throws and the parameter names are gone. They keep [RequiresUnreferencedCode]/[RequiresDynamicCode], and the warning now points to tool classes.

User experience

Under Native AOT, tools with parameters are defined as a tool class, and register with no warnings:

[BedrockFunctionType]
public class WeatherTools
{
    [BedrockFunctionTool(Name = "GetWeather", Description = "Gets the weather forecast for a city")]
    public static string GetWeather(string city, int days, TemperatureUnit unit) => $"...";
}

var resolver = new BedrockAgentFunctionResolver().RegisterTool<WeatherTools>();
app.MapBedrockToolType<WeatherTools>();   // ASP.NET Core

Delegate tools still warn at the call site:

Program.cs(14,1): warning IL3050: Using member 'BedrockAgentFunctionResolver.Tool(String, String, Delegate)' which has 'RequiresDynamicCodeAttribute' ... Define the tool as a static method of a [BedrockFunctionType] class and register it with RegisterTool<T>(), or use a Tool overload that takes a Func<BedrockFunctionRequest, ...> or a Func<string>.

JIT behavior doesn't change. Docs:

  • The AOT section of bedrock_agent_function.md is now a "Native AOT" section that says which APIs to use (tool classes, plus the typed Func<BedrockFunctionRequest, ...> / Func<string> overloads).
  • New snippet docs/snippets/bedrock-agent-function/NativeAot.cs: a tool class, its registration with the Lambda runtime and a source-generated context, and ASP.NET Core.
  • The custom-type AOT example is now a tool class with the user's JsonSerializerContext.
  • The package readmes no longer claim full AOT compatibility.

Evidence

Native AOT runtime (.NET 10, PublishAot=true, packages packed locally from develop and from this branch, same app run under JIT and as a native binary):

API JIT (develop and this PR) Native AOT, develop Native AOT, this PR
Tool(name, Func<BedrockFunctionRequest, BedrockFunctionResponse>), Tool(name, Func<string>) works works works
Tool(name, description, (string city, int days) => ...) (Delegate) works every call: Cannot retrieve a MethodInfo for this delegate ... (warns) unchanged, warns with the new message
RegisterTool<T>(): (string, int), (double, bool), long -> int, (string, enum, int?, bool?), missing params, Task<string>, BedrockFunctionRequest param, throwing tool, invalid enum works throws at registration: Func<Double, Boolean, String> is missing native code (warns) works, output identical to JIT, no warning
RegisterTool<T>(), custom type from InputText with a JsonSerializerContext works throws at registration works
RegisterTool<T>(), custom type without a context deserialized throws at registration null (documented)
AspNetCore MapBedrockToolType<T>() works throws at registration (warns) works, no warning
AspNetCore endpoint (any mapping) works building the endpoint throws NotSupportedException: JsonTypeInfo metadata for type Task<IResult> 200 / 400 / 500 bodies identical to JIT
AspNetCore MapBedrockFunction(name, Delegate) works endpoint throws (see above) endpoint works, the tool returns the MethodInfo error (warns)

The JIT responses of the ASP.NET Core endpoint (200 for a tool, 200 for an unknown tool, 400 for null) are byte-identical to develop. The 500 ProblemDetails body has the same content, but ' is now escaped as \u0027, because the source-generated context uses the default encoder rather than ASP.NET Core's JsonOptions.

Native AOT publish warnings (each package with TrimmerRootAssembly): EventHandler 0, BedrockAgentFunction 0, BedrockAgentFunction.AspNetCore 0, on both develop and this branch. The AspNetCore 0 on develop came from the suppressions, which are now removed.

Unit tests (EventHandler.Tests, 189 passed on net8.0 and on net10.0):

RegisterToolTests           multi-parameter (string, int, bool, enum, int?), same output as the Delegate overload,
                            defaults, method-name fallback, async + context, sync and async exception messages,
                            types without [BedrockFunctionType]
NativeAotCompatibilityTests RegisterTool<T> has no RUC/RDC and keeps DAM(PublicMethods)   (red before, green after)
                            Delegate overloads still have RUC/RDC
BedrockMinimalApiExtensionsTests (new, AspNetCore had no tests): MapBedrockToolType, Delegate mapping,
                            annotations, endpoint 200/400/500 bodies, app IProblemDetailsService

The full Release build from libraries/ (dotnet restore && dotnet build -c Release --no-restore) has 0 errors and no new warnings. dotnet build docs/snippets passes.

Merge Danger

Door: two-way

No signatures change. Two methods lose [RequiresUnreferencedCode]/[RequiresDynamicCode], which could be added back.

Blast Radius: narrow

  • JIT behavior of the existing APIs doesn't change. RegisterTool<T> now calls MethodInfo.Invoke instead of DynamicInvoke. Arguments are the same, and so is the unwrapping of TargetInvocationException into the tool's own error message.
  • ASP.NET Core: the endpoint no longer goes through RequestDelegateFactory, so route-handler filters and endpoint metadata from the delegate don't apply. The library added none. The ProblemDetails fallback ignores customizations to the app's JsonOptions. An IProblemDetailsService is still honored.

Follow-ups, not in this PR:

  • A source generator could make lambda tools AOT-safe later.
  • Nullable parameters (int?, bool?) aren't bound by either path, as before.
  • Without a resolver in DI, each MapBedrockFunction call creates its own resolver, and only the first one gets the endpoint.

Checklist

Is this a breaking change?

RFC issue number:

Checklist:

  • Migration process documented
  • Implement warnings (if it can live side by side)

Acknowledgment

By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.

Disclaimer: We value your time and bandwidth. As such, any pull requests created on non-triaged issues might not be successful.

…> for Bedrock Agent Functions

Add Tool<T1..T8, TResult>(name, description, handler, parameterName1..N)
overloads that bind parameters by name without reading the delegate with
reflection. RegisterTool<T> now invokes the tool methods kept by
[DynamicallyAccessedMembers(PublicMethods)] instead of creating typed
delegates, so it no longer needs [RequiresUnreferencedCode] or
[RequiresDynamicCode]. The reflection-based JSON fallback for custom types
is guarded by JsonSerializer.IsReflectionEnabledByDefault.

Refs #1351
…oint work under Native AOT

Map the endpoint with a RequestDelegate instead of a Delegate that needs
RequestDelegateFactory, and write responses with source-generated
serialization. Remove the UnconditionalSuppressMessage attributes that hid
both problems. Add the named-parameter MapBedrockFunction overloads and drop
[RequiresUnreferencedCode]/[RequiresDynamicCode] from MapBedrockToolType<T>.

Refs #1351
@hjgraca hjgraca added bug Unexpected, reproducible and unintended software behaviour event_handlers aot labels Nov 25, 2026
@boring-cyborg boring-cyborg Bot added documentation Improvements or additions to documentation tests labels Nov 25, 2026
@powertools-for-aws-oss-automation powertools-for-aws-oss-automation Bot added the size/XXL Denotes a PR that changes 1000+ lines, ignoring generated files. label Nov 25, 2026
@codecov

codecov Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 93.45794% with 7 lines in your changes missing coverage. Please review.
✅ Project coverage is 80.43%. Comparing base (57c40dc) to head (a1b7d5d).
⚠️ Report is 1 commits behind head on develop.

Files with missing lines Patch % Lines
...drockAgentFunction/BedrockAgentFunctionResolver.cs 91.17% 1 Missing and 2 partials ⚠️
...rs.BedrockAgentFunction/Helpers/ParameterMapper.cs 90.62% 0 Missing and 3 partials ⚠️
...Function.AspNetCore/BedrockMinimalApiExtensions.cs 97.36% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##           develop    #1372      +/-   ##
===========================================
+ Coverage    80.29%   80.43%   +0.13%     
===========================================
  Files          303      305       +2     
  Lines        12962    13058      +96     
  Branches      1551     1559       +8     
===========================================
+ Hits         10408    10503      +95     
- Misses        2098     2102       +4     
+ Partials       456      453       -3     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

… tool classes under AOT

Remove the Tool<T1..T8, TResult> and MapBedrockFunction<T1..T8, TResult>
overloads that took parameter names, and their tests. Under Native AOT,
tools with parameters are [BedrockFunctionType] classes registered with
RegisterTool<T>() or MapBedrockToolType<T>(). Point the Delegate overloads'
AOT warning and the docs at tool classes.

Refs #1351
@powertools-for-aws-oss-automation powertools-for-aws-oss-automation Bot added size/XL Denotes a PR that changes 500-999 lines, ignoring generated files. and removed size/XXL Denotes a PR that changes 1000+ lines, ignoring generated files. labels Nov 25, 2026
@hjgraca hjgraca changed the title fix(event-handler): AOT-safe tool registration for Bedrock Agent Functions fix(event-handler): make Bedrock Agent Function tool classes and ASP.NET Core work under Native AOT Nov 25, 2026
@sonarqubecloud

Copy link
Copy Markdown

@hjgraca
hjgraca merged commit 11b9d9f into develop Nov 25, 2026
11 checks passed
@hjgraca
hjgraca deleted the fix/bedrock-aot-tools branch November 25, 2026 18:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

aot bug Unexpected, reproducible and unintended software behaviour documentation Improvements or additions to documentation event_handlers size/XL Denotes a PR that changes 500-999 lines, ignoring generated files. tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug: Bedrock Agent Function Delegate tools and RegisterTool<T> don't work under Native AOT

1 participant