Skip to content

Commit b862e22

Browse files
committed
feat: Refactor agent request context handling and improve agent definitions
- 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.
1 parent 7b3972e commit b862e22

60 files changed

Lines changed: 1030 additions & 691 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

app/chat/providers/chat-context.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -163,7 +163,7 @@ export function ChatProvider({
163163
id: selectedAgent,
164164
messages: outgoingMessages,
165165
parts: outgoingMessages.flatMap(
166-
(m) => (m.parts ?? []) as UIMessage['parts']
166+
(m) => (m.parts ?? [])
167167
),
168168
trigger,
169169
messageId,

lib/types/chat-request.ts

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import { z } from 'zod'
2+
3+
export const chatTransportRequestSchema = z
4+
.object({
5+
id: z.string().optional(),
6+
messages: z.array(z.unknown()).default([]),
7+
trigger: z.string().optional(),
8+
messageId: z.string().optional(),
9+
requestMetadata: z.unknown().optional(),
10+
requestContext: z.record(z.string(), z.unknown()).optional(),
11+
memory: z
12+
.object({
13+
thread: z.string().optional(),
14+
resource: z.string().optional(),
15+
})
16+
.partial()
17+
.optional(),
18+
data: z
19+
.object({
20+
agentId: z.string().min(1).optional(),
21+
input: z.string().optional(),
22+
})
23+
.loose()
24+
.optional(),
25+
})
26+
.loose()
27+
28+
export type ChatTransportRequest = z.infer<typeof chatTransportRequestSchema>

memory-bank/activeContext.md

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,61 @@
1+
## Active Context Update (2026-03-17 - codingAgents explicit tool-generic cleanup)
2+
3+
- User flagged that `codingAgents.ts` still contained an explicit `new Agent<...>` constructor and that the per-agent tool objects had been disturbed.
4+
- Fixed `src/mastra/agents/codingAgents.ts` by:
5+
- removing the remaining explicit generic constructor from `codeReviewerAgent`
6+
- restoring the local per-agent tool objects (`codeArchitectTools`, `codeReviewerTools`, `testEngineerTools`, `refactoringTools`) with concrete tool names
7+
- normalizing `codeArchitectAgent` model selection back to shared request-context helper usage rather than raw string access
8+
- removing the stray unused `scrapingSchedulerTool` import
9+
- Validation:
10+
- targeted `get_errors` on `src/mastra/agents/codingAgents.ts` returned **No errors found**
11+
- folder-level `get_errors` on `src/mastra/agents` returned **No errors found**
12+
13+
## Active Context Update (2026-03-17 - networks/a2a nested-agent cleanup completed without ToolsInput adaptering)
14+
15+
- Completed the follow-up fix pass for the remaining `src/mastra/networks` and `src/mastra/a2a` nested child-agent assignment failures.
16+
- User direction was explicit: do **not** rely on any shared adapter or `as Record<string, Agent>` cast, and do **not** introduce gratuitous `ToolsInput` typing into agents.
17+
- Source-level fix applied across the remaining child agents by:
18+
- removing narrowed `RequestContext<SpecificContext>` instruction callback annotations from public agent surfaces
19+
- pinning affected child agents to public `new Agent<..., unknown>(...)` request-context generics
20+
- keeping specialized runtime-context parsing local inside instruction bodies via explicit narrowing/constants
21+
- removing the extra `ToolsInput` usage introduced in the touched agents; tool maps now use direct inferred object types (`typeof toolMap`) or `Record<string, never>` for tool-less agents
22+
- Additional cleanup included:
23+
- `codingAgents.ts` refactoring-tool typing cleanup
24+
- `codingA2ACoordinator.ts` / `a2aCoordinatorAgent.ts` unused-parameter cleanup
25+
- `codingTeamNetwork.ts` synchronous quality gate fix
26+
- Source agents updated in this pass:
27+
- `dataExportAgent.ts`
28+
- `dataIngestionAgent.ts`
29+
- `dataTransformationAgent.ts`
30+
- `reportAgent.ts`
31+
- `stockAnalysisAgent.ts`
32+
- `recharts.ts`
33+
- `researchPaperAgent.ts`
34+
- `documentProcessingAgent.ts`
35+
- `learningExtractionAgent.ts`
36+
- `scriptWriterAgent.ts`
37+
- `package-publisher.ts`
38+
- plus cleanup in previously touched `editorAgent.ts`, `copywriterAgent.ts`, `knowledgeIndexingAgent.ts`, `researchAgent.ts`, `contentStrategistAgent.ts`, `evaluationAgent.ts`, and `codingAgents.ts`
39+
- Validation result:
40+
- targeted `get_errors` returned clean for all edited agent files
41+
- targeted `get_errors` for `src/mastra/a2a` and `src/mastra/networks` no longer surfaced the earlier nested-agent assignment failures
42+
43+
## Active Context Update (2026-03-17 - nested agent typing without adapter)
44+
45+
- Resolved the `seoAgent.ts` nested child-agent type errors without using a shared adapter or local cast.
46+
- Root cause: Mastra inferred narrower child `Agent<..., TRequestContext>` generics from `researchAgent`, `contentStrategistAgent`, and `evaluationAgent`, which made them fail assignment to parent `agents: Record<string, Agent<..., unknown>>` slots.
47+
- Fix applied:
48+
- centralized shared request-context keys in `src/mastra/agents/request-context.ts`
49+
- replaced raw string usage in touched agents with declared constants/helpers
50+
- explicitly pinned the public child-agent generic to `unknown` via `new Agent<..., unknown>(...)`
51+
- kept runtime-safe parsing of specialized context values inside the agent instruction bodies
52+
- Files updated:
53+
- `src/mastra/agents/request-context.ts`
54+
- `src/mastra/agents/researchAgent.ts`
55+
- `src/mastra/agents/contentStrategistAgent.ts`
56+
- `src/mastra/agents/evaluationAgent.ts`
57+
- Validation: targeted `get_errors` is clean for all edited files and `src/mastra/agents/seoAgent.ts`.
58+
159
## Active Context Update (2026-03-16 - use-mastra-query full client-js surface expansion)
260

361
- Expanded `lib/hooks/use-mastra-query.ts` beyond dataset/eval coverage to expose the remaining installed `@mastra/client-js` surfaces needed by the frontend hook factory.

memory-bank/progress.md

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,41 @@
1+
# 2026-03-17 codingAgents normalization
2+
3+
- Restored `codingAgents.ts` after a bad intermediate state:
4+
- local tool objects are back in place by concrete tool name
5+
- no explicit `new Agent<...>` tool generic remains in that file
6+
- targeted validation for `codingAgents.ts` is clean
7+
- Rechecked `src/mastra/agents` after the fix:
8+
-**No errors found**
9+
10+
# 2026-03-17 full nested-agent source fix for networks/a2a
11+
12+
- Completed the remaining nested-agent typing cleanup the user requested across `src/mastra/networks` and `src/mastra/a2a`.
13+
- Removed the bad `ToolsInput` additions from the touched agent implementations.
14+
- Reworked the remaining child agents so parent registration compiles by source design rather than parent-side casting/adaptering.
15+
- Fixed adjacent diagnostics encountered during the pass:
16+
- invalid `unknown` template interpolation in `knowledgeIndexingAgent.ts`
17+
- `codingAgents.ts` unused import + `projectRoot` stringification issue
18+
- unused `requestContext` / `userId` in A2A coordinators
19+
- `codingTeamNetwork.ts` async/no-await quality-gate bug
20+
- Validation:
21+
- ✅ edited agent files clean
22+
-`src/mastra/a2a` clean
23+
-`src/mastra/networks` clean
24+
25+
# 2026-03-17 nested-agent typing fix without adapter
26+
27+
- Fixed the reported `seoAgent.ts` nested child-agent assignment failures for:
28+
- `researchAgent`
29+
- `contentStrategistAgent`
30+
- `evaluationAgent`
31+
- Kept the solution at the source rather than adding a parent-side adapter:
32+
- shared request-context keys now come from `src/mastra/agents/request-context.ts`
33+
- touched child agents parse specialized runtime context internally
34+
- touched child agents now expose `unknown` as their public `Agent` request-context generic so direct parent registration compiles cleanly
35+
- Validation:
36+
- ✅ targeted `get_errors` on `request-context.ts`, `researchAgent.ts`, `contentStrategistAgent.ts`, `evaluationAgent.ts`, and `seoAgent.ts` returned clean
37+
- ⚠️ folder-wide `get_errors` on `src/mastra/agents` still shows unrelated pre-existing diagnostics in `knowledgeIndexingAgent.ts`
38+
139
# 2026-03-16 use-mastra-query full client-js hook expansion
240

341
- Completed the requested `@mastra/client-js` parity pass in `lib/hooks/use-mastra-query.ts` without replacing the file’s existing hook-factory pattern.

src/mastra/a2a/AGENTS.md

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -100,15 +100,16 @@ coordinate_a2a_task({
100100

101101
## Typing Note
102102

103-
- Parent coordinators that register child agents should use `@/src/mastra/agents/nestedAgents` for the `agents` config.
104-
- This keeps the current Mastra nested-agent typing workaround isolated to one boundary while upstream typings remain restrictive.
103+
- Do **not** rely on parent-side adapter helpers or `as Record<string, Agent>` casts for child-agent registration.
104+
- Fix child agents at the source by exposing the public `Agent<..., unknown>` request-context generic and keeping any specialized runtime-context parsing inside the agent implementation.
105105

106106
---
107107

108108
## Change Log
109109

110110
| Version | Date (UTC) | Changes |
111111
| ------- | ---------- | ----------------------------------------------- |
112+
| 2.0.2 | 2026-03-17 | Updated guidance to use source-level public `unknown` request-context generics for child agents instead of adapter-based registration. |
112113
| 2.0.1 | 2026-03-16 | Added note about `nestedAgents` boundary adapter for child-agent registration typing. |
113114
| 2.0.0 | 2025-11-26 | Major update: documented all coordinated agents |
114115
| 1.0.0 | 2025-11-14 | Initial A2A coordinator implementation |

src/mastra/a2a/a2aCoordinatorAgent.ts

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@ import {
1010
refactoringAgent,
1111
testEngineerAgent,
1212
} from '../agents/codingAgents'
13-
import { asNestedAgents } from '@/src/mastra/agents/nestedAgents'
1413
import { contentStrategistAgent } from '../agents/contentStrategistAgent'
1514
import { copywriterAgent } from '../agents/copywriterAgent'
1615
import { editorAgent } from '../agents/editorAgent'
@@ -40,7 +39,7 @@ export const a2aCoordinatorAgent = new Agent({
4039
name: 'a2aCoordinator',
4140
description:
4241
'A2A Coordinator that orchestrates multiple specialized agents in parallel. Routes tasks dynamically, coordinates workflows, and synthesizes results using the A2A protocol.',
43-
instructions: ({ requestContext }) => {
42+
instructions: () => {
4443
// const userId = requestContext.get('userId')
4544
return {
4645
role: 'system',
@@ -108,7 +107,7 @@ Use knowledgeIndexingAgent to provide semantic context for complex queries.
108107
model: googleAI,
109108
memory: pgMemory,
110109
options: {},
111-
agents: asNestedAgents({
110+
agents: {
112111
researchAgent,
113112
knowledgeIndexingAgent,
114113
editorAgent,
@@ -119,7 +118,7 @@ Use knowledgeIndexingAgent to provide semantic context for complex queries.
119118
refactoringAgent,
120119
contentStrategistAgent,
121120
projectManagementAgent,
122-
}),
121+
},
123122
workflows: {
124123
researchSynthesisWorkflow,
125124
repoIngestionWorkflow,

src/mastra/a2a/codingA2ACoordinator.ts

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@ import {
1616
refactoringAgent,
1717
testEngineerAgent,
1818
} from '../agents/codingAgents'
19-
import { asNestedAgents } from '@/src/mastra/agents/nestedAgents'
2019
import {
2120
checkFileExists,
2221
createDirectory,
@@ -59,8 +58,7 @@ export const codingA2ACoordinator = new Agent({
5958
name: 'Coding A2A Coordinator',
6059
description:
6160
'A2A Coordinator that orchestrates multiple coding agents in parallel for complex development tasks like full feature development, comprehensive reviews, and refactoring with tests.',
62-
instructions: ({ requestContext }) => {
63-
const userId = requestContext.get('userId')
61+
instructions: () => {
6462
return {
6563
role: 'system',
6664
content: `You are a Coding A2A (Agent-to-Agent) Coordinator that orchestrates multi-agent coding workflows.
@@ -206,12 +204,12 @@ When a user's request requires prolonged, structured work across multiple subtas
206204
model: googleAIFlashLite,
207205
memory: pgMemory,
208206

209-
agents: asNestedAgents({
207+
agents: {
210208
codeArchitectAgent,
211209
codeReviewerAgent,
212210
testEngineerAgent,
213211
refactoringAgent,
214-
}),
212+
},
215213
workflows: {
216214
researchSynthesisWorkflow,
217215
financialReportWorkflow,

src/mastra/agents/AGENTS.md

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,8 @@ This directory contains 22+ agent definitions that map use-case intents to seque
9090
- **Logging**: Use the provided logger for consistent logging
9191
- **Testing**: Write unit tests for all agent functionality
9292
- **Documentation**: Document your agent's purpose, inputs, and outputs
93-
- **Nested Agent Registration**: When an agent exposes child agents via the `agents` config, use `@/src/mastra/agents/nestedAgents` to adapt Mastra's current nested-agent typing without spreading one-off workarounds across files.
93+
- **Nested Agent Registration**: Prefer fixing child-agent public generics at the source. If a child agent needs specialized runtime context internally, keep that parsing inside its instruction/helpers while pinning the public `Agent<..., unknown>` request-context generic so parent `agents` registration remains directly assignable.
94+
- **Tool Typing**: Avoid adding `ToolsInput` annotations to agent definitions unless they are truly required. Prefer inferred tool maps (`const tools = { ... }`) with `typeof tools`, or `Record<string, never>` for tool-less agents.
9495

9596
## Execution & Testing
9697

@@ -121,6 +122,9 @@ npm test src/mastra/__tests__/agents/your-agent.test.ts
121122
| Version | Date (UTC) | Changes |
122123
| ------- | ---------- | ------------------------------------------------------------------------------------------------------------------------------------ |
123124
| 2.2.0 | 2025-12-15 | Added 5 new specialized agents: socialMediaAgent, seoAgent, translationAgent, customerSupportAgent, projectManagementAgent. |
125+
| 2.2.4 | 2026-03-17 | Normalized `codingAgents.ts` by restoring concrete per-agent tool maps and removing the last explicit `new Agent<...>` tool generic; `src/mastra/agents` now validates clean. |
126+
| 2.2.3 | 2026-03-17 | Removed unnecessary `ToolsInput` usage from touched agents and completed the source-level `unknown` request-context fix for all remaining network/A2A child-agent registrations. |
127+
| 2.2.2 | 2026-03-17 | 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. |
124128
| 2.2.1 | 2026-03-16 | Added `nestedAgents.ts` boundary adapter for Mastra nested sub-agent typing and cleaned folder-level agent errors. |
125129
| 2.1.0 | 2025-11-28 | Added 4 Financial Chart agents: chartTypeAdvisorAgent, chartDataProcessorAgent, chartGeneratorAgent, chartSupervisorAgent. |
126130
| 2.0.0 | 2025-11-26 | Major update: 22 agents documented. Added data pipeline, research paper, document processing, knowledge indexing agents. |

src/mastra/agents/academicResearchAgent.ts

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import type { GoogleGenerativeAIProviderOptions } from '@ai-sdk/google'
22
import { Agent } from '@mastra/core/agent'
33
import type { RequestContext } from '@mastra/core/request-context'
4+
import type { AgentRequestContext } from './request-context'
45

56
import { google } from '../config/google'
67
import { log } from '../config/logger'
@@ -18,14 +19,9 @@ import {
1819
import { extractLearningsTool } from '../tools/extractLearningsTool'
1920
import { InternalSpans } from '@mastra/core/observability'
2021

21-
type UserTier = 'free' | 'pro' | 'enterprise'
22-
23-
export interface AcademicResearchRuntimeContext {
24-
'user-tier': UserTier
25-
language: 'en' | 'es' | 'ja' | 'fr'
26-
userId?: string
22+
export type AcademicResearchRuntimeContext = AgentRequestContext<{
2723
researchType?: 'quick' | 'deep' | 'systematic'
28-
}
24+
}>
2925

3026
log.info('Initializing Academic Research Agent...')
3127

src/mastra/agents/acpAgent.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -38,11 +38,11 @@ import type { RequestContext } from '@mastra/core/request-context'
3838
import { PGVECTOR_PROMPT } from '@mastra/pg'
3939
import { TokenLimiterProcessor } from '@mastra/core/processors'
4040
import { InternalSpans } from '@mastra/core/observability'
41+
import type { AgentRequestContext } from './request-context'
4142

42-
export interface ACPContext {
43-
userId?: string
43+
export type ACPContext = AgentRequestContext<{
4444
userRole?: string
45-
}
45+
}>
4646

4747
export const acpAgent = new Agent({
4848
id: 'acpAgent',

0 commit comments

Comments
 (0)