Skip to content

feat: Refactor agent request context handling and improve agent defin… - #125

Merged
ssdeanx merged 1 commit into
mainfrom
develop
Mar 17, 2026
Merged

ssdeanx merged 1 commit into
mainfrom
develop

Conversation

@ssdeanx

@ssdeanx ssdeanx commented Mar 17, 2026 •

Copy link
Copy Markdown
Owner

…itions

  • Introduced a new request-context.ts file to centralize request context management for agents.
  • Created a BaseAgentRequestContext interface to standardize user tier and language handling across agents.
  • Implemented utility functions getUserTierFromContext and getLanguageFromContext to simplify context retrieval.
  • Updated all agents (reportAgent, researchAgent, researchPaperAgent, scriptWriterAgent, seoAgent, socialMediaAgent, stockAnalysisAgent, translationAgent, weatherAgent, webResearchAgent) to use the new context handling methods, removing redundant code.
  • Replaced asNestedAgents usage in network definitions with direct agent assignments to improve type safety and clarity.
  • Added a new chat-request.ts file defining a schema for chat transport requests using Zod for validation.
  • Updated documentation in AGENTS.md to reflect changes in agent wiring and context handling.
  • Enhanced type definitions for agent contexts to support additional properties and improve type safety.

Summary by Sourcery

Centralize agent request context handling and nested agent wiring, simplifying runtime context access and improving type safety across agents and networks.

New Features:

  • Introduce a shared request-context helper module for agents, including standardized user tier, language, and model override handling.
  • Add a chat transport request schema for validating chat requests on the client side.

Enhancements:

  • Refactor multiple agents to use the new shared request-context helpers and safer context parsing instead of ad-hoc RequestContext typings and string keys.
  • Normalize agent tool configuration into shared tool maps per agent and remove unused imports.
  • Update network and A2A coordinator agents to register child agents directly without adapter helpers or generic casts, aligning with the new typing approach.
  • Clarify documentation for agents, A2A coordinators, and networks around nested agent registration, tool typing, and request-context usage.

Documentation:

  • Extend AGENTS.md, A2A AGENTS.md, and networks AGENTS.md with updated guidance on nested agent typing, tool typing, and recent version history entries.

Chores:

  • Update internal memory-bank notes to record the nested-agent typing cleanup, coding agent normalization, and validation status.

…itions

- Introduced a new `request-context.ts` file to centralize request context management for agents.
- Created a `BaseAgentRequestContext` interface to standardize user tier and language handling across agents.
- Implemented utility functions `getUserTierFromContext` and `getLanguageFromContext` to simplify context retrieval.
- Updated all agents (reportAgent, researchAgent, researchPaperAgent, scriptWriterAgent, seoAgent, socialMediaAgent, stockAnalysisAgent, translationAgent, weatherAgent, webResearchAgent) to use the new context handling methods, removing redundant code.
- Replaced `asNestedAgents` usage in network definitions with direct agent assignments to improve type safety and clarity.
- Added a new `chat-request.ts` file defining a schema for chat transport requests using Zod for validation.
- Updated documentation in `AGENTS.md` to reflect changes in agent wiring and context handling.
- Enhanced type definitions for agent contexts to support additional properties and improve type safety.
Copilot AI review requested due to automatic review settings March 17, 2026 08:49
@vercel

vercel Bot commented Mar 17, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
agent-stack Building Building Preview, Comment Mar 17, 2026 8:49am

@greptile-apps greptile-apps Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Your free trial has ended. If you'd like to continue receiving code reviews, you can add a payment method here.

@sourcery-ai

sourcery-ai Bot commented Mar 17, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Refactors agent request-context handling into a shared request-context module, updates many agents and networks to consume the new helpers and unified AgentRequestContext typing, replaces nestedAgents adapter usage with direct child-agent registration, and introduces a validated chat transport request schema for frontend/backend integration.

Sequence diagram for chat transport request handling with validated context

sequenceDiagram
    actor Client
    participant ChatAPI
    participant chatTransportRequestSchema
    participant request_context_module as request-context.ts
    participant AgentInstance as Agent

    Client->>ChatAPI: send ChatTransportRequest payload
    ChatAPI->>chatTransportRequestSchema: parse(payload)
    chatTransportRequestSchema-->>ChatAPI: validated_request or error
    ChatAPI->>ChatAPI: extract requestContext, memory, data.agentId

    ChatAPI->>request_context_module: buildSharedRequestContextPayload(sharedPayload)
    request_context_module-->>ChatAPI: contextRecord

    ChatAPI->>request_context_module: createAgentRequestContext(payload, identity)
    request_context_module-->>ChatAPI: RequestContext_AgentRequestContext_

    ChatAPI->>AgentInstance: invoke(messages, requestContext)
    AgentInstance->>request_context_module: getUserTierFromContext(requestContext)
    AgentInstance->>request_context_module: getLanguageFromContext(requestContext)
    AgentInstance->>request_context_module: resolveTieredModelFromContext(requestContext, models)
    request_context_module-->>AgentInstance: userTier, language, modelId

    AgentInstance-->>ChatAPI: streaming or final response
    ChatAPI-->>Client: response
Loading

File-Level Changes

