Skip to content

Commit cefa8f1

Browse files
authored
Merge pull request #5 from ssdeanx/develop
feat: update AGENTS and README metadata, enhance chat API
2 parents d729737 + 27d8e92 commit cefa8f1

5 files changed

Lines changed: 93 additions & 137 deletions

File tree

AGENTS.md

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
1-
<!-- AGENTS-META {"title":"Mastra Root","version":"2.2.0","applies_to":"/","last_updated":"2025-11-27T00:00:00Z","status":"stable"} -->
1+
<!-- AGENTS-META {"title":"Mastra Root","version":"2.3.0","applies_to":"/","last_updated":"2025-12-05T00:00:00Z","status":"stable"} -->
22
# AGENTS
33

44
## Project Overview
55

6-
Mastra is a production-grade multi-agent framework for building agent-driven applications and RAG (retrieval-augmented generation) workflows. It provides **30+ enterprise tools**, **22+ specialized agents**, **10 workflows**, **4 agent networks**, **A2A/MCP orchestration**, and now a **complete UI component library** (49 components) for scalable AI systems. Key capabilities include **financial intelligence**, **RAG pipelines**, **observability**, **secure governance**, and **AI chat interfaces**.
6+
Mastra is a production-grade multi-agent framework for building agent-driven applications and RAG (retrieval-augmented generation) workflows. It provides **34+ enterprise tools**, **38 specialized agents**, **10 workflows**, **4 agent networks**, **A2A/MCP orchestration**, and a **complete UI component library** (64 components: 30 AI Elements + 34 base UI) for scalable AI systems. Key capabilities include **financial intelligence**, **RAG pipelines**, **observability**, **secure governance**, and **AI chat interfaces**.
77

88
This repo is structured to keep tools, agents, workflows, networks, UI components, and configs separated, with strict Zod schemas for tool inputs/outputs and strong environment-based configuration in `src/mastra/config`.
99

@@ -89,9 +89,9 @@ NEXT_PUBLIC_MASTRA_API_URL=http://localhost:4111
8989

9090
## Architecture & conventions
9191

92-
- **Frontend** (`app/`, `ui/`, `src/components/ai-elements/`): Next.js 16 App Router with React 19. AI Elements (30 components) for chat/reasoning/canvas UIs. shadcn/ui base (19 components) in `ui/`. Tailwind CSS 4 with oklch color variables.
93-
- **Tools** (`src/mastra/tools`): 30+ tools implementing `createTool({ id, inputSchema, outputSchema, execute })` with strict Zod schemas. Categories: Financial (Polygon, Finnhub, AlphaVantage), Research (SerpAPI, ArXiv), Data (CSV, JSON), RAG (chunking, embeddings).
94-
- **Agents** (`src/mastra/agents`): 22+ agents composing tools into specialized behaviors (research, stock analysis, content creation, data processing).
92+
- **Frontend** (`app/`, `ui/`, `src/components/ai-elements/`): Next.js 16 App Router with React 19. AI Elements (30 components) for chat/reasoning/canvas UIs. shadcn/ui base (34 components) in `ui/`. Tailwind CSS 4 with oklch color variables.
93+
- **Tools** (`src/mastra/tools`): 34+ tools implementing `createTool({ id, inputSchema, outputSchema, execute })` with strict Zod schemas. Categories: Financial (Polygon, Finnhub, AlphaVantage), Research (SerpAPI, ArXiv), Data (CSV, JSON), RAG (chunking, embeddings).
94+
- **Agents** (`src/mastra/agents`): 38 agents composing tools into specialized behaviors (research, stock analysis, content creation, data processing, business/legal, charting, image processing).
9595
- **Networks** (`src/mastra/networks`): 4 agent networks for routing and orchestration (agentNetwork, dataPipelineNetwork, reportGenerationNetwork, researchPipelineNetwork).
9696
- **Workflows** (`src/mastra/workflows`): 10 multi-step workflows using Mastra DSL (weather, content, financial reports, document processing, research synthesis).
9797
- **Config** (`src/mastra/config`): Centralized provider clients (Google, OpenAI, Anthropic, OpenRouter, Vertex), pg-storage with PgVector, and role hierarchy.
@@ -120,11 +120,11 @@ NEXT_PUBLIC_MASTRA_API_URL=http://localhost:4111
120120
## Where to look for more info
121121

