.NET: Add factory delegate overload to MapAGUI for per-request agent resolution#6659
Open
Ashutosh0x wants to merge 2 commits into
Open
.NET: Add factory delegate overload to MapAGUI for per-request agent resolution#6659Ashutosh0x wants to merge 2 commits into
Ashutosh0x wants to merge 2 commits into
Conversation
…resolution Add a new MapAGUI overload that accepts a Func<HttpContext, CancellationToken, ValueTask<AIAgent?>> factory delegate, enabling dynamic per-request agent resolution for multi-tenant AG-UI hosting scenarios. Key changes: - New MapAGUI(pattern, agentFactory) overload that resolves agents per-request instead of capturing at startup - AgentSessionStore resolved per-request from HttpContext.RequestServices (fixes singleton-capture bug) - IsolationKeyScopedAgentSessionStore wrapping applied per-request - Returns 404 when factory returns null, 400 for null input - Full XML documentation with trust model cross-reference This implements Phase 1 of ADR-0029 for the AG-UI channel, following the approach recommended by @javiercn (Use(...) middleware pattern with per-request resolution). Fixes microsoft#2988, microsoft#3162 Related: microsoft#2343, ADR PR microsoft#6643
4 tasks
Contributor
There was a problem hiding this comment.
Pull request overview
Adds an additive AG-UI hosting API for per-request agent resolution in the .NET ASP.NET Core AG-UI endpoint builder, avoiding startup-time singleton capture and enabling multi-tenant/dynamic routing scenarios.
Changes:
- Adds a new
MapAGUI(pattern, Func<HttpContext, CancellationToken, ValueTask<AIAgent?>> agentFactory)overload for per-request agent selection. - Resolves
AgentSessionStoreandSessionIsolationKeyProviderfromHttpContext.RequestServices(per-request scope) instead ofendpoints.ServiceProvider. - Mirrors the existing AG-UI execution pipeline (run options, streaming, SSE result, and post-stream session save) for the factory-based overload.
Comment on lines
+198
to
+205
| public static IEndpointConventionBuilder MapAGUI( | ||
| this IEndpointRouteBuilder endpoints, | ||
| [StringSyntax("route")] string pattern, | ||
| Func<HttpContext, CancellationToken, ValueTask<AIAgent?>> agentFactory) | ||
| { | ||
| ArgumentNullException.ThrowIfNull(endpoints); | ||
| ArgumentNullException.ThrowIfNull(agentFactory); | ||
|
|
Author
There was a problem hiding this comment.
Good catch! Pushed 0131d01 addressing both review items:
- Tests added — 3 new unit tests for the factory delegate overload:
MapAGUI_WithFactoryDelegate_MapsEndpoint_AtSpecifiedPatternMapAGUI_WithNullFactory_ThrowsArgumentNullExceptionMapAGUI_WithFactoryDelegate_AndNullEndpoints_ThrowsArgumentNullException
These follow the same Moq + xUnit pattern used by the existing overload tests.
Comment on lines
+206
to
+214
| return endpoints.MapPost(pattern, async ([FromBody] RunAgentInput? input, HttpContext context, CancellationToken cancellationToken) => | ||
| { | ||
| if (input is null) | ||
| { | ||
| return Results.BadRequest(); | ||
| } | ||
|
|
||
| // Resolve agent per-request via factory delegate | ||
| var aiAgent = await agentFactory(context, cancellationToken).ConfigureAwait(false); |
Author
There was a problem hiding this comment.
Fixed! Extracted the shared execution pipeline into a private ExecuteAgentRequestAsync helper method. Both overloads now call into it:
- Static overload: resolves agent/session at startup, then calls
ExecuteAgentRequestAsync - Factory overload: resolves agent/session per-request, then calls
ExecuteAgentRequestAsync
This ensures the message conversion, run options, streaming pipeline, and session save logic stay in sync when AG-UI behavior changes.
Address Copilot review feedback: - Extract shared AG-UI execution pipeline into private ExecuteAgentRequestAsync helper (eliminates code duplication between static and factory MapAGUI overloads) - Add unit tests for factory delegate overload: * MapAGUI_WithFactoryDelegate_MapsEndpoint_AtSpecifiedPattern * MapAGUI_WithNullFactory_ThrowsArgumentNullException * MapAGUI_WithFactoryDelegate_AndNullEndpoints_ThrowsArgumentNullException
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Motivation and Context
This PR implements Phase 1 of ADR-0029 — the factory delegate approach recommended by @javiercn for dynamic per-request agent resolution.
The problem (confirmed in source code)
All three hosting channels currently resolve the
AIAgentandAgentSessionStoreonce at startup viaendpoints.ServiceProvider:This singleton-capture prevents:
/agents/{agentId}) — .NET: Support dynamic agent resolution in AG-UI endpoints (MapAGUI with factory delegate) #2988, .NET: Support dynamic agent resolution in AG-UI endpoints #3162The solution
New
MapAGUIoverload accepting a factory delegate:Key implementation details:
AgentSessionStoreresolved per-request fromHttpContext.RequestServices(fixes singleton-capture)IsolationKeyScopedAgentSessionStorewrapping applied per-requestMapAGUI(pattern, agent)overloads unchangedDesign decisions
Following @javiercn's guidance on #6643:
HttpContext.RequestServices(notIHttpContextAccessor)AddDbContext,AddAuthentication, etc.Scope
This PR covers AG-UI only as the first channel. OpenAI Responses and A2A have different architectures (service-based vs delegate-based) and will follow in subsequent PRs once the pattern is validated.
References
Contribution Checklist
cc @javiercn @DeagleGross @westey-m @rogerbarreto