Change Details Files
Centralize agent request context typing and helper utilities, and migrate agents to use them.
  • Introduce request-context.ts with shared UserTier/language constants, AgentRequestContext type, Zod schema, and helper functions for reading tier/language/model overrides from RequestContext.
  • Replace per-agent UserTier/language interfaces with AgentRequestContext-based types across many agents (coding, research, report, stock, script, research paper, etc.).
  • Update agent instructions/model selectors to use getUserTierFromContext, getLanguageFromContext, and resolveTieredModelFromContext instead of raw string keys and ad hoc defaults.
src/mastra/agents/request-context.ts
src/mastra/agents/codingAgents.ts
src/mastra/agents/researchAgent.ts
src/mastra/agents/reportAgent.ts
src/mastra/agents/scriptWriterAgent.ts
src/mastra/agents/stockAnalysisAgent.ts
src/mastra/agents/researchPaperAgent.ts
src/mastra/agents/contentStrategistAgent.ts
src/mastra/agents/evaluationAgent.ts
src/mastra/agents/editorAgent.ts
src/mastra/agents/learningExtractionAgent.ts
src/mastra/agents/financialAnalysisAgent.ts
src/mastra/agents/dataProcessingAgent.ts
src/mastra/agents/academicResearchAgent.ts
src/mastra/agents/webResearchAgent.ts
src/mastra/agents/weather-agent.ts
src/mastra/agents/excalidraw_validator.ts
src/mastra/agents/image_to_csv.ts
src/mastra/agents/image.ts
src/mastra/agents/businessLegalAgents.ts
src/mastra/agents/dane.ts
src/mastra/agents/graphingAgents.ts
Harden agent-specific runtime context parsing and factor tool maps for clarity and type safety.
  • Redefine agent-specific context types as AgentRequestContext with typed optional fields plus local constants for context keys.
  • Introduce small helper functions per agent (e.g., getChartStyleFromContext, getStrategyFromContext, getBackupDataToolsFromContext) to validate and default context values instead of trusting raw RequestContext data.
  • Factor per-agent tool maps into named constants (e.g., codeArchitectTools, chartSupervisorTools, contentStrategistTools, dataExportTools) and wire them via tools: to improve readability and infer tool typing.
src/mastra/agents/codingAgents.ts
src/mastra/agents/recharts.ts
src/mastra/agents/contentStrategistAgent.ts
src/mastra/agents/researchAgent.ts
src/mastra/agents/dataTransformationAgent.ts
src/mastra/agents/documentProcessingAgent.ts
src/mastra/agents/knowledgeIndexingAgent.ts
src/mastra/agents/stockAnalysisAgent.ts
src/mastra/agents/dataExportAgent.ts
src/mastra/agents/dataIngestionAgent.ts
src/mastra/agents/copywriterAgent.ts
src/mastra/agents/learningExtractionAgent.ts
src/mastra/agents/researchPaperAgent.ts
src/mastra/agents/scriptWriterAgent.ts
src/mastra/agents/package-publisher.ts
Remove nestedAgents adapter usage and fix nested child-agent typing at the source for agents, A2A coordinators, and networks.
  • Delete nestedAgents.ts and replace asNestedAgents(...) calls with direct object literals for agents fields across coordinators and networks.
  • Adjust child agents to expose a public Agent<..., unknown>-compatible request-context surface via AgentRequestContext, with any narrower parsing done internally, so they can be directly registered as children.
  • Update AGENTS.md docs (agents, a2a, networks) to describe the new guidance: avoid adapters and ToolsInput casts, prefer source-level unknown request context generics and internal parsing.
src/mastra/agents/nestedAgents.ts
src/mastra/a2a/codingA2ACoordinator.ts
src/mastra/a2a/a2aCoordinatorAgent.ts
src/mastra/networks/codingTeamNetwork.ts
src/mastra/networks/index.ts
src/mastra/networks/businessIntelligenceNetwork.ts
src/mastra/networks/contentCreationNetwork.ts
src/mastra/networks/dataPipelineNetwork.ts
src/mastra/networks/devopsNetwork.ts
src/mastra/networks/financialIntelligenceNetwork.ts
src/mastra/networks/learningNetwork.ts
src/mastra/networks/marketingAutomationNetwork.ts
src/mastra/networks/reportGenerationNetwork.ts
src/mastra/networks/researchPipelineNetwork.ts
src/mastra/networks/securityNetwork.ts
src/mastra/agents/customerSupportAgent.ts
src/mastra/agents/projectManagementAgent.ts
src/mastra/agents/seoAgent.ts
src/mastra/agents/socialMediaAgent.ts
src/mastra/agents/translationAgent.ts
src/mastra/agents/AGENTS.md
src/mastra/networks/AGENTS.md
src/mastra/a2a/AGENTS.md
Refine specific agents’ behavior and cleanup context usage, including quality checker and A2A coordinators.
  • Simplify QualityChecker in codingTeamNetwork by making evaluateQuality synchronous and removing unnecessary Promise handling.
  • Remove unused requestContext/userId from A2A coordinator instruction functions where not needed, and normalize tools: {} for tool-less agents.
  • Standardize use of USER_ID_CONTEXT_KEY and other shared constants when reading userId and related fields in data/knowledge/calendar/etc. agents.