122122
- `app/AGENTS.md`: Next.js App Router pages and layouts
123-
- `ui/AGENTS.md`: shadcn/ui base components (19 components)
123+
- `ui/AGENTS.md`: shadcn/ui base components (34 components)
124124
- `src/components/ai-elements/AGENTS.md`: AI Elements library (30 components)
125125
- `src/mastra/AGENTS.md`: top-level code-agent focused docs (this file is mirrored to subfolders)
126-
- `src/mastra/tools/AGENTS.md`: 30+ tools and their patterns
127-
- `src/mastra/agents/AGENTS.md`: 22+ agents catalog
126+
- `src/mastra/tools/AGENTS.md`: 34+ tools and their patterns
127+
- `src/mastra/agents/AGENTS.md`: 38 agents catalog
128128
- `src/mastra/workflows/AGENTS.md`: 10 workflow definitions
129129
- `src/mastra/networks/AGENTS.md`: 4 agent networks
130130
- `src/mastra/config/AGENTS.md`: configuration and storage guidance
@@ -135,4 +135,4 @@ NEXT_PUBLIC_MASTRA_API_URL=http://localhost:4111
135135
If you need more details for a subdirectory, open the folder-specific `AGENTS.md` which contains persona, purpose, and actionable commands.
136136

137137
---
138-
Last updated: 2025-11-27
138+
Last updated: 2025-12-05

README.md

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
<!-- AGENTS-META {"title":"AgentStack README","version":"3.2.0","applies_to":"/","last_updated":"2025-11-27T00:00:00Z","status":"stable"} -->
1+
<!-- AGENTS-META {"title":"AgentStack README","version":"3.3.0","applies_to":"/","last_updated":"2025-12-05T00:00:00Z","status":"stable"} -->
22

33
<div align="center">
44

@@ -13,7 +13,7 @@
1313
[![wakatime](https://wakatime.com/badge/user/7a2fb9a0-188b-4568-887f-7645f9249e62/project/e44412f3-9bcc-4661-b79d-23160d90dfe0.svg)](https://wakatime.com/badge/user/7a2fb9a0-188b-4568-887f-7645f9249e62/project/e44412f3-9bcc-4661-b79d-23160d90dfe0)
1414
[![GitMCP](https://img.shields.io/endpoint?url=https://gitmcp.io/badge/ssdeanx/AgentStack)](https://gitmcp.io/ssdeanx/AgentStack)
1515

16-
**AgentStack** is a **production-grade multi-agent framework** built on Mastra, delivering **30+ enterprise tools**, **25+ specialized agents**, **10 workflows**, **4 agent networks**, **49 UI components**, and **A2A/MCP orchestration** for scalable AI systems. Focuses on **financial intelligence**, **RAG pipelines**, **observability**, **secure governance**, and **AI chat interfaces**.
16+
**AgentStack** is a **production-grade multi-agent framework** built on Mastra, delivering **34+ enterprise tools**, **38 specialized agents**, **10 workflows**, **4 agent networks**, **64 UI components** (30 AI Elements + 34 base), and **A2A/MCP orchestration** for scalable AI systems. Focuses on **financial intelligence**, **RAG pipelines**, **observability**, **secure governance**, and **AI chat interfaces**.
1717

1818
[![@mastra/core](https://img.shields.io/npm/v/@mastra/core.svg)](https://www.npmjs.com/package/@mastra/core)
1919
[![@mastra/pg](https://img.shields.io/npm/v/@mastra/pg.svg)](https://www.npmjs.com/package/@mastra/pg)
@@ -44,7 +44,7 @@
4444
| **Multi-Agent** |**A2A MCP + parallel orchestration** | ⚠️ Sequential | ✅ Sequential | ✅ Custom |
4545
| **Governance** |**JWT/RBAC + path traversal + HTML sanitization** | ❌ Custom | ❌ None | ❌ None |
4646
| **TypeScript** |**Zod schemas everywhere** | ⚠️ JS/TS mix | ⚠️ JS focus | ❌ Python |
47-
| **UI Components** |**49 AI Elements + shadcn/ui** | ❌ None | ❌ None | ❌ None |
47+
| **UI Components** |**64 AI Elements + shadcn/ui** | ❌ None | ❌ None | ❌ None |
4848
| **Tests** |**97% Vitest coverage** | ⚠️ Partial | ❌ Sparse | ⚠️ Partial |
4949

5050
**Built for production**: Secure, observable, testable agents with **zero-config** PgVector RAG + **enterprise financial APIs**.
@@ -53,11 +53,11 @@
5353

5454
- **💰 Financial Intelligence**: 20+ tools (Polygon quotes/aggs/fundamentals, Finnhub analysis, AlphaVantage indicators)
5555
- **🔍 Semantic RAG**: PgVector (3072D embeddings) + MDocument chunking + rerank + graph traversal
56-
- **🤖 25+ Agents**: Research → Learn → Report → Edit → Analyze (stock/crypto/copywriter/evaluator/data pipeline)
56+
- **🤖 38 Agents**: Research → Learn → Report → Edit → Analyze (stock/crypto/copywriter/evaluator/data pipeline/business-legal/charting/image)
5757
- **📋 10 Workflows**: Weather, content, financial reports, document processing, research synthesis, learning extraction
5858
- **🌐 4 Agent Networks**: Primary routing, data pipeline, report generation, research pipeline
5959
- **🔌 A2A/MCP**: MCP server coordinates parallel agents (research+stock→report)
60-
- **🎨 49 UI Components**: AI Elements (30 chat/reasoning/canvas components) + shadcn/ui (19 base primitives)
60+
- **🎨 64 UI Components**: AI Elements (30 chat/reasoning/canvas components) + shadcn/ui (34 base primitives)
6161
- **📊 Full Observability**: Arize/Phoenix traces + 10+ custom scorers (diversity/quality/completeness)
6262
- **🛡️ Enterprise Security**: JWT auth, RBAC, path validation, HTML sanitization, secrets masking
6363
- **⚡ Extensible**: Model registry (Gemini/OpenAI/Anthropic), Zod schemas everywhere
@@ -67,7 +67,7 @@
6767
```mermaid
6868
graph TB
6969
subgraph "� Frontend (Next.js 16)"
70-
UI[AI Elements + shadcn/ui<br/>• 30 AI Components<br/>• 19 Base Primitives]
70+
UI[AI Elements + shadcn/ui<br/>• 30 AI Components<br/>• 34 Base Primitives]
7171
App[App Router<br/>• React 19<br/>• Tailwind CSS 4]
7272
end
7373
@@ -76,8 +76,8 @@ graph TB
7676
end
7777
7878
subgraph "🎯 AgentStack Runtime"
79-
Coord --> Agents[22+ Agents<br/>• ResearchAgent<br/>• StockAnalysis<br/>• Copywriter<br/>• ReportAgent]
80-
Agents --> Tools[30+ Tools<br/>• Polygon/Finnhub<br/>• SerpAPI 10+<br/>• PgVector RAG<br/>• PDF→MD]
79+
Coord --> Agents[38 Agents<br/>• ResearchAgent<br/>• StockAnalysis<br/>• Copywriter<br/>• ReportAgent]
80+
Agents --> Tools[34+ Tools<br/>• Polygon/Finnhub<br/>• SerpAPI 10+<br/>• PgVector RAG<br/>• PDF→MD]
8181
Agents --> Workflows[Research→Report<br/>Weather→Activities]
8282
end
8383
@@ -212,14 +212,14 @@ npm run start
212212
```bash
213213
# Frontend
214214
app/ # 📱 Next.js 16 App Router (layouts, pages)
215-
ui/ # 🎨 shadcn/ui base components (19 primitives)
215+
ui/ # 🎨 shadcn/ui base components (34 primitives)
216216
src/components/ai-elements/ # 🤖 AI Elements (30 chat/reasoning/canvas components)
217217

218218
# Backend
219219
src/mastra/
220-
├── index.ts # 🎯 Mastra bootstrap (25+ agents, 10 workflows, 4 networks, MCP)
221-
├── agents/ # 🤖 22+ agents (research/stock/copywriter/report/data pipeline...)
222-
├── tools/ # 🔧 30+ tools (financial/RAG/scrape/PDF/SerpAPI...)
220+
├── index.ts # 🎯 Mastra bootstrap (38 agents, 10 workflows, 4 networks, MCP)
221+
├── agents/ # 🤖 38 agents (research/stock/copywriter/report/data pipeline/business-legal/charting...)
222+
├── tools/ # 🔧 34+ tools (financial/RAG/scrape/PDF/SerpAPI...)
223223
├── workflows/ # 📋 10 workflows (weather, content, financial, document, research)
224224
├── networks/ # 🌐 4 agent networks (routing/coordination)
225225
├── config/ # ⚙️ Models/PgVector/Logging/Auth
@@ -333,10 +333,10 @@ npm run mcp-server
333333

334334
## 📚 **Resources**
335335

336-
- **[UI Components](ui/AGENTS.md)**: 19 shadcn/ui base components
336+
- **[UI Components](ui/AGENTS.md)**: 34 shadcn/ui base components
337337
- **[AI Elements](src/components/ai-elements/AGENTS.md)**: 30 AI chat/reasoning/canvas components
338-
- **[Agents Catalog](src/mastra/agents/AGENTS.md)**: 22+ agents
339-
- **[Tools Matrix](src/mastra/tools/AGENTS.md)**: 30+ tools
338+
- **[Agents Catalog](src/mastra/agents/AGENTS.md)**: 38 agents
339+
- **[Tools Matrix](src/mastra/tools/AGENTS.md)**: 34+ tools
340340
- **[Workflows](src/mastra/workflows/AGENTS.md)**: 10 multi-step workflows
341341
- **[Networks](src/mastra/networks/AGENTS.md)**: 4 agent networks
342342
- **[Config Guide](src/mastra/config/AGENTS.md)**: Setup + env vars
@@ -350,7 +350,7 @@ npm run mcp-server
350350
- [x] **A2A MCP**: Parallel orchestration (✅ Live)
351351
- [x] **10 Workflows**: Sequential, parallel, branch, loop, foreach, suspend/resume (✅ Live)
352352
- [x] **4 Agent Networks**: Routing and coordination (✅ Live)
353-
- [x] **UI Components**: AI Elements + shadcn/ui (49 components) (✅ Live)
353+
- [x] **UI Components**: AI Elements + shadcn/ui (64 components) (✅ Live)
354354
- [ ] **Chat Interface**: Full agent chat UI with AI Elements
355355
- [ ] **LangSmith/Phoenix**: Eval dashboards
356356
- [ ] **Docker/Helm**: K8s deploy
@@ -362,4 +362,4 @@ npm run mcp-server
362362
🐦 **Follow [@ssdeanx](https://x.com/ssdeanx)**
363363
📘 **[Docs](https://agentstack.ai)** (Coming Q1 2026)
364364

365-
_Last updated: 2025-11-27 | v3.2.0_
365+
_Last updated: 2025-12-05 | v3.3.0_

app/api/chat/route.ts

Lines changed: 16 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -1,64 +1,21 @@
1-
import { mastra } from "@/src/mastra";
2-
import { createAgentStreamResponse } from "@/lib/client-stream-to-ai-sdk";
3-
import type { UIMessage } from "ai";
4-
5-
export const maxDuration = 60;
6-
7-
interface ChatRequestBody {
8-
messages: UIMessage[];
9-
agentId?: string;
10-
threadId?: string;
11-
resourceId?: string;
12-
memory?: {
13-
thread?: string | { id: string; resourceId?: string };
14-
resource?: string;
15-
options?: {
16-
lastMessages?: number;
17-
semanticRecall?: boolean;
18-
workingMemory?: { enabled?: boolean };
19-
};
20-
};
21-
maxSteps?: number;
22-
}
1+
import { mastra } from "../../../src/mastra";
2+
import { RuntimeContext } from "@mastra/core/runtime-context";
233

244
export async function POST(req: Request) {
25-
const body: ChatRequestBody = await req.json();
26-
27-
// Get available agents dynamically from mastra
28-
const agentsMap = await mastra.getAgents();
29-
const availableAgents = Object.keys(agentsMap);
30-
31-
// Use first available agent if none specified
32-
const agentId = body.agentId || availableAgents[0];
33-
34-
if (!agentId || !availableAgents.includes(agentId)) {
35-
return Response.json(
36-
{ error: `Invalid or missing agentId. Available: ${availableAgents.join(", ")}` },
37-
{ status: 400 }
38-
);
39-
}
5+
const { messages, data } = await req.json();
6+
const myAgent = mastra.getAgent("weatherAgent");
407

41-
if (!body.messages?.length) {
42-
return Response.json({ error: "messages required" }, { status: 400 });
43-
}
44-
45-
try {
46-
return await createAgentStreamResponse(mastra as Parameters<typeof createAgentStreamResponse>[0], agentId, body.messages, {
47-
threadId: body.threadId,
48-
resourceId: body.resourceId,
49-
memory: body.memory,
50-
maxSteps: body.maxSteps ?? 50,
51-
});
52-
} catch (error) {
53-
return Response.json(
54-
{ error: error instanceof Error ? error.message : "Stream failed" },
55-
{ status: 500 }
56-
);
8+
const runtimeContext = new RuntimeContext();
9+
10+
if (data) {
11+
for (const [key, value] of Object.entries(data)) {
12+
runtimeContext.set(key, value);
13+
}
5714
}
58-
}
5915

60-
export async function GET() {
61-
const agentsMap = await mastra.getAgents();
62-
const availableAgents = Object.keys(agentsMap);
63-
return Response.json({ agents: availableAgents, count: availableAgents.length });
64-
}
16+
const stream = await myAgent.stream(messages, {
17+
runtimeContext,
18+
format: "aisdk",
19+
});
20+
return stream.toUIMessageStreamResponse();
21+
}

lib/client-stream-to-ai-sdk.ts

Lines changed: 44 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ import {
33
createUIMessageStreamResponse,
44
} from "ai";
55
import { toAISdkFormat } from "@mastra/ai-sdk";
6+
import type { Mastra } from "@mastra/core/mastra";
7+
import type { AgentExecutionOptions } from "@mastra/core/agent";
68
import type { MastraModelOutput } from "@mastra/core/stream";
79

810
export interface StreamToAISdkOptions {
@@ -16,34 +18,34 @@ export interface AgentStreamOptions {
1618
format?: "aisdk" | "mastra";
1719
threadId?: string;
1820
resourceId?: string;
19-
memory?: {
20-
thread?: string | { id: string; resourceId?: string };
21-
resource?: string;
22-
options?: {
23-
lastMessages?: number;
24-
semanticRecall?: boolean;
25-
workingMemory?: { enabled?: boolean };
26-
};
27-
};
21+
memory?: AgentExecutionOptions["memory"];
2822
maxSteps?: number;
2923
}
3024

31-
type MastraAgent = {
32-
stream: (
33-
messages: unknown,
34-
options?: {
35-
format?: string;
36-
threadId?: string;
37-
resourceId?: string;
38-
memory?: AgentStreamOptions["memory"];
39-
maxSteps?: number;
40-
}
41-
) => Promise<MastraModelOutput & { toUIMessageStreamResponse?: () => Response }>;
42-
};
25+
type StreamResult = MastraModelOutput & { toUIMessageStreamResponse?: () => Response };
26+
27+
function isReadableStream<T>(value: unknown): value is ReadableStream<T> {
28+
return (
29+
typeof value === "object" &&
30+
value !== null &&
31+
typeof (value as ReadableStream<T>).getReader === "function"
32+
);
33+
}
4334

44-
type MastraInstance = {
45-
getAgent: (id: string) => MastraAgent;
46-
} & Record<string, any>;
35+
async function* asyncIterableFromReadableStream<T>(
36+
stream: ReadableStream<T>
37+
): AsyncIterable<T> {
38+
const reader = stream.getReader();
39+
try {
40+
while (true) {
41+
const { done, value } = await reader.read();
42+
if (done) break;
43+
yield value;
44+
}
45+
} finally {
46+
reader.releaseLock();
47+
}
48+
}
4749

4850
/**
4951
* Creates a streaming Response for Next.js API routes using server-side Mastra agent.
@@ -55,7 +57,7 @@ type MastraInstance = {
5557
* ```ts
5658
* // app/api/chat/route.ts
5759
* import { mastra } from "@/src/mastra";
58-
* import { createAgentStreamResponse } from "@/lib/client-stream-to-ai-sdk";
60+
* import { createAgentStreamResponse } from "@/lib/server/agent-stream";
5961
*
6062
* export async function POST(req: Request) {
6163
* const { messages, agentId, threadId, resourceId, memory } = await req.json();
@@ -70,7 +72,7 @@ type MastraInstance = {
7072
* @see https://mastra.ai/docs/frameworks/agentic-uis/ai-sdk
7173
*/
7274
export async function createAgentStreamResponse(
73-
mastra: MastraInstance,
75+
mastra: Mastra,
7476
agentId: string,
7577
messages: unknown,
7678
options?: AgentStreamOptions
@@ -85,34 +87,27 @@ export async function createAgentStreamResponse(
8587
maxSteps: options?.maxSteps,
8688
};
8789

88-
// Preferred: Use built-in AI SDK format
89-
if (streamOptions.format === "aisdk") {
90-
const stream = await agent.stream(messages, streamOptions);
91-
if (stream.toUIMessageStreamResponse) {
92-
return stream.toUIMessageStreamResponse();
93-
}
90+
// Call agent.stream once and reuse the result
91+
const stream = await agent.stream(messages, streamOptions) as StreamResult;
92+
93+
// Preferred: Use built-in AI SDK format when available
94+
if (streamOptions.format === "aisdk" && stream.toUIMessageStreamResponse) {
95+
return stream.toUIMessageStreamResponse();
9496
}
9597

9698
// Fallback: Manual transformation with toAISdkFormat
97-
const stream = await agent.stream(messages, {
98-
threadId: options?.threadId,
99-
resourceId: options?.resourceId,
100-
memory: options?.memory,
101-
maxSteps: options?.maxSteps,
102-
});
103-
99+
// Handles both ReadableStream and AsyncIterable return types
104100
const uiMessageStream = createUIMessageStream({
105101
execute: async ({ writer }) => {
106-
const aiSdkStream = toAISdkFormat(stream, { from: "agent" });
107-
const reader = aiSdkStream.getReader();
108-
try {
109-
while (true) {
110-
const { done, value } = await reader.read();
111-
if (done) break;
112-
writer.write(value);
113-
}
114-
} finally {
115-
reader.releaseLock();
102+
const aiSdkResult = toAISdkFormat(stream, { from: "agent" });
103+
104+
// Handle both ReadableStream and AsyncIterable
105+
const iterable: AsyncIterable<unknown> = isReadableStream(aiSdkResult)
106+
? asyncIterableFromReadableStream(aiSdkResult)
107+
: aiSdkResult;
108+
109+
for await (const value of iterable) {
110+
writer.write(value as Parameters<typeof writer.write>[0]);
116111
}
117112
},
118113
});

lib/mastra-client.ts

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,12 @@
11
import { MastraClient } from "@mastra/client-js";
22

3+
/**
4+
* Client-side Mastra SDK instance for frontend use.
5+
* Use this in React components to interact with the Mastra API.
6+
*
7+
* For server-side streaming in API routes, import createAgentStreamResponse
8+
* directly from "@/lib/client-stream-to-ai-sdk" instead.
9+
*/
310
export const mastraClient = new MastraClient({
411
baseUrl: process.env.NEXT_PUBLIC_MASTRA_API_URL || "http://localhost:4111",
512
retries: 3,
@@ -9,6 +16,3 @@ export const mastraClient = new MastraClient({
916
headers: {},
1017
credentials: "same-origin",
1118
});
12-
13-
export { createAgentStreamResponse } from "./client-stream-to-ai-sdk";
14-
export type { StreamToAISdkOptions } from "./client-stream-to-ai-sdk";

0 commit comments

Comments
 (0)