src/mastra/networks/codingTeamNetwork.ts
src/mastra/a2a/codingA2ACoordinator.ts
src/mastra/a2a/a2aCoordinatorAgent.ts
src/mastra/agents/dataExportAgent.ts
src/mastra/agents/dataIngestionAgent.ts
src/mastra/agents/contentStrategistAgent.ts
src/mastra/agents/documentProcessingAgent.ts
src/mastra/agents/knowledgeIndexingAgent.ts
src/mastra/agents/calendarAgent.ts
src/mastra/agents/csv_to_excalidraw.ts
src/mastra/agents/acpAgent.ts
src/mastra/agents/dane.ts
Introduce a validated chat transport request schema and align the chat provider to it.
  • Add lib/types/chat-request.ts with a Zod-based chatTransportRequestSchema and ChatTransportRequest type to standardize chat payloads (messages, trigger, metadata, context, memory, agentId, input).
  • Update ChatProvider to treat outgoingMessages parts as raw arrays (removing cast to UIMessage['parts']) to better align with the generic chat request typing.
lib/types/chat-request.ts
app/chat/providers/chat-context.tsx
Update in-repo documentation and memory-bank notes to reflect the new context and nested-agent design.
  • Extend AGENTS.md, networks/AGENTS.md, and a2a/AGENTS.md with new guidance on nested agent registration, request-context generics, and tool typing best practices.
  • Add memory-bank activeContext.md and progress.md entries documenting the March 17 changes, rationale, and validation status.
src/mastra/agents/AGENTS.md
src/mastra/networks/AGENTS.md
src/mastra/a2a/AGENTS.md
memory-bank/activeContext.md
memory-bank/progress.md

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@github-actions

Copy link
Copy Markdown

🤖 Hi @ssdeanx, I've received your request, and I'm working on it now! You can track my progress in the logs for more details.

@coderabbitai

coderabbitai Bot commented Mar 17, 2026 •

Copy link
Copy Markdown

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: a23e639b-dbe1-4bee-a3d6-ebca71be790b

📥 Commits

Reviewing files that changed from the base of the PR and between 31f3e4f and b862e22.

📒 Files selected for processing (60)
  • app/chat/providers/chat-context.tsx
  • lib/types/chat-request.ts
  • memory-bank/activeContext.md
  • memory-bank/progress.md
  • src/mastra/a2a/AGENTS.md
  • src/mastra/a2a/a2aCoordinatorAgent.ts
  • src/mastra/a2a/codingA2ACoordinator.ts
  • src/mastra/agents/AGENTS.md
  • src/mastra/agents/academicResearchAgent.ts
  • src/mastra/agents/acpAgent.ts
  • src/mastra/agents/businessLegalAgents.ts
  • src/mastra/agents/calendarAgent.ts
  • src/mastra/agents/codingAgents.ts
  • src/mastra/agents/contentStrategistAgent.ts
  • src/mastra/agents/copywriterAgent.ts
  • src/mastra/agents/csv_to_excalidraw.ts
  • src/mastra/agents/customerSupportAgent.ts
  • src/mastra/agents/dane.ts
  • src/mastra/agents/dataExportAgent.ts
  • src/mastra/agents/dataIngestionAgent.ts
  • src/mastra/agents/dataProcessingAgent.ts
  • src/mastra/agents/dataTransformationAgent.ts
  • src/mastra/agents/documentProcessingAgent.ts
  • src/mastra/agents/editorAgent.ts
  • src/mastra/agents/evaluationAgent.ts
  • src/mastra/agents/excalidraw_validator.ts
  • src/mastra/agents/financialAnalysisAgent.ts
  • src/mastra/agents/graphingAgents.ts
  • src/mastra/agents/image.ts
  • src/mastra/agents/image_to_csv.ts
  • src/mastra/agents/knowledgeIndexingAgent.ts
  • src/mastra/agents/learningExtractionAgent.ts
  • src/mastra/agents/nestedAgents.ts
  • src/mastra/agents/package-publisher.ts
  • src/mastra/agents/projectManagementAgent.ts
  • src/mastra/agents/recharts.ts
  • src/mastra/agents/reportAgent.ts
  • src/mastra/agents/request-context.ts
  • src/mastra/agents/researchAgent.ts
  • src/mastra/agents/researchPaperAgent.ts
  • src/mastra/agents/scriptWriterAgent.ts
  • src/mastra/agents/seoAgent.ts
  • src/mastra/agents/socialMediaAgent.ts
  • src/mastra/agents/stockAnalysisAgent.ts
  • src/mastra/agents/translationAgent.ts
  • src/mastra/agents/weather-agent.ts
  • src/mastra/agents/webResearchAgent.ts
  • src/mastra/networks/AGENTS.md
  • src/mastra/networks/businessIntelligenceNetwork.ts
  • src/mastra/networks/codingTeamNetwork.ts
  • src/mastra/networks/contentCreationNetwork.ts
  • src/mastra/networks/dataPipelineNetwork.ts
  • src/mastra/networks/devopsNetwork.ts
  • src/mastra/networks/financialIntelligenceNetwork.ts
  • src/mastra/networks/index.ts
  • src/mastra/networks/learningNetwork.ts
  • src/mastra/networks/marketingAutomationNetwork.ts
  • src/mastra/networks/reportGenerationNetwork.ts
  • src/mastra/networks/researchPipelineNetwork.ts
  • src/mastra/networks/securityNetwork.ts

Summary by CodeRabbit

  • New Features

    • Introduced centralized request-context module with standardized context handling and utilities for agent configuration.
  • Refactor

    • Simplified nested agent configuration across agents and networks by removing wrapper abstraction.
    • Standardized agent runtime context to use consistent AgentRequestContext pattern.
    • Consolidated agent tool definitions into organized groupings for improved maintainability.
    • Updated context extraction to use helper functions instead of direct property access.

Walkthrough

This PR refactors the MAStra agent system by introducing centralized request-context utilities, replacing agent runtime context interfaces with generic type aliases, removing the asNestedAgents wrapper function, and updating 50+ agent and network files to consolidate context handling and tool organization patterns.

Changes

Cohort / File(s) Summary
Chat Context & Schema
app/chat/providers/chat-context.tsx, lib/types/chat-request.ts
Removed TypeScript type cast in outgoing message flatMap; added new Zod schema for ChatTransportRequest with optional fields for id, trigger, messageId, requestMetadata, requestContext, memory, and data.
Request Context Foundation
src/mastra/agents/request-context.ts
New 231-line module introducing centralized context utilities: exports user tier/language/language constants; defines BaseAgentRequestContext, AgentRequestContext<TExtra> generic type; provides helpers like getUserTierFromContext, getLanguageFromContext, resolveTieredModelFromContext; and Zod validation schema.
Nested Agents Removal
src/mastra/agents/nestedAgents.ts
Deleted entire file containing asNestedAgents wrapper function and NestedAgentsInput type alias, consolidating agent registration without adapter layer.
Agent Context Type Standardization
src/mastra/agents/academicResearchAgent.ts, src/mastra/agents/acpAgent.ts, src/mastra/agents/businessLegalAgents.ts, src/mastra/agents/calendarAgent.ts, src/mastra/agents/csv_to_excalidraw.ts, src/mastra/agents/dane.ts, src/mastra/agents/excalidraw_validator.ts, src/mastra/agents/financialAnalysisAgent.ts, src/mastra/agents/graphingAgents.ts, src/mastra/agents/image.ts, src/mastra/agents/image_to_csv.ts, src/mastra/agents/weather-agent.ts, src/mastra/agents/webResearchAgent.ts
Replaced explicit runtime context interfaces with generic type aliases extending AgentRequestContext; removed explicit user-tier, language, and userId fields from public context types.
Agent Context with Custom Fields
src/mastra/agents/contentStrategistAgent.ts, src/mastra/agents/copywriterAgent.ts, src/mastra/agents/dataExportAgent.ts, src/mastra/agents/dataIngestionAgent.ts, src/mastra/agents/dataProcessingAgent.ts, src/mastra/agents/dataTransformationAgent.ts, src/mastra/agents/documentProcessingAgent.ts, src/mastra/agents/knowledgeIndexingAgent.ts, src/mastra/agents/learningExtractionAgent.ts, src/mastra/agents/researchAgent.ts
Replaced context interfaces with AgentRequestContext<{ ... }> type aliases carrying custom fields (e.g., projectRoot, outputDirectory); introduced internal context key constants and consolidation of tool references into centralized objects.
Agent Instructions & Model Refactor
src/mastra/agents/codingAgents.ts, src/mastra/agents/editorAgent.ts, src/mastra/agents/evaluationAgent.ts, src/mastra/agents/package-publisher.ts, src/mastra/agents/reportAgent.ts, src/mastra/agents/researchPaperAgent.ts, src/mastra/agents/scriptWriterAgent.ts, src/mastra/agents/stockAnalysisAgent.ts, src/mastra/agents/recharts.ts
Updated instruction handlers to use context helpers (getUserTierFromContext, getLanguageFromContext); consolidated tool definitions into agent-specific tool objects; simplified function signatures to remove explicit RequestContext typing.
Nested Agent Removal (Agent Files)
src/mastra/agents/customerSupportAgent.ts, src/mastra/agents/projectManagementAgent.ts, src/mastra/agents/seoAgent.ts, src/mastra/agents/socialMediaAgent.ts, src/mastra/agents/translationAgent.ts
Replaced asNestedAgents({ ... }) with plain object literal for agents property; removed corresponding imports; added explicit as Record<string, Agent> type casts where needed.
Network Agent Wiring
src/mastra/networks/businessIntelligenceNetwork.ts, src/mastra/networks/codingTeamNetwork.ts, src/mastra/networks/contentCreationNetwork.ts, src/mastra/networks/dataPipelineNetwork.ts, src/mastra/networks/devopsNetwork.ts, src/mastra/networks/financialIntelligenceNetwork.ts, src/mastra/networks/index.ts, src/mastra/networks/learningNetwork.ts, src/mastra/networks/marketingAutomationNetwork.ts, src/mastra/networks/reportGenerationNetwork.ts, src/mastra/networks/researchPipelineNetwork.ts, src/mastra/networks/securityNetwork.ts
Removed asNestedAgents imports and replaced wrapper calls with plain object literals for agents configuration across all network files; synchronous evaluation added to codingTeamNetwork.
Documentation & Guidance
src/mastra/a2a/AGENTS.md, src/mastra/agents/AGENTS.md, src/mastra/a2a/a2aCoordinatorAgent.ts, src/mastra/a2a/codingA2ACoordinator.ts, src/mastra/networks/AGENTS.md, memory-bank/activeContext.md, memory-bank/progress.md
Updated best-practice guidance to favor source-level child-agent generics (Agent<..., unknown>) and runtime-context parsing inside agent implementations; added 2.0.2 changelog entries; removed requestContext parameter from coordinator instructions functions; updated progress notes on refactoring validations.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • Develop #52: Overlaps on chat context implementation (app/chat/providers/chat-context.tsx) with modifications to sendMessage typing.
  • Develop #93: Shares the major MAStra context/type refactoring initiative, including widespread agent context updates and new request-context module.
  • feat: update agents to include observability tracing policy #91: Both PRs modify agent module initializations across src/mastra/agents, changing how agents are configured and exported.

Poem

🐰 Contexts now flow through golden keys,
No nested wraps, just types so free,
Helpers guide the tier and tongue,
Agent songs from helpers sung!
Networks dance with simpler grace,
Request-context finds its place. 🌙

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch develop
📝 Coding Plan
  • Generate coding plan for human review comments

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@gemini-code-assist

Copy link
Copy Markdown
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request introduces a significant refactoring of how request context is managed and utilized across the agent ecosystem. By centralizing context definitions and providing helper functions, it streamlines development, enhances type safety, and removes boilerplate code from individual agent implementations. The changes also improve the clarity and maintainability of agent and network configurations, alongside adding a new Zod schema for chat transport requests.

Highlights

  • Centralized Request Context Management: A new request-context.ts file was introduced to centralize and standardize request context management for all agents, including user tier and language handling.
  • Standardized Context Retrieval: Utility functions getUserTierFromContext and getLanguageFromContext were implemented to simplify and standardize context retrieval across agents.
  • Agent Updates for New Context Handling: All existing agents (reportAgent, researchAgent, researchPaperAgent, scriptWriterAgent, seoAgent, socialMediaAgent, stockAnalysisAgent, translationAgent, weatherAgent, webResearchAgent) were updated to utilize the new centralized context handling methods, eliminating redundant code.
  • Improved Type Safety for Nested Agents: The asNestedAgents utility was removed, and network definitions were updated to use direct agent assignments, improving type safety and clarity for nested agent configurations.
  • New Chat Request Schema: A chat-request.ts file was added to define a new schema for chat transport requests, leveraging Zod for robust validation.
  • Documentation Updates: The AGENTS.md documentation was updated to reflect the changes in agent wiring and the new context handling paradigm.
Changelog
  • memory-bank/activeContext.md
    • Updated active context for codingAgents.ts to remove explicit generic constructors and restore local tool objects.
    • Completed nested-agent cleanup for networks/a2a, removing ToolsInput and narrowing RequestContext annotations.
    • Resolved seoAgent.ts nested child-agent type errors by centralizing request-context keys and pinning public child-agent generics to unknown.
  • memory-bank/progress.md
    • Normalized codingAgents.ts by restoring local tool objects and removing explicit new Agent<...> tool generics.
    • Completed nested-agent typing cleanup across src/mastra/networks and src/mastra/a2a, removing ToolsInput and reworking child agents for direct compilation.
    • Fixed seoAgent.ts nested child-agent assignment failures by using shared request-context keys and exposing unknown as public Agent request-context generic.
  • src/mastra/a2a/AGENTS.md
    • Updated guidance to use source-level public unknown request-context generics for child agents instead of adapter-based registration (v2.0.2).
  • src/mastra/agents/AGENTS.md
    • Normalized codingAgents.ts by restoring concrete per-agent tool maps and removing the last explicit new Agent<...> tool generic (v2.2.4).
    • Removed unnecessary ToolsInput usage from touched agents and completed the source-level unknown request-context fix for all remaining network/A2A child-agent registrations (v2.2.3).
    • Fixed direct nested-agent registration typing by centralizing request-context keys and pinning touched child agents to public unknown request-context generics instead of using an adapter in parent registrations (v2.2.2).
  • src/mastra/networks/AGENTS.md
    • Replaced adapter guidance with the current source-level child-agent typing standard, emphasizing unknown public request context and internal runtime parsing (v2.0.2).
Activity
  • No human activity has been recorded on this pull request yet.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution. ↩

@github-actions

Copy link
Copy Markdown

🤖 I'm sorry @ssdeanx, but I was unable to process your request. Please see the logs for more details.

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Hey - I've found 1 issue, and left some high level feedback:

  • In several agents (e.g., customerSupportAgent, projectManagementAgent, socialMediaAgent, translationAgent) you're still casting the agents map to Record<string, Agent>; now that child agent generics have been normalized, consider removing these casts entirely and letting the types infer cleanly.
  • In editorAgent you manually read USER_TIER_CONTEXT_KEY inside the model function instead of using getUserTierFromContext; aligning this with the new helper would reduce duplication and keep fallback/validation behavior consistent with the rest of the agents.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- In several agents (e.g., customerSupportAgent, projectManagementAgent, socialMediaAgent, translationAgent) you're still casting the `agents` map to `Record<string, Agent>`; now that child agent generics have been normalized, consider removing these casts entirely and letting the types infer cleanly.
- In editorAgent you manually read `USER_TIER_CONTEXT_KEY` inside the `model` function instead of using `getUserTierFromContext`; aligning this with the new helper would reduce duplication and keep fallback/validation behavior consistent with the rest of the agents.

## Individual Comments

### Comment 1
<location path="memory-bank/progress.md" line_range="14" />
<code_context>
+
+- Completed the remaining nested-agent typing cleanup the user requested across `src/mastra/networks` and `src/mastra/a2a`.
+- Removed the bad `ToolsInput` additions from the touched agent implementations.
+- Reworked the remaining child agents so parent registration compiles by source design rather than parent-side casting/adaptering.
+- Fixed adjacent diagnostics encountered during the pass:
+  - invalid `unknown` template interpolation in `knowledgeIndexingAgent.ts`
</code_context>
<issue_to_address>
**issue (typo):** The term "adaptering" here is unconventional; "adapting" would be clearer.

Consider updating the phrase to "casting/adapting" or "casting/adapter-based registration" to align with standard terminology.

```suggestion
- Reworked the remaining child agents so parent registration compiles by source design rather than parent-side casting/adapting.
```
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment thread memory-bank/progress.md

- Completed the remaining nested-agent typing cleanup the user requested across `src/mastra/networks` and `src/mastra/a2a`.
- Removed the bad `ToolsInput` additions from the touched agent implementations.
- Reworked the remaining child agents so parent registration compiles by source design rather than parent-side casting/adaptering.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

issue (typo): The term "adaptering" here is unconventional; "adapting" would be clearer.

Consider updating the phrase to "casting/adapting" or "casting/adapter-based registration" to align with standard terminology.

Suggested change
- Reworked the remaining child agents so parent registration compiles by source design rather than parent-side casting/adaptering.
- Reworked the remaining child agents so parent registration compiles by source design rather than parent-side casting/adapting.

@ssdeanx
ssdeanx merged commit dee9344 into main Mar 17, 2026
32 of 37 checks passed

Copilot AI left a comment

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.

Pull request overview

This PR standardizes Mastra agent request-context handling by introducing a shared request-context.ts module, updating agents to use the shared helpers/types, and removing the previous nested-agent adapter approach in favor of direct agent registration.

Changes:

  • Centralized request-context keys/types and added helpers for tier/language/model override resolution.
  • Updated many agents to use the new context helpers and consolidated tool maps into named objects.
  • Removed nestedAgents adapter usage across networks/A2A coordinators and added a Zod schema for chat transport requests.

Reviewed changes

Copilot reviewed 60 out of 60 changed files in this pull request and generated 7 comments.

Show a summary per file
File Description
src/mastra/networks/securityNetwork.ts Removes asNestedAgents usage; registers child agents directly.
src/mastra/networks/researchPipelineNetwork.ts Removes asNestedAgents usage; registers child agents directly.
src/mastra/networks/reportGenerationNetwork.ts Removes asNestedAgents usage; registers child agents directly.
src/mastra/networks/marketingAutomationNetwork.ts Removes asNestedAgents usage; registers child agents directly.
src/mastra/networks/learningNetwork.ts Removes asNestedAgents usage; registers child agents directly.
src/mastra/networks/index.ts Removes asNestedAgents usage; registers child agents directly.
src/mastra/networks/financialIntelligenceNetwork.ts Removes asNestedAgents usage; registers child agents directly.
src/mastra/networks/devopsNetwork.ts Removes asNestedAgents usage; registers child agents directly.
src/mastra/networks/dataPipelineNetwork.ts Removes asNestedAgents usage; registers child agents directly.
src/mastra/networks/contentCreationNetwork.ts Removes asNestedAgents usage; registers child agents directly.
src/mastra/networks/codingTeamNetwork.ts Fixes quality-check processor to be synchronous; removes asNestedAgents usage.
src/mastra/networks/businessIntelligenceNetwork.ts Removes asNestedAgents usage; registers child agents directly.
src/mastra/networks/AGENTS.md Updates guidance away from adapters/casts toward source-level agent typing.
src/mastra/agents/webResearchAgent.ts Switches runtime context typing to shared AgentRequestContext.
src/mastra/agents/weather-agent.ts Switches runtime context typing to shared AgentRequestContext.
src/mastra/agents/translationAgent.ts Removes asNestedAgents import; uses direct child agents (still has a cast).
src/mastra/agents/stockAnalysisAgent.ts Uses shared context helpers; consolidates tool map.
src/mastra/agents/socialMediaAgent.ts Removes asNestedAgents import; uses direct child agents (still has a cast).
src/mastra/agents/seoAgent.ts Removes asNestedAgents import; uses direct child agents.
src/mastra/agents/scriptWriterAgent.ts Uses shared context helpers; consolidates tool map.
src/mastra/agents/researchPaperAgent.ts Uses shared context helpers; consolidates tool map.
src/mastra/agents/researchAgent.ts Uses shared context helpers; adds typed parsing for researchPhase; consolidates tool map.
src/mastra/agents/request-context.ts New shared request-context keys/types/helpers (tier/language/model override, context creation).
src/mastra/agents/reportAgent.ts Uses shared tier/language helpers in instructions; normalizes tools: {} placement.
src/mastra/agents/recharts.ts Uses shared context helpers; adds typed parsing helpers for chart runtime keys; consolidates tool maps.
src/mastra/agents/projectManagementAgent.ts Removes asNestedAgents import; uses direct child agents (still has a cast).
src/mastra/agents/package-publisher.ts Uses shared context helpers; consolidates tool map.
src/mastra/agents/nestedAgents.ts Deletes the nested-agent adapter helper.
src/mastra/agents/learningExtractionAgent.ts Uses shared context keys/helpers; adds runtime narrowing for userId/researchPhase; sets tools: {}.
src/mastra/agents/knowledgeIndexingAgent.ts Switches to shared request-context typing; adds constants and runtime narrowing; consolidates tool map.
src/mastra/agents/image_to_csv.ts Switches runtime context typing to shared AgentRequestContext.
src/mastra/agents/image.ts Switches runtime context typing to shared AgentRequestContext.
src/mastra/agents/graphingAgents.ts Switches runtime context typing to shared AgentRequestContext; aligns tier key usage.
src/mastra/agents/financialAnalysisAgent.ts Switches runtime context typing to shared AgentRequestContext.
src/mastra/agents/excalidraw_validator.ts Switches runtime context typing to shared AgentRequestContext.
src/mastra/agents/evaluationAgent.ts Uses shared tier helper; sets tools: {}.
src/mastra/agents/editorAgent.ts Uses shared tier/language helpers for instructions; updates runtime context type; sets tools: {}.
src/mastra/agents/documentProcessingAgent.ts Switches runtime context typing to shared AgentRequestContext; adds constants and runtime narrowing; consolidates tool map.
src/mastra/agents/dataTransformationAgent.ts Switches runtime context typing to shared AgentRequestContext; adds constants and runtime narrowing; consolidates tool map.
src/mastra/agents/dataProcessingAgent.ts Switches runtime context typing to shared AgentRequestContext.
src/mastra/agents/dataIngestionAgent.ts Switches runtime context typing to shared AgentRequestContext; adds constants and runtime narrowing; consolidates tool map.
src/mastra/agents/dataExportAgent.ts Switches runtime context typing to shared AgentRequestContext; adds constants and runtime narrowing; consolidates tool map.
src/mastra/agents/dane.ts Switches runtime context typing to shared AgentRequestContext.
src/mastra/agents/customerSupportAgent.ts Removes asNestedAgents import; uses direct child agents (still has a cast).
src/mastra/agents/csv_to_excalidraw.ts Switches runtime context typing to shared AgentRequestContext.
src/mastra/agents/copywriterAgent.ts Switches runtime context typing to shared AgentRequestContext; consolidates tool map; uses shared context keys.
src/mastra/agents/contentStrategistAgent.ts Uses shared tier helper + shared keys; adds typed parsing helpers/constants; consolidates tool map.
src/mastra/agents/codingAgents.ts Uses shared context helpers; consolidates per-agent tool maps; uses tiered model resolver.
src/mastra/agents/calendarAgent.ts Switches runtime context typing to shared AgentRequestContext.
src/mastra/agents/businessLegalAgents.ts Switches runtime context typing to shared AgentRequestContext.
src/mastra/agents/acpAgent.ts Switches runtime context typing to shared AgentRequestContext.
src/mastra/agents/academicResearchAgent.ts Switches runtime context typing to shared AgentRequestContext.
src/mastra/agents/AGENTS.md Updates repo guidance toward source-level typing + inferred tool maps; changelog entry.
src/mastra/a2a/codingA2ACoordinator.ts Removes asNestedAgents usage; registers child agents directly; removes unused requestContext usage.
src/mastra/a2a/a2aCoordinatorAgent.ts Removes asNestedAgents usage; registers child agents directly; removes unused requestContext usage.
src/mastra/a2a/AGENTS.md Updates A2A guidance away from adapters/casts toward source-level agent typing.
memory-bank/progress.md Documents the typing cleanup/normalization work performed.
memory-bank/activeContext.md Documents the typing cleanup/normalization work performed.
lib/types/chat-request.ts Adds Zod schema/type for chat transport request payloads.
app/chat/providers/chat-context.tsx Removes unnecessary type assertion when flattening message parts.
Comments suppressed due to low confidence (1)

src/mastra/agents/copywriterAgent.ts:56

  • requestContext.get(USER_ID_CONTEXT_KEY) returns unknown, but it’s interpolated into the system prompt directly. If a non-string value is ever present, this will produce confusing output (e.g., [object Object]). Consider narrowing to string (as several other agents do) and falling back to 'anonymous' when the value isn’t a valid user id string.
  instructions: ({ requestContext }) => {
    const userId = requestContext.get(USER_ID_CONTEXT_KEY)
    return {
      role: 'system',
      content: `
# Copywriter Agent
User: ${userId ?? 'anonymous'}


You can also share your feedback on Copilot code review. Take the survey.

Comment on lines +96 to +101
agents: {
copywriterAgent,
contentStrategistAgent,
researchAgent,
calendarAgent,
}),
} as Record<string, Agent>,
Comment on lines +143 to +147
agents: {
calendarAgent,
reportAgent,
evaluationAgent,
}),
} as Record<string, Agent>,
evaluationAgent,
reportAgent,
}),
} as Record<string, Agent>,
Comment on lines +69 to +72
const userTier =
typeof requestContext.get(USER_TIER_CONTEXT_KEY) === 'string'
? requestContext.get(USER_TIER_CONTEXT_KEY)
: 'free'
import type { RequestContext } from '@mastra/core/request-context'
import {
USER_ID_CONTEXT_KEY,
USER_TIER_CONTEXT_KEY,
Comment on lines +189 to +205
export function getModelOverrideFromContext(
requestContext: RequestContextReader | undefined
): string | undefined {
const providerId = requestContext?.get(PROVIDER_ID_CONTEXT_KEY)
const modelId = requestContext?.get(MODEL_ID_CONTEXT_KEY)

if (typeof modelId !== 'string' || modelId.trim().length === 0) {
return undefined
}

if (modelId.includes('/')) {
return modelId.trim()
}

if (typeof providerId === 'string' && providerId.trim().length > 0) {
return `${providerId}/${modelId}`
}
Comment on lines +120 to +123
agents: {
evaluationAgent,
researchAgent,
}),
} as Record<string, Agent>,

@gemini-code-assist gemini-code-assist Bot left a comment

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.

Code Review

This pull request introduces a significant and valuable refactoring to centralize agent request context handling. The introduction of request-context.ts with shared types and helper functions is a great step towards improving type safety and maintainability across the agent ecosystem. The removal of the asNestedAgents helper and the move towards direct agent assignment is also a positive change. My review focuses on ensuring these new patterns are applied consistently and identifying a few areas where the new abstractions could be further leveraged. I've also noted some places where type safety could be further improved.

Comment thread lib/types/chat-request.ts
export const chatTransportRequestSchema = z
.object({
id: z.string().optional(),
messages: z.array(z.unknown()).default([]),

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.

medium

The schema for messages is currently using z.array(z.unknown()), which provides no type safety for the message objects. To improve validation and align with the goal of better type safety, consider defining a more specific schema for the message objects. Even a minimal schema would be an improvement.

For example, you could define a schema that validates the basic structure of a message:

const messagePartSchema = z.object({
  type: z.string(),
}).passthrough();

const messageSchema = z.object({
  id: z.string(),
  role: z.enum(['user', 'assistant', 'system', 'tool']),
  parts: z.array(messagePartSchema),
}).passthrough();

// ... in chatTransportRequestSchema
messages: z.array(messageSchema).default([]),

evaluationAgent,
reportAgent,
}),
} as Record<string, Agent>,

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.

medium

The type assertion as Record<string, Agent> is used here, which goes against one of the main goals of this pull request as stated in the description: "do not rely on any shared adapter or as Record<string, Agent> cast".

The preferred solution, as mentioned in the PR description, is to fix the child agents at the source by ensuring their public request-context generic is unknown. This would make them directly assignable to the agents property without needing a cast.

Comment on lines +69 to +72
const userTier =
typeof requestContext.get(USER_TIER_CONTEXT_KEY) === 'string'
? requestContext.get(USER_TIER_CONTEXT_KEY)
: 'free'

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.

medium

For consistency and to fully leverage the new centralized context handling, it's better to use the getUserTierFromContext helper function here, just as it's used in the instructions function within the same agent. This avoids duplicating the logic for retrieving and providing a fallback for the user tier.

Suggested change
const userTier =
typeof requestContext.get(USER_TIER_CONTEXT_KEY) === 'string'
? requestContext.get(USER_TIER_CONTEXT_KEY)
: 'free'
const userTier = getUserTierFromContext(requestContext)

}) => {
const lang = requestContext.get('language') ?? 'en'
const tier = requestContext.get('userTier') ?? 'free'
const tier = requestContext.get('user-tier') ?? 'free'

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.

medium

For consistency with the refactoring patterns introduced in this PR, consider using the getUserTierFromContext helper function from src/mastra/agents/request-context.ts to retrieve the user tier. This will centralize the logic and make the code more maintainable.

You'll need to import it first:
import { getUserTierFromContext } from './request-context'

Suggested change
const tier = requestContext.get('user-tier') ?? 'free'
const tier = getUserTierFromContext(requestContext) ?? 'free'

reportAgent,
evaluationAgent,
}),
} as Record<string, Agent>,

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.

medium

The type assertion as Record<string, Agent> is used here, which goes against one of the main goals of this pull request as stated in the description: "do not rely on any shared adapter or as Record<string, Agent> cast".

The preferred solution, as mentioned in the PR description, is to fix the child agents at the source by ensuring their public request-context generic is unknown. This would make them directly assignable to the agents property without needing a cast.

}

function isUserTier(value: unknown): value is UserTier {
return value === 'free' || value === 'pro' || value === 'enterprise'

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.

medium

To improve maintainability, consider using the USER_TIERS constant for this check. This ensures that if the USER_TIERS array is ever updated, this function will not need to be changed manually.

  return (USER_TIERS as readonly unknown[]).includes(value)

}

function isSupportedLanguage(value: unknown): value is SupportedLanguage {
return value === 'en' || value === 'es' || value === 'ja' || value === 'fr'

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.

medium

To improve maintainability, consider using the SUPPORTED_LANGUAGES constant for this check. This ensures that if the SUPPORTED_LANGUAGES array is ever updated, this function will not need to be changed manually.

  return (SUPPORTED_LANGUAGES as readonly unknown[]).includes(value)

researchAgent,
calendarAgent,
}),
} as Record<string, Agent>,

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.

medium

The type assertion as Record<string, Agent> is used here, which goes against one of the main goals of this pull request as stated in the description: "do not rely on any shared adapter or as Record<string, Agent> cast".

The preferred solution, as mentioned in the PR description, is to fix the child agents at the source by ensuring their public request-context generic is unknown. This would make them directly assignable to the agents property without needing a cast.

evaluationAgent,
researchAgent,
}),
} as Record<string, Agent>,

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.

medium

The type assertion as Record<string, Agent> is used here, which goes against one of the main goals of this pull request as stated in the description: "do not rely on any shared adapter or as Record<string, Agent> cast".

The preferred solution, as mentioned in the PR description, is to fix the child agents at the source by ensuring their public request-context generic is unknown. This would make them directly assignable to the agents property without needing a cast.

This branch had an error being deployed

1 failed deployment
Preview — b862e228 Deployed Mar 17, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants