Crawler Summary

agentstack answer-first brief

Multi-agent frameworks and tools for building AI applications with Mastra. <!-- AGENTS-META {"title":"AgentStack README","version":"3.4.0","applies_to":"/","last_updated":"2026-02-16T00:00:00Z","status":"stable"} --> <div align="center"> 🚀 AgentStack <img src="assets/logo.png" width="128" height="128" alt="AgentStack Logo" /> <!-- Core Project Badges --> $1 $1 $1 $1 $1 <!-- Stats Badges --> $1 $1 $1 $1 $1 <!-- Quality Badges --> $1 $1 $1 <!-- Repository Links --> $1 $1 $1 **AgentStack** is Capability contract not published. No trust telemetry is available yet. 17 GitHub stars reported by the source. Last updated 2/25/2026.

Freshness

Last checked 2/25/2026

Best For

agentstack is best for ai, agents, mastra workflows where MCP compatibility matters.

Not Ideal For

Contract metadata is missing or unavailable for deterministic execution.

Evidence Sources Checked

editorial-content, GITHUB MCP, runtime-metrics, public facts pack

Claim this agent
Agent DossierGitHubSafety: 100/100

agentstack

Multi-agent frameworks and tools for building AI applications with Mastra. <!-- AGENTS-META {"title":"AgentStack README","version":"3.4.0","applies_to":"/","last_updated":"2026-02-16T00:00:00Z","status":"stable"} --> <div align="center"> 🚀 AgentStack <img src="assets/logo.png" width="128" height="128" alt="AgentStack Logo" /> <!-- Core Project Badges --> $1 $1 $1 $1 $1 <!-- Stats Badges --> $1 $1 $1 $1 $1 <!-- Quality Badges --> $1 $1 $1 <!-- Repository Links --> $1 $1 $1 **AgentStack** is

MCPself-declared

Public facts

4

Change events

0

Artifacts

0

Freshness

Feb 25, 2026

Verifiededitorial-contentNo verified compatibility signals17 GitHub stars

Capability contract not published. No trust telemetry is available yet. 17 GitHub stars reported by the source. Last updated 2/25/2026.

17 GitHub starsTrust evidence available

Trust score

Unknown

Compatibility

MCP

Freshness

Feb 25, 2026

Vendor

Deanmachines

Artifacts

0

Benchmarks

0

Last release

1.2.1

Executive Summary

Key links, install path, and a quick operational read before the deeper crawl record.

Verifiededitorial-content

Summary

Capability contract not published. No trust telemetry is available yet. 17 GitHub stars reported by the source. Last updated 2/25/2026.

Setup snapshot

git clone https://github.com/ssdeanx/AgentStack.git
  1. 1

    Setup complexity is MEDIUM. Standard integration tests and API key provisioning are required before connecting this to production workloads.

  2. 2

    Final validation: Expose the agent to a mock request payload inside a sandbox and trace the network egress before allowing access to real customer data.

Evidence Ledger

Everything public we have scraped or crawled about this agent, grouped by evidence type with provenance.

Verifiededitorial-content
Vendor (1)

Vendor

Deanmachines

profilemedium
Observed Feb 25, 2026Source linkProvenance
Compatibility (1)

Protocol compatibility

MCP

contractmedium
Observed Feb 25, 2026Source linkProvenance
Adoption (1)

Adoption signal

17 GitHub stars

profilemedium
Observed Feb 25, 2026Source linkProvenance
Security (1)

Handshake status

UNKNOWN

trustmedium
Observed unknownSource linkProvenance

Release & Crawl Timeline

Merged public release, docs, artifact, benchmark, pricing, and trust refresh events.

Self-declaredagent-index

Artifacts Archive

Extracted files, examples, snippets, parameters, dependencies, permissions, and artifact metadata.

Self-declaredGITHUB MCP

Extracted files

0

Examples

6

Snippets

0

Languages

typescript

Executable Examples

typescript

// Example: Multi-source stock analysis
const analysis = await stockAnalysisAgent.execute({
    symbol: 'AAPL',
    includeFundamentals: true,
    includeNews: true,
    timeRange: '1Y',
})
// → Combines Polygon quotes, Finnhub analysis, AlphaVantage indicators
// → Returns: Price action, valuation metrics, sentiment analysis

typescript

// 1. Index documents
await documentProcessingWorkflow.execute({
    documents: ['./annual-report.pdf', './market-data.csv'],
    chunkingStrategy: 'semantic',
    indexName: 'financial-reports',
})

// 2. Query with context
const answer = await governedRagAnswerWorkflow.execute({
    query: 'What were Q3 revenue drivers?',
    indexName: 'financial-reports',
    rerankTopK: 5,
})
// → Returns: Synthesized answer + source citations + confidence score

typescript

// Research + Analysis + Report in parallel
const result = await researchPipelineNetwork.execute({
    query: 'Analyze renewable energy market trends',
    agents: ['research', 'learning', 'knowledge', 'synthesis'],
    parallel: true,
})
// → 4 agents work simultaneously, results merged by coordinator

typescript

// Traces automatically captured
const trace = await langfuse.getTrace(traceId)
// → Agent execution steps
// → Tool calls with latency
// → Token usage per step
// → Custom scorer results (quality, diversity, completeness)

tsx

import { AgentArtifact, AgentChainOfThought, AgentSources } from '@/ai-elements'

// Render streaming AI responses
<AgentChainOfThought
  steps={reasoningSteps}
  isStreaming={true}
  duration={1500}
/>

// Display code artifacts with syntax highlighting
<AgentArtifact
  artifact={{
    type: 'code',
    language: 'typescript',
    content: generatedCode
  }}
  onCodeUpdate={handleUpdate}
/>

// Show source citations
<AgentSources
  sources={citedSources}
  maxVisible={5}
/>

typescript

// Multi-agent stock research with visual reports
const report = await financialIntelligenceNetwork.execute({
    symbol: 'TSLA',
    includeTechnicalAnalysis: true,
    includeNewsSentiment: true,
    generateCharts: true,
})
// → Combines 7 specialized agents
// → Generates PDF report with charts and citations

Docs & README

Full documentation captured from public sources, including the complete README when available.

Self-declaredGITHUB MCP

Docs source

GITHUB MCP

Editorial quality

ready

Multi-agent frameworks and tools for building AI applications with Mastra. <!-- AGENTS-META {"title":"AgentStack README","version":"3.4.0","applies_to":"/","last_updated":"2026-02-16T00:00:00Z","status":"stable"} --> <div align="center"> 🚀 AgentStack <img src="assets/logo.png" width="128" height="128" alt="AgentStack Logo" /> <!-- Core Project Badges --> $1 $1 $1 $1 $1 <!-- Stats Badges --> $1 $1 $1 $1 $1 <!-- Quality Badges --> $1 $1 $1 <!-- Repository Links --> $1 $1 $1 **AgentStack** is

Full README
<!-- AGENTS-META {"title":"AgentStack README","version":"3.4.0","applies_to":"/","last_updated":"2026-02-16T00:00:00Z","status":"stable"} --> <div align="center">

🚀 AgentStack

<img src="assets/logo.png" width="128" height="128" alt="AgentStack Logo" />

Home Networks Custom Tool v1.0.0

<!-- Core Project Badges -->

Node.js TypeScript Next.js React License

<!-- Stats Badges -->

Agents Tools Workflows Networks UI Components

<!-- Quality Badges -->

Tests Zod ESLint

<!-- Repository Links -->

GitHub GitMCP wakatime

AgentStack is a production-grade multi-agent framework built on Mastra, delivering 60+ enterprise tools, 48+ specialized agents, 21 workflows, 12 agent networks, 105 UI components (50+ AI Elements + 55+ base), and A2A/MCP orchestration for scalable AI systems. Focuses on financial intelligence, RAG pipelines, observability, secure governance, and AI chat interfaces.

<!-- Mastra Ecosystem -->

@mastra/core @mastra/pg @mastra/rag @mastra/memory @mastra/ai-sdk

<!-- AI/ML Stack -->

@ai-sdk/google @ai-sdk/react Langfuse PgVector

<!-- LLM Providers -->

Gemini OpenAI Anthropic

</div>

🎯 Why AgentStack?

AgentStack bridges the gap between experimental AI frameworks and production-ready systems. While other frameworks focus on prototyping, AgentStack delivers the observability, security, and scalability required for enterprise deployment.

| Feature | AgentStack | LangChain | CrewAI | AutoGen | | ----------------------------- | --------------------------------------------------------------- | ------------- | ------------- | ---------- | | Production Observability | ✅ Full Langfuse tracing + 10+ custom scorers | ⚠️ Partial | ❌ Basic | ❌ Limited | | Financial Intelligence | ✅ Polygon/Finnhub/AlphaVantage (30+ endpoints) | ❌ None | ❌ None | ❌ None | | RAG Pipeline | ✅ PgVector HNSW + rerank + graphRAG | ⚠️ External | ❌ Basic | ❌ None | | Multi-Agent Orchestration | ✅ A2A MCP + parallel execution (48+ agents) | ⚠️ Sequential | ✅ Sequential | ✅ Custom | | Enterprise Security | ✅ JWT/RBAC + path traversal protection + HTML sanitization | ❌ Custom | ❌ None | ❌ None | | Type Safety | ✅ Zod schemas everywhere (94+ tools) | ⚠️ JS/TS mix | ⚠️ JS focus | ❌ Python | | UI Components | ✅ 105 components (AI Elements + shadcn/ui) | ❌ None | ❌ None | ❌ None | | Testing | ✅ Vitest + 97% coverage + comprehensive mocks | ⚠️ Partial | ❌ Sparse | ⚠️ Partial |

🚀 Production-Ready from Day One

  • Zero-config RAG: PgVector with 3072D embeddings works out of the box
  • Enterprise APIs: First-class support for financial data providers
  • Full Observability: Every agent call, tool execution, and workflow step is traced
  • Type Safety: Strict TypeScript with Zod validation on all boundaries

Core Capabilities

  • 💰 Financial Intelligence: 30+ tools (Polygon quotes/aggs/fundamentals, Finnhub analysis, AlphaVantage indicators)
  • 🔍 Semantic RAG: PgVector (3072D embeddings) + MDocument chunking + rerank + graph traversal
  • 🤖 48+ Agents: Research → Learn → Report → Edit → Analyze (stock/crypto/copywriter/evaluator/data pipeline/business-legal/charting/image/coding/dane/social media/SEO/translation/customer support/project management)
  • 📋 21 Workflows: Weather, content, financial reports, document processing, research synthesis, learning extraction, governed RAG (index + answer), spec generation, repo ingestion, stock analysis, marketing campaign
  • 🌐 12 Agent Networks: Primary routing, data pipeline, report generation, research pipeline, content creation, financial intelligence, learning, marketing automation, DevOps, business intelligence, security
  • 🔌 A2A/MCP: MCP server coordinates parallel agents (research+stock→report), A2A coordinator for cross-agent communication
  • 🎨 105 UI Components: AI Elements (50 chat/reasoning/canvas components) + shadcn/ui (55 base primitives)
  • 📊 Full Observability: Langfuse traces + 10+ custom scorers (diversity/quality/completeness) + TanStack Query for state management
  • 🛡️ Enterprise Security: JWT auth, RBAC, path validation, HTML sanitization, secrets masking
  • ⚡ Extensible: Model registry (Gemini/OpenAI/Anthropic/OpenRouter), Zod schemas everywhere, MastraClient SDK integration

🌟 Feature Highlights

💰 Financial Intelligence Suite

Real-time market data from 30+ endpoints:

// Example: Multi-source stock analysis
const analysis = await stockAnalysisAgent.execute({
    symbol: 'AAPL',
    includeFundamentals: true,
    includeNews: true,
    timeRange: '1Y',
})
// → Combines Polygon quotes, Finnhub analysis, AlphaVantage indicators
// → Returns: Price action, valuation metrics, sentiment analysis

Supported Data Providers:

  • Polygon.io: Real-time quotes, historical aggregates, fundamentals
  • Finnhub: Company profiles, insider transactions, earnings surprises
  • Alpha Vantage: Technical indicators (RSI, MACD, Bollinger Bands)

🔍 Production RAG Pipeline

Zero-config semantic search with PgVector:

// 1. Index documents
await documentProcessingWorkflow.execute({
    documents: ['./annual-report.pdf', './market-data.csv'],
    chunkingStrategy: 'semantic',
    indexName: 'financial-reports',
})

// 2. Query with context
const answer = await governedRagAnswerWorkflow.execute({
    query: 'What were Q3 revenue drivers?',
    indexName: 'financial-reports',
    rerankTopK: 5,
})
// → Returns: Synthesized answer + source citations + confidence score

Features:

  • 10 Chunking Strategies: Semantic, recursive, markdown-aware
  • 3072D Embeddings: Gemini embedding-001
  • Hybrid Search: Vector similarity + BM25 reranking
  • Graph Traversal: Relationship-aware context expansion

🤖 Agent Networks

Parallel multi-agent orchestration:

// Research + Analysis + Report in parallel
const result = await researchPipelineNetwork.execute({
    query: 'Analyze renewable energy market trends',
    agents: ['research', 'learning', 'knowledge', 'synthesis'],
    parallel: true,
})
// → 4 agents work simultaneously, results merged by coordinator

Pre-configured Networks:

  • Coding Team: Architect → Reviewer → Tester → Refactorer
  • Financial Intelligence: Researcher → Analyst → Chart Generator → Reporter
  • Content Creation: Writer → Editor → Strategist → SEO Optimizer

📊 Full Observability

Every operation traced with Langfuse:

// Traces automatically captured
const trace = await langfuse.getTrace(traceId)
// → Agent execution steps
// → Tool calls with latency
// → Token usage per step
// → Custom scorer results (quality, diversity, completeness)

Dashboard Views:

  • Real-time trace visualization
  • Performance metrics (latency, error rates)
  • Cost tracking by agent/workflow
  • Custom scorer analytics

🎨 AI Elements UI Library

50+ production-ready React components:

import { AgentArtifact, AgentChainOfThought, AgentSources } from '@/ai-elements'

// Render streaming AI responses
<AgentChainOfThought
  steps={reasoningSteps}
  isStreaming={true}
  duration={1500}
/>

// Display code artifacts with syntax highlighting
<AgentArtifact
  artifact={{
    type: 'code',
    language: 'typescript',
    content: generatedCode
  }}
  onCodeUpdate={handleUpdate}
/>

// Show source citations
<AgentSources
  sources={citedSources}
  maxVisible={5}
/>

🚀 What You Can Build

Real-world applications powered by AgentStack:

📈 Financial Analysis Platform

// Multi-agent stock research with visual reports
const report = await financialIntelligenceNetwork.execute({
    symbol: 'TSLA',
    includeTechnicalAnalysis: true,
    includeNewsSentiment: true,
    generateCharts: true,
})
// → Combines 7 specialized agents
// → Generates PDF report with charts and citations

Features:

  • Real-time market data from multiple providers
  • Automated technical analysis (RSI, MACD, Bollinger Bands)
  • News sentiment analysis with SerpAPI
  • Interactive chart generation
  • PDF report export with source citations

📚 Enterprise Knowledge Base

// Ingest and query company documents
await documentProcessingWorkflow.execute({
    source: 'https://company.com/docs',
    includeSubpages: true,
    chunkingStrategy: 'semantic',
    extractMetadata: true,
})

const answer = await knowledgeBaseAgent.execute({
    query: 'What is our refund policy?',
    includeSources: true,
    confidenceThreshold: 0.8,
})
// → Searches across all indexed documents
// → Returns answer with source URLs

Features:

  • Web scraping with recursive crawling
  • PDF/CSV/JSON document processing
  • Semantic chunking with 10 strategies
  • Hybrid search (vector + keyword)
  • Source attribution for every answer

🤖 AI Coding Assistant

// Code review and refactoring pipeline
const result = await codingTeamNetwork.execute({
    task: 'Refactor authentication module',
    code: './src/auth/*',
    requirements: [
        'Improve security',
        'Add rate limiting',
        'Better error handling',
    ],
})
// → Architect designs solution
// → Reviewer validates approach
// → Tester generates test cases
// → Refactorer implements changes

Features:

  • Multi-agent code review pipeline
  • Automatic test generation
  • Security vulnerability detection
  • TypeScript/React expertise
  • GitHub integration for PR automation

📊 Content Creation Studio

// End-to-end content production
const content = await contentCreationNetwork.execute({
    topic: 'Sustainable investing trends',
    formats: ['blog', 'social', 'newsletter'],
    tone: 'professional',
    seoOptimize: true,
})
// → Writer creates draft
// → Editor refines content
// → Strategist optimizes for engagement
// → SEO agent adds keywords and meta

Features:

  • Multi-format content generation
  • SEO optimization with keyword research
  • Tone and style consistency
  • Social media post generation
  • Editorial calendar integration

🔍 Research Synthesis Engine

// Automated literature review
const research = await researchPipelineNetwork.execute({
    query: 'Latest advances in LLM safety',
    sources: ['arxiv', 'serpapi', 'web'],
    synthesizeFindings: true,
    generateReport: true,
})
// → Searches across academic and web sources
// → Extracts key findings
// → Identifies consensus and gaps
// → Generates comprehensive report

Features:

  • ArXiv paper analysis
  • Web scraping with content extraction
  • Citation tracking and verification
  • Consensus detection across sources
  • Automated report generation

🏗️ System Architecture

%%{init: {'theme': 'dark', 'themeVariables': { 'primaryColor': '#58a6ff', 'primaryTextColor': '#c9d1d9', 'primaryBorderColor': '#30363d', 'lineColor': '#58a6ff', 'sectionBkgColor': '#161b22', 'altSectionBkgColor': '#0d1117', 'sectionTextColor': '#c9d1d9', 'gridColor': '#30363d', 'tertiaryColor': '#161b22', 'fontFamily': 'JetBrains Mono, monospace' }}}%%
graph TB
    subgraph "🎨 Frontend Layer"
        direction TB
        UI[AI Elements Library<br/>• 50 Chat/Reasoning/Canvas Components<br/>• Real-time Streaming]
        Base[shadcn/ui Foundation<br/>• 55 Base Primitives<br/>• Accessible & Themable]
        App[Next.js 16 App Router<br/>• React 19 + Server Components<br/>• Tailwind CSS 4 + oklch]
    end

    subgraph "🌐 External Interfaces"
        direction LR
        Client[MCP Clients<br/>Cursor / Claude / Windsurf]
        API[REST API<br/>OpenAPI + Typed SDK]
        SDK[MastraClient SDK<br/>TanStack Query Integration]
    end

    subgraph "⚡ AgentStack Runtime"
        direction TB
        Coord[A2A Coordinator<br/>Parallel Agent Orchestration]

        subgraph "Intelligent Agents"
            Agents[48+ Specialized Agents]
            Research[Research Suite]
            Financial[Financial Intelligence]
            Coding[Coding Team]
            Content[Content Creation]
        end

        subgraph "Tool Ecosystem"
            Tools[60+ Enterprise Tools]
            APIs[Financial APIs<br/>Polygon / Finnhub / AlphaVantage]
            Search[Search & Research<br/>SerpAPI / ArXiv / Web Scraping]
            RAG[RAG Pipeline<br/>PgVector + Embeddings]
        end

        subgraph "Workflow Engine"
            Workflows[21 Multi-Step Workflows]
            Sequential[Sequential Execution]
            Parallel[Parallel Branches]
            Suspense[Suspend/Resume]
        end

        subgraph "Network Topology"
            Networks[12 Agent Networks]
            Routing[Smart Routing]
            Coordination[Cross-Agent Communication]
        end
    end

    subgraph "🗄️ Data & Persistence Layer"
        direction TB
        VectorStore[(PgVector<br/>3072D Embeddings<br/>HNSW/Flat Indexes)]
        Relational[(PostgreSQL<br/>Memory Threads<br/>Workflow State)]
        Cache[(Redis-ready<br/>Session Management)]
    end

    subgraph "📊 Observability Stack"
        direction LR
        Tracing[Langfuse Tracing<br/>100% Coverage]
        Metrics[Custom Scorers<br/>10+ Quality Metrics]
        Analytics[Performance Analytics<br/>Latency / Errors / Usage]
    end

    %% Connections
    UI --> App
    Base --> UI
    App --> SDK
    SDK --> Coord

    Client --> Coord
    API --> Coord

    Coord --> Agents
    Coord --> Workflows
    Coord --> Networks

    Agents --> Tools
    Agents --> VectorStore
    Agents --> Relational

    Workflows --> Agents
    Networks --> Agents

    Tools --> VectorStore
    Tools --> Relational

    Agents --> Tracing
    Workflows --> Tracing
    Networks --> Tracing
    Tools --> Tracing

    Tracing --> Metrics
    Tracing --> Analytics

    %% Styling
    classDef frontend fill:#1e3a5f,stroke:#58a6ff,stroke-width:3px,color:#fff
    classDef runtime fill:#2d4a22,stroke:#7ee787,stroke-width:3px,color:#fff
    classDef storage fill:#3d2817,stroke:#ffa657,stroke-width:3px,color:#fff
    classDef observe fill:#2a2a4a,stroke:#d2a8ff,stroke-width:3px,color:#fff
    classDef external fill:#3d3d3d,stroke:#8b949e,stroke-width:2px,color:#fff

    class UI,Base,App frontend
    class Coord,Agents,Tools,Workflows,Networks,Research,Financial,Coding,Content,APIs,Search,RAG,Sequential,Parallel,Suspense,Routing,Coordination runtime
    class VectorStore,Relational,Cache storage
    class Tracing,Metrics,Analytics observe
    class Client,API,SDK external

🔍 Chat UI-Backend Architecture

%%{init: {'theme': 'dark', 'themeVariables': { 'primaryColor': '#58a6ff', 'primaryTextColor': '#c9d1d9', 'primaryBorderColor': '#30363d', 'lineColor': '#58a6ff', 'sectionBkgColor': '#161b22', 'altSectionBkgColor': '#0d1117', 'sectionTextColor': '#c9d1d9', 'gridColor': '#30363d', 'tertiaryColor': '#161b22' }}}%%
sequenceDiagram
    participant UI as ChatUI
    participant Msg as MessageItem
    participant TG as TypeGuards
    participant ADS as AgentDataSection
    participant WDS as WorkflowDataSection
    participant NDS as NetworkDataSection
    participant AT as AgentTool

    UI->>Msg: render(message)
    Msg->>Msg: compute dataParts via useMemo

    loop for each part in dataParts
        Msg->>TG: isAgentDataPart(part)
        alt part is AgentDataPart
            Msg->>ADS: render part
            ADS-->>Msg: Agent execution collapsible
        else not AgentDataPart
            Msg->>TG: isWorkflowDataPart(part)
            alt part is WorkflowDataPart
                Msg->>WDS: render part
                WDS-->>Msg: Workflow execution collapsible
            else not WorkflowDataPart
                Msg->>TG: isNetworkDataPart(part)
                alt part is NetworkDataPart
                    Msg->>NDS: render part
                    NDS-->>Msg: Network execution collapsible
                else other data-tool-* part
                    alt part.type startsWith data-tool-
                        Msg->>AT: render custom tool UI
                        AT-->>Msg: Tool-specific panel
                    else generic data-* part
                        Msg-->>Msg: render generic Collapsible with JSON
                    end
                end
            end
        end
    end

    Msg-->>UI: message body with nested sections

📊 System Flowchart

%%{init: {'theme': 'dark', 'themeVariables': { 'primaryColor': '#58a6ff', 'primaryTextColor': '#c9d1d9', 'primaryBorderColor': '#30363d', 'lineColor': '#58a6ff', 'sectionBkgColor': '#161b22', 'altSectionBkgColor': '#0d1117', 'sectionTextColor': '#c9d1d9', 'gridColor': '#30363d', 'tertiaryColor': '#161b22' }}}%%
classDiagram
    direction LR

    class UIMessage {
      +string id
      +parts MastraDataPart[]
    }

    class MastraDataPart {
      +string type
      +string id
      +unknown data
    }

    class AgentDataPart {
      +string type
      +string id
      +AgentExecutionData data
    }

    class WorkflowDataPart {
      +string type
      +string id
      +WorkflowExecutionData data
    }

    class NetworkDataPart {
      +string type
      +string id
      +NetworkExecutionData data
    }

    class AgentExecutionData {
      +string text
      +unknown usage
      +toolResults unknown[]
    }

    class WorkflowExecutionData {
      +string name
      +string status
      +WorkflowStepMap steps
      +WorkflowOutput output
    }

    class NetworkExecutionData {
      +string name
      +string status
      +NetworkStep[] steps
      +NetworkUsage usage
      +unknown output
    }

    class WorkflowStepMap {
      <<map>>
      +string key
      +WorkflowStep value
    }

    class WorkflowStep {
      +string status
      +unknown input
      +unknown output
      +unknown suspendPayload
    }

    class NetworkStep {
      +string name
      +string status
      +unknown input
      +unknown output
    }

    class NetworkUsage {
      +number inputTokens
      +number outputTokens
      +number totalTokens
    }

    class MessageItem {
      +UIMessage message
      -MastraDataPart[] dataParts
      +render()
    }

    class AgentDataSection {
      +AgentDataPart part
      +render()
    }

    class WorkflowDataSection {
      +WorkflowDataPart part
      +render()
    }

    class NetworkDataSection {
      +NetworkDataPart part
      +render()
    }

    class AgentTool {
      +string id
      +string type
      +unknown data
      +render()
    }

    class TypeGuards {
      +bool hasStringType(unknown part)
      +bool isAgentDataPart(unknown part)
      +bool isWorkflowDataPart(unknown part)
      +bool isNetworkDataPart(unknown part)
    }

    class KeyHelpers {
      +string getToolCallId(unknown tool, number fallbackIndex)
    }

    UIMessage "1" o-- "*" MastraDataPart
    MastraDataPart <|-- AgentDataPart
    MastraDataPart <|-- WorkflowDataPart
    MastraDataPart <|-- NetworkDataPart

    MessageItem ..> MastraDataPart : filters dataParts
    MessageItem ..> AgentDataPart : uses when isAgentDataPart
    MessageItem ..> WorkflowDataPart : uses when isWorkflowDataPart
    MessageItem ..> NetworkDataPart : uses when isNetworkDataPart

    MessageItem --> AgentDataSection : renders nested agent
    MessageItem --> WorkflowDataSection : renders nested workflow
    MessageItem --> NetworkDataSection : renders nested network
    MessageItem --> AgentTool : renders other data-tool-* parts

    MessageItem ..> TypeGuards
    MessageItem ..> KeyHelpers

    AgentDataSection --> AgentExecutionData
    WorkflowDataSection --> WorkflowExecutionData
    NetworkDataSection --> NetworkExecutionData

    WorkflowExecutionData o-- WorkflowStepMap
    WorkflowStepMap o-- WorkflowStep
    NetworkExecutionData o-- NetworkStep
    NetworkExecutionData o-- NetworkUsage


    style UIMessage stroke:#64b5f6
    style MastraDataPart  stroke:#64b5f6
    style AgentDataPart stroke:#64b5f6
    style WorkflowDataPart stroke:#64b5f6
    style NetworkDataPart stroke:#64b5f6
    style AgentExecutionData stroke:#64b5f6
    style WorkflowExecutionData stroke:#64b5f6
    style NetworkExecutionData stroke:#64b5f6
    style MessageItem stroke:#64b5f6
    style TypeGuards stroke:#64b5f6
    style KeyHelpers stroke:#64b5f6
    style AgentDataSection stroke:#64b5f6
    style WorkflowDataSection stroke:#64b5f6
    style NetworkDataSection stroke:#64b5f6
    style AgentTool stroke:#64b5f6
    style NetworkUsage stroke:#64b5f6
    style NetworkStep stroke:#64b5f6
    style WorkflowStep stroke:#64b5f6
    style WorkflowStepMap stroke:#64b5f6
    style uses when stroke:#64b5f6

🔄 RAG Pipeline (Production-Grade)

%%{init: {'theme': 'dark', 'themeVariables': { 'primaryColor': '#58a6ff', 'primaryTextColor': '#c9d1d9', 'primaryBorderColor': '#30363d', 'lineColor': '#58a6ff', 'sectionBkgColor': '#161b22', 'altSectionBkgColor': '#0d1117', 'sectionTextColor': '#c9d1d9', 'gridColor': '#30363d', 'tertiaryColor': '#161b22' }}}%%
flowchart TB
    subgraph Indexing ["📥 Ingestion Pipeline"]
        A[Documents<br/>PDF/Web/MDX] --> B{MDocument<br/>Chunker}
        B -->|10 Strategies| C[Chunks +<br/>Metadata]
        C --> D[text-embedding-004<br/>3072D Vectors]
        D --> E[(PgVector<br/>HNSW Index)]
    end

    subgraph Querying ["🔍 Retrieval Pipeline"]
        F[User Query] --> G[Query<br/>Embedding]
        G --> H{Vector<br/>Search}
        E -.->|Top-K| H
        H -->|Cosine Similarity| I[Candidates]
        I --> J[Rerank<br/>Cross-Encoder]
        J --> K[GraphRAG<br/>Relations]
        K --> L[Context<br/>Assembly]
    end

    subgraph Generation ["💬 Answer Pipeline"]
        L --> M[Answer Agent<br/>Gemini 2.5 Pro]
        M --> N[Generated<br/>Response]
        N --> O[Citations<br/>Verification]
        O --> P[Sources +<br/>Confidence Score]
    end

    subgraph Observability ["📊 Full Observability"]
        M -.->|Spans| Q[Langfuse<br/>Traces]
        E -.->|Usage| Q
        N -.->|Metrics| R[Custom Scorers<br/>10+ Metrics]
    end

    style A fill:#1a237e,color:#fff
    style B fill:#0d47a1,color:#fff
    style C fill:#1565c0,color:#fff
    style D fill:#1976d2,color:#fff
    style E fill:#2e7d32,color:#fff
    style F fill:#e65100,color:#fff
    style G fill:#ef6c00,color:#fff
    style H fill:#f57c00,color:#fff
    style I fill:#ff8f00,color:#fff
    style J fill:#ffa000,color:#000
    style K fill:#ffb300,color:#000
    style L fill:#4a148c,color:#fff
    style M fill:#6a1b9a,color:#fff
    style N fill:#8e24aa,color:#fff
    style O fill:#ab47bc,color:#fff
    style P fill:#ce93d8,color:#000
    style Q fill:#004d40,color:#fff
    style R fill:#00695c,color:#fff

🤝 Flowcharts

%%{init: {'theme': 'dark', 'themeVariables': { 'primaryColor': '#58a6ff', 'primaryTextColor': '#c9d1d9', 'primaryBorderColor': '#30363d', 'lineColor': '#58a6ff', 'sectionBkgColor': '#161b22', 'altSectionBkgColor': '#0d1117', 'sectionTextColor': '#c9d1d9', 'gridColor': '#30363d', 'tertiaryColor': '#161b22' }}}%%
sequenceDiagram
    actor User as User
    participant Assistant as Assistant_Message
    participant NetworkProvider as NetworkProvider
    participant WorkflowProvider as WorkflowProvider
    participant ProgressPanel as ProgressPanel

    User->>Assistant: Run network or workflow
    Assistant->>NetworkProvider: Stream messages with parts
    Assistant->>WorkflowProvider: Stream messages with parts

    loop For_each_assistant_message_in_network
        NetworkProvider->>NetworkProvider: Iterate parts with index partIndex
        NetworkProvider->>NetworkProvider: Build id using messageId_partType_partIndex
        NetworkProvider->>NetworkProvider: Append ProgressEvent to allProgressEvents
    end

    loop For_each_assistant_message_in_workflow
        WorkflowProvider->>WorkflowProvider: Iterate parts with index partIndex
        WorkflowProvider->>WorkflowProvider: Build id using messageId_partType_partIndex
        WorkflowProvider->>WorkflowProvider: Append ProgressEvent to allProgressEvents
    end

    NetworkProvider->>ProgressPanel: Provide progressEvents for network view
    WorkflowProvider->>ProgressPanel: Provide progressEvents for workflow view
    ProgressPanel->>User: Render grouped progress items with stable IDs

🚀 Quick Start (5 Minutes to Production)

%%{init: {'theme': 'dark', 'themeVariables': { 'primaryColor': '#58a6ff', 'primaryTextColor': '#c9d1d9', 'primaryBorderColor': '#30363d', 'lineColor': '#58a6ff', 'sectionBkgColor': '#161b22', 'altSectionBkgColor': '#0d1117', 'sectionTextColor': '#c9d1d9', 'gridColor': '#30363d', 'tertiaryColor': '#161b22' }}}%%
flowchart LR
    A[1️⃣ Prerequisites] --> B[2️⃣ Clone & Install]
    B --> C[3️⃣ Configure Env]
    C --> D[4️⃣ Run Dev]
    D --> E[5️⃣ Start Building]

    style A fill:#1565c0,color:#fff
    style B fill:#2e7d32,color:#fff
    style C fill:#ef6c00,color:#fff
    style D fill:#6a1b9a,color:#fff
    style E fill:#c62828,color:#fff

1️⃣ Prerequisites

Before you begin, ensure you have:

| Requirement | Version | Purpose | Install | | -------------- | ------- | ------------------- | ----------------------------------------------------------------------------------------------------- | | Node.js | ≥20.9.0 | Runtime | Download | | PostgreSQL | 14+ | Database + PgVector | Docker or Install | | API Keys | - | LLM & Tools | See Configuration below |

One-liner for PostgreSQL with PgVector:

docker run -d --name pgvector -e POSTGRES_PASSWORD=postgres -p 5432:5432 ankane/pgvector

2️⃣ Clone & Install

# Clone the repository
git clone https://github.com/ssdeanx/AgentStack.git
cd AgentStack

# Install dependencies (includes Mastra, Next.js, AI SDK)
npm install

# Verify installation
npm run typecheck  # Should pass with 0 errors

3️⃣ Configure Environment

# Copy the example environment file
cp .env.example .env

# Edit .env and add your API keys
# Minimum required for basic functionality:
# - GOOGLE_GENERATIVE_AI_API_KEY (for Gemini)
# - SUPABASE or DATABASE_URL (for PostgreSQL)

Quick .env setup:

# Required - Get free API keys from Google AI Studio
echo "GOOGLE_GENERATIVE_AI_API_KEY=your-key-here" >> .env

# Required - PostgreSQL connection
echo "SUPABASE=postgresql://postgres:postgres@localhost:5432/mastra" >> .env

# Optional - For enhanced tools
echo "SERPAPI_API_KEY=your-key" >> .env      # Search tools
echo "POLYGON_API_KEY=your-key" >> .env      # Financial data
echo "OPENAI_API_KEY=your-key" >> .env       # Alternative LLM

4️⃣ Start Development Server

# Single command starts both Mastra backend + Next.js frontend
npm run dev

# Services will be available at:
# - Frontend: http://localhost:3000
# - Mastra API: http://localhost:4111
# - MCP Server: http://localhost:6969/mcp (optional)

Expected startup output:

✓ Mastra Dev Server: http://localhost:4111
✓ Next.js Dev Server: http://localhost:3000
✓ 48 agents registered
✓ 60+ tools loaded
✓ 15 workflows ready

5️⃣ Verify & Start Building

Open your browser and navigate to:

| URL | What You'll See | | --------------------------------- | ------------------------------------- | | http://localhost:3000 | Landing page with agent overview | | http://localhost:3000/chat | AI chat interface with 48+ agents | | http://localhost:3000/dashboard | Admin dashboard with traces & metrics | | http://localhost:3000/workflows | Interactive workflow canvas |

Test your setup:

# Run the test suite
npm test

# Should show: ✓ 100+ tests passed (97% coverage)

🎉 You're ready! Check out Development to start building custom tools and agents.

Next.js + Mastra Client SDK

The frontend uses @mastra/client-js with TanStack Query for robust state management:

// lib/mastra-client.ts - Base client configuration
import { MastraClient } from '@mastra/client-js'

export const mastraClient = new MastraClient({
    baseUrl: process.env.NEXT_PUBLIC_MASTRA_API_URL || 'http://localhost:4111',
})

// lib/hooks/use-dashboard-queries.ts - TanStack Query hooks
import { useQuery } from '@tanstack/react-query'
import { mastraClient } from '@/lib/mastra-client'

// Query keys for cache management
export const queryKeys = {
    agents: ['agents'] as const,
    agent: (id: string) => ['agents', id] as const,
    workflows: ['workflows'] as const,
    tools: ['tools'] as const,
    traces: (filters?: Record<string, unknown>) => ['traces', filters] as const,
    threads: (resourceId: string, agentId: string) =>
        ['threads', resourceId, agentId] as const,
    vectors: (vectorName: string) => ['vectors', vectorName] as const,
}

// Type-safe query hooks
export function useAgentsQuery() {
    return useQuery({
        queryKey: queryKeys.agents,
        queryFn: async (): Promise<Agent[]> => {
            const agents = await mastraClient.listAgents()
            return Object.entries(agents).map(([id, agent]) => ({
                id,
                name: agent.name,
                description: agent.description,
                model: agent.model,
            }))
        },
    })
}

// lib/types/mastra-api.ts - Zod schemas for type safety
import { z } from 'zod'

export const AgentSchema = z.object({
    id: z.string(),
    name: z.string().optional(),
    description: z.string().optional(),
    model: z
        .union([
            z.string(),
            z.object({ provider: z.string(), name: z.string() }),
        ])
        .optional(),
    tools: z
        .union([z.array(z.string()), z.record(z.string(), z.unknown())])
        .optional(),
})
export type Agent = z.infer<typeof AgentSchema>

// Available hooks:
// - useAgentsQuery(), useAgentQuery(id)
// - useWorkflowsQuery(), useWorkflowQuery(id)
// - useToolsQuery(), useToolQuery(id)
// - useTracesQuery(params), useTraceQuery(id)
// - useMemoryThreadsQuery(resourceId, agentId)
// - useMemoryMessagesQuery(threadId, agentId)
// - useVectorIndexesQuery(vectorName)
// - useExecuteToolMutation()
// - useCreateThreadMutation()
// - useVectorQueryMutation()

Key Features:

  • Type Safety: All API responses validated with Zod schemas
  • Caching: Centralized query keys for efficient cache management
  • Mutations: useExecuteToolMutation, useCreateThreadMutation, useVectorQueryMutation
  • Real-time: Automatic cache invalidation and refetch on mutations
  • Error Handling: Built-in loading/error states

Usage in client components:

"use client";
import { useAgentsQuery } from "@/lib/hooks/use-dashboard-queries";

export function AgentsList() {
  const { data: agents, isLoading, error } = useAgentsQuery();

  if (isLoading) return <div>Loading agents...</div>;
  if (error) return <div>Error: {error.message}</div>;

  return agents.map(agent => <AgentCard key={agent.id} agent={agent} />);
}

Pages:

  • / - Landing page with agent overview
  • /test - Server action demo (SSR)
  • /chat - AI chat with 48+ agents using AI Elements and @ai-sdk/react
  • /networks - Advanced agent network orchestration with routing
  • /workflows - Interactive workflow canvas with 11+ workflows
  • /dashboard - Admin dashboard with TanStack Query hooks for agents/tools/workflows/traces/memory/vectors
  • /tools - Tool documentation and execution interface
  • /docs - Comprehensive documentation (AI SDK, components, RAG, security, runtime context)
  • /api-reference - OpenAPI schema and API documentation

Shared Libraries:

  • lib/mastra-client.ts - MastraClient configuration for frontend
  • lib/hooks/ - TanStack Query hooks for data fetching (15+ hooks)
    • use-dashboard-queries.ts - Agents, workflows, tools, traces, threads, messages, vectors
    • use-mastra.ts - Generic fetch hook with loading/error states
  • lib/types/ - Zod schemas and TypeScript types
    • mastra-api.ts - Agent, Workflow, Tool, Trace, Message, Vector types
  • lib/utils.ts - Shared utilities (cn, formatDate, etc.)
  • lib/a2a.ts - Agent-to-agent coordination utilities
  • lib/auth.ts - Authentication utilities

MCP Server (A2A)

npm run mcp-server  # http://localhost:6969/mcp

Production

npm run build
npm run start

Performance Metrics

AgentStack is engineered for high-performance production workloads with comprehensive benchmarking and optimization:

System Benchmarks

| Metric | Value | Details | | ------------------------ | ------------ | ----------------------------------- | | Cold Start | < 2s | Agent initialization with 60+ tools | | Memory Usage | ~180MB | Base runtime with loaded agents | | Concurrent Agents | 50+ | Parallel execution via A2A networks | | Vector Search | < 50ms | PgVector HNSW top-k retrieval | | Embedding Generation | ~120ms | text-embedding-004 (3072D) | | RAG End-to-End | < 300ms | Chunk → Embed → Search → Answer | | Test Suite | 97% coverage | 100+ tests, ~45s runtime |

Throughput Metrics

%%{init: {'theme': 'dark', 'themeVariables': { 'primaryColor': '#58a6ff', 'primaryTextColor': '#c9d1d9', 'primaryBorderColor': '#30363d', 'lineColor': '#58a6ff' }}}%%
bar
    title Requests Per Second (RPS) by Endpoint
    y-axis Requests per second
    x-axis Endpoint
    bar [150, 85, 200, 120, 90]
    x-axis ["/chat", "/workflow", "/rag/query", "/tools/execute", "/dashboard/api"]

| Endpoint | RPS | Avg Latency | Use Case | | -------------------- | --- | ----------- | ------------------------ | | /api/chat | 150 | 180ms | AI chat streaming | | /api/workflow | 85 | 420ms | Multi-step workflows | | /api/rag/query | 200 | 95ms | Vector similarity search | | /api/tools/execute | 120 | 250ms | Tool execution | | /api/dashboard/* | 90 | 150ms | Admin metrics |

Observability Performance

# Tracing overhead: < 5% latency increase
# Memory per trace: ~2KB (compressed)
# Trace retention: 30 days default
# Scorer latency: < 20ms per evaluation

Monitoring Dashboard:

  • Real-time latency percentiles (p50, p95, p99)
  • Token usage tracking by agent/model
  • Tool execution heatmaps
  • Error rate trending
  • Custom scorer distributions

Optimization Tips

// Enable connection pooling
export const pgStorage = new PgVectorStorage({
    poolSize: 20, // Default: 10
    maxOverflow: 5,
    connectionTimeout: 5000,
})

// Configure embedding batch size
const batchEmbed = async (texts: string[]) => {
    const batchSize = 32 // Optimal for Gemini embeddings
    const batches = chunk(texts, batchSize)
    return Promise.all(batches.map((b) => embedBatch(b)))
}

// Use HNSW for high-recall RAG
const hnswIndex = await pgVector.createIndex({
    tableName: 'embeddings',
    indexName: 'hnsw_cosine_idx',
    metric: 'cosine',
    method: 'hnsw', // Faster than ivfflat for most workloads
    efConstruction: 128,
    efSearch: 64,
})

📁 Structure

╭─────────────────────────────── AgentStack ───────────────────────────────╮
│ Files: 727 | Size: 8.5MB                                                 │
│ Top Extensions: .tsx (314), .ts (299), .json (59), .md (27), .mdx (16)   │
╰──────────────────────────────────────────────────────────────────────────╯
AgentStack

├──   app/ (298 files, 1.2MB)
│   ├──   about/ (410.0B)
│   │   └── page.tsx
│   ├──   api/ (6 files, 6.6KB)
│   │   ├──   chat/
│   │   │   └── route.ts
│   │   ├──   chat-extra/ (581.0B)
│   │   │   └── route.ts
│   │   ├──   completion/ (449.0B)
│   │   │   └── route.ts
│   │   ├──   contact/ (2.2KB)
│   │   │   └── route.ts
│   │   └──   v0/ (445.0B)
│   │       └── route.ts
│   ├──   api-reference/ (5 files, 38.0KB)
│   │   ├──   agents/ (8.2KB)
│   │   │   └── page.mdx
│   │   ├──   openapi-schema/ (13.6KB)
│   │   │   └── page.mdx
│   │   ├──   tools/ (7.1KB)
│   │   │   └── page.mdx
│   │   ├──   workflows/ (8.8KB)
│   │   │   └── page.mdx
│   │   └── page.tsx
│   ├──   blog/ (4 files, 13.4KB, all .tsx)
│   │   ├──   hello-world-agentstack/ (9.1KB)
│   │   │   └── page.mdx
│   │   ├──   session-summary/ (2.1KB)
│   │   │   └── page.tsx
│   │   └── layout page
│   ├──   careers/ (418.0B)
│   │   └── page.tsx
│   ├──   changelog/ (417.0B)
│   │   └── page.tsx
│   ├──   chat/ (27 files, 175.7KB)
│   │   ├──   components/ (16 files, 93.5KB, all .tsx)
│   │   │   └── agent-artifact         agent-inline-citation  agent-sources          agent-web-preview
│   │   │       agent-chain-of-thought agent-plan             agent-suggestions      chat-header
│   │   │       agent-checkpoint       agent-queue            agent-task             chat-input
│   │   │       agent-confirmation     agent-reasoning        agent-tools            chat-messages
│   │   ├──   config/ (7 files, 50.4KB, all .ts)
│   │   │   └── agents            google-models     ollama-models     openrouter-models
│   │   │       anthropic-models  models            openai-models
│   │   ├──   helpers/ (6.6KB)
│   │   │   └── tool-part-transform.ts
│   │   ├──   providers/ (16.8KB)
│   │   │   └── chat-context.tsx
│   │   └── AGENTS.md page.tsx
│   ├──   components/ (30 files, 218.5KB, all .tsx)
│   │   └── about-content         contact-form          landing-hero          privacy-content
│   │       api-components        docs-layout           landing-stats         sidebar
│   │       api-reference-content docs-nav              landing-testimonials  strip-frontmatter
│   │       blog-data             examples-list         landing-trust         terms-content
│   │       blog-layout           footer                navbar                tools-list
│   │       blog-list             landing-agents        networks-list         workflows-list
│   │       careers-content       landing-cta           page-header
│   │       changelog-list        landing-features      pricing-tiers
│   ├──   contact/ (409.0B)
│   │   └── page.tsx
│   ├──   dashboard/ (44 files, 162.4KB)
│   │   ├──   _components/ (8 files, 26.9KB)
│   │   │   └── data-table.tsx       empty-state.tsx      index.ts             sidebar.tsx
│   │   │       detail-panel.tsx     error-fallback.tsx   loading-skeleton.tsx stat-card.tsx
│   │   ├──   agents/ (9 files, 15.2KB, all .tsx)
│   │   │   ├──   _components/ (6 files, 11.9KB)
│   │   │   │   └── agent-details.tsx   agent-list-item.tsx agent-tools-tab.tsx
│   │   │   │       agent-evals-tab.tsx agent-list.tsx      index.ts
│   │   │   └── error   loading page
│   │   ├──   logs/ (3 files, 11.2KB, all .tsx)
│   │   │   └── error   loading page
│   │   ├──   memory/ (3 files, 17.2KB, all .tsx)
│   │   │   └── error   loading page
│   │   ├──   observability/ (3 files, 18.1KB, all .tsx)
│   │   │   └── error   loading page
│   │   ├──   telemetry/ (3 files, 11.1KB, all .tsx)
│   │   │   └── error   loading page
│   │   ├──   tools/ (3 files, 11.1KB, all .tsx)
│   │   │   └── error   loading page
│   │   ├──   vectors/ (3 files, 15.0KB, all .tsx)
│   │   │   └── error   loading page
│   │   ├──   workflows/ (3 files, 14.1KB, all .tsx)
│   │   │   └── error   loading page
│   │   └── AGENTS.md     error.tsx     layout.tsx    loading.tsx   page.tsx      providers.tsx
│   ├──   docs/ (13 files, 90.5KB, all .tsx)
│   │   ├──   ai-sdk/ (13.5KB)
│   │   │   └── page.mdx
│   │   ├──   components/ (8.1KB)
│   │   │   └── page.mdx
│   │   ├──   configuration/ (8.6KB)
│   │   │   └── page.mdx
│   │   ├──   core-concepts/ (7.6KB)
│   │   │   └── page.mdx
│   │   ├──   getting-started/ (2 files, 7.5KB)
│   │   │   └── 1.tsx    page.mdx
│   │   ├──   prompts/kiro-lite/ (9.8KB)
│   │   │   └── page.mdx
│   │   ├──   rag/ (8.3KB)
│   │   │   └── page.mdx
│   │   ├──   runtime-context/ (9.9KB)
│   │   │   └── page.mdx
│   │   ├──   security/ (9.1KB)
│   │   │   └── page.mdx
│   │   ├──   ui/ (6.8KB)
│   │   │   └── page.mdx
│   │   └── layout page
│   ├──   examples/ (413.0B)
│   │   └── page.tsx
│   ├──   login/ (6.4KB)
│   │   └── page.tsx
│   ├──   networks/ (11 files, 82.1KB)
│   │   ├──   components/ (7 files, 63.8KB, all .tsx)
│   │   │   └── network-agents        network-header        network-input         network-routing-panel
│   │   │       network-chat          network-info-panel    network-messages
│   │   ├──   config/ (4.4KB)
│   │   │   └── networks.ts
│   │   ├──   providers/ (9.2KB)
│   │   │   └── network-context.tsx
│   │   └── AGENTS.md page.tsx
│   ├──   pricing/ (412.0B)
│   │   └── page.tsx
│   ├──   privacy/ (418.0B)
│   │   └── page.tsx
│   ├──   terms/ (410.0B)
│   │   └── page.tsx
│   ├──   test/ (7 files, 4.1KB)
│   │   └── AGENTS.md      chat-extra.tsx completion.tsx page.tsx
│   │       action.ts      chat.tsx       form.tsx
│   ├──   tools/ (401.0B)
│   │   └── page.tsx
│   ├──   workflows/ (12 files, 60.7KB)
│   │   ├──   components/ (8 files, 28.8KB, all .tsx)
│   │   │   └── workflow-actions     workflow-header      workflow-input-panel workflow-node
│   │   │       workflow-canvas      workflow-info-panel  workflow-legend      workflow-output
│   │   ├──   config/ (13.0KB)
│   │   │   └── workflows.ts
│   │   ├──   providers/ (10.8KB)
│   │   │   └── workflow-context.tsx
│   │   └── AGENTS.md page.tsx
│   └── AGENTS.md   globals.css layout.tsx  page.tsx
├──   docs/ (12 files, 339.7KB)
│   ├──   adr/ (1.6KB)
│   │   └── 0001-why-pgvector-and-gemini-embeddings.md
│   ├──   components/ (5 files, 36.5KB, all .md)
│   │   └── app-chat-documentation      app-networks-documentation  lib-documentation
│   │       app-dashboard-documentation app-workflows-documentation
│   └── ai-elements_aisk-urls.md                   kiro-lite.prompt.md
│       api-small.md                               runtimeContext.md
│       ⭐️ api.md
├──   hooks/ (7 files, 6.2KB, all .ts)
│   └── index             use-debounce      use-local-storage use-media-query   use-mounted       use-utils
├──   lib/ (13 files, 45.6KB, all .ts)
│   ├──   hooks/ (2 files, 24.2KB, all .ts)
│   │   └── use-dashboard-queries use-mastra
│   ├──   types/ (5.4KB)
│   │   └── mastra-api.ts
│   └── auth                    client-stream-to-ai-sdk mastra-client           utils
├──   src/ (346 files, 3.2MB)
│   ├──   components/ai-elements/ (51 files, 210.5KB, all .tsx)
│   │   └── artifact         confirmation     edge             model-selector   prompt-input     suggestion
│   │       canvas           connection       image            node             queue            task
│   │       chain-of-thought context          inline-citation  open-in-chat     reasoning        tool
│   │       checkpoint       controls         loader           panel            shimmer          toolbar
│   │       code-block       conversation     message          plan             sources          web-preview
│   └──   mastra/ (176 files, 2.5MB)
│       ├──   a2a/ (3 files, 13.4KB)
│       │   └── AGENTS.md               a2aCoordinatorAgent.ts  codingA2ACoordinator.ts
│       ├──   agents/ (39 files, 242.5KB)
│       │   └── AGENTS.md                          excalidraw_validator.ts
│       │       acpAgent.ts                        for await (const part of result.md
│       │       businessLegalAgents.ts             image.ts
│       │       calendarAgent.ts                   image_to_csv.ts
│       │       codingAgents.ts                    knowledgeIndexingAgent.ts
│       │       contentStrategistAgent.ts          learningExtractionAgent.ts
│       │       copywriterAgent.ts                 package-publisher.ts
│       │       csv_to_excalidraw.ts               recharts.ts
│       │       dane.ts                            reportAgent.ts
│       │       dataExportAgent.ts                 researchAgent.ts
│       │       dataIngestionAgent.ts              researchPaperAgent.ts
│       │       dataTransformationAgent.ts         scriptWriterAgent.ts
│       │       documentProcessingAgent.ts         sql.ts
│       │       editorAgent.ts                     stockAnalysisAgent.ts
│       │       evaluationAgent.ts                 weather-agent.ts
│       ├──   config/ (29 files, 252.4KB)
│       │   ├──   vector/ (11 files, 108.0KB)
│       │   │   └── AGENTS.md     chroma.ts     couchbase.ts  opensearch.ts qdrant.ts     s3vectors.ts
│       │   │       astra.ts      cloudflare.ts lance.ts      pinecone.ts   registry.ts
│       │   └── AGENTS.md         gemini-cli.ts     mongodb.ts        processors.ts     upstashMemory.ts
│       │       README.md         google.ts         openai.ts         role-hierarchy.ts vertex.ts
│       │       anthropic.ts      index.ts          openrouter.ts     tracing.ts
│       │       copilot.ts        logger.ts         pg-storage.ts     upstash.ts
│       ├──   data/ (10 files, 1020.7KB)
│       │   └── AGENTS.md                      diamond.excalidraw             sample_dataset.csv
│       │       circle.excalidraw              example-text-arrows.excalidraw ⭐️ test.excalidraw
│       │       diagram (5).json               pencil.excalidraw
│       │       diagram.excalidraw             relationship.excalidraw
│       ├──   experiments/ (8.6KB)
│       │   └── agent-experiments.ts
│       ├──   mcp/ (6 files, 34.6KB)
│       │   └── AGENTS.md     index.ts      mcp-client.ts prompts.ts    resources.ts  server.ts
│       ├──   networks/ (12 files, 32.6KB)
│       │   └── AGENTS.md                  dataPipelineNetwork.ts     reportGenerationNetwork.ts
│       │       codingTeamNetwork.ts       index.ts                   researchPipelineNetwork.ts
│       ├──   policy/ (2 files, 7.0KB)
│       │   └── AGENTS.md acl.yaml
│       ├──   scorers/ (11 files, 52.3KB)
│       │   └── AGENTS.md                  financial-scorers.ts       structure.scorer.ts
│       │       csv-validity.scorer.ts     index.ts                   tone-consistency.scorer.ts
│       │       custom-scorers.ts          script-scorers.ts          weather-scorer.ts
│       │       factuality.scorer.ts       sql-validity.scorer.ts
│       ├──   tools/ (58 files, 753.7KB)
│       │   ├──   tests/ (15 files, 145.8KB, all .ts)
│       │   │   └── copywriter-agent-tool.test       json-to-csv.tool.test
│       │   │       csv-to-json.tool.test            serpapi-academic-local.tool.test
│       │   │       data-file-manager.test           serpapi-news-trends.tool.test
│       │   │       data-validator.tool.test         serpapi-search.tool.test
│       │   │       document-chunking.tool.test      serpapi-shopping.tool.test
│       │   │       editor-agent-tool.test           weather-tool.test
│       │   │       evaluateResultTool.test          web-scraper-tool.test
│       │   │       extractLearningsTool.test
│       │   └── AGENTS.md                      document-chunking.tool.ts      pdf-data-conversion.tool.ts
│       │       AGENTS.md.bak                  editor-agent-tool.ts           pdf.ts
│       │       alpha-vantage.tool.ts          evaluateResultTool.ts          pg-sql-tool.ts
│       │       arxiv.tool.ts                  execa-tool.ts                  pnpm-tool.ts
│       │       browser-tool.ts                extractLearningsTool.ts        polygon-tools.ts
│       │       calendar-tool.ts               financial-chart-tools.ts       semantic-utils.ts
│       │       code-analysis.tool.ts          find-references.tool.ts        serpapi-academic-local.tool.ts
│       │       code-chunking.ts               find-symbol.tool.ts            serpapi-config.ts
│       │       code-search.tool.ts            finnhub-tools.ts               serpapi-news-trends.tool.ts
│       │       copywriter-agent-tool.ts       fs.ts                          serpapi-search.tool.ts
│       │       csv-to-json.tool.ts            github.ts                      serpapi-shopping.tool.ts
│       │       data-file-manager.ts           index.ts                       test-generator.tool.ts
│       │       data-processing-tools.ts       json-to-csv.tool.ts            weather-tool.ts
│       │       data-validator.tool.ts         jwt-auth.tool.ts               ⭐️ web-scraper-tool.ts
│       │       diff-review.tool.ts            multi-string-edit.tool.ts      write-note.ts
│       ├──   types/ (2 files, 1.2KB, all .ts)
│       │   └── excalidraw-to-svg.d svgjson.d
│       ├──   workflows/ (21 files, 210.8KB)
│       │   └── AGENTS.md                       financial-report-workflow.ts    spec-generation-workflow.ts
│       │       changelog.ts                    learning-extraction-workflow.ts stock-analysis-workflow.ts
│       │       content-review-workflow.ts      new-contributor.ts              telephone-game.ts
│       │       content-studio-workflow.ts      repo-ingestion-workflow.ts      weather-workflow.ts
│       │       document-processing-workflow.ts research-synthesis-workflow.ts
│       └── AGENTS.md index.ts
├──   tests/ (3 files, 2.5KB, all .ts)
│   ├──   test-results/ (1.0KB)
│   │   └── test-results.json
│   └── api-chat-r.test       docs-hello-world.test
├──   ui/ (63 files, 120.4KB, all .tsx)
│   └── accordion     button        command       input-group   popover       separator     textarea
│       alert         card          dialog        input         progress      sheet         theme-toggle
│       avatar        carousel      dropdown-menu label         radio-group   skeleton      tooltip
│       badge         checkbox      helpers       layout        scroll-area   switch        typography
│       button-group  collapsible   hover-card    link          select        tabs
└── .blackboxrules           components.json          networksCustomToolv1.png prettier.config.js
    .env.example             eslint.config.cjs        networksv1.png           read_pdf_parse.js
    .gitignore               globalSetup.ts           next.config.ts           testSetup.ts
    .markdownlint.json       instrumentation.ts       ⭐️ package-lock.json     tsconfig.json
    AGENTS.md                llms.txt                 package.json             vitest.config.ts
    README.md                mdx-components.tsx       postcss.config.mjs

🛠️ Development

Building with AgentStack is designed to be intuitive and productive. Here's your development workflow:

Creating Custom Tools

// src/mastra/tools/my-tool.ts
import { createTool } from '@mastra/core/tools'
import { z } from 'zod'

export const myCustomTool = createTool({
    id: 'my-custom-tool',
    description: 'What this tool does',
    inputSchema: z.object({
        param: z.string().describe('Parameter description'),
    }),
    outputSchema: z.object({
        result: z.any(),
        error: z.string().optional(),
    }),
    execute: async ({ context }) => {
        // Your logic here
        return { result: 'success' }
    },
})

Tool Development Best Practices:

  • ✅ Always define strict Zod schemas for inputs and outputs
  • ✅ Keep tools stateless and pure (agents handle orchestration)
  • ✅ Include comprehensive error handling with typed returns
  • ✅ Add Vitest tests with mocked external dependencies
  • ✅ Use structured logging for observability

Creating Custom Agents

// src/mastra/agents/my-agent.ts
import { Agent } from '@mastra/core/agent'
import { googleAI } from '../config/google'
import { myCustomTool, pgQueryTool } from '../tools'

export const myAgent = new Agent({
    id: 'my-agent',
    name: 'My Custom Agent',
    description: 'What this agent specializes in',
    instructions: `
    You are an expert in... Use the available tools to...
    Always validate inputs and provide structured outputs.
  `,
    model: googleAI, // or openAI, anthropic, openrouter
    tools: {
        myCustomTool,
        pgQueryTool,
    },
    memory: pgMemory, // Enable conversation memory
})

Agent Development Best Practices:

  • ✅ Write clear, detailed instructions with examples
  • ✅ Compose 3-5 focused tools per agent (avoid tool bloat)
  • ✅ Use memory for conversational agents
  • ✅ Add evaluation scorers for quality monitoring
  • ✅ Document expected inputs/outputs

Development Commands

# Run the full test suite (97% coverage target)
npm test

# Run tests for a specific tool
npx vitest src/mastra/tools/tests/my-tool.test.ts

# Run tests matching a pattern
npx vitest -t "financial"

# Check TypeScript types
npm run typecheck

# Lint and auto-fix issues
npm run lint:fix

# Format code with Prettier
npm run format

# Build for production
npm run build

Testing Strategy

// Example tool test
import { describe, it, expect, vi } from 'vitest'
import { myCustomTool } from '../my-tool'

describe('myCustomTool', () => {
    it('should process valid input correctly', async () => {
        const result = await myCustomTool.execute({
            context: { param: 'test-value' },
            runtimeContext: {} as any,
        })

        expect(result.result).toBeDefined()
        expect(result.error).toBeUndefined()
    })

    it('should handle errors gracefully', async () => {
        const result = await myCustomTool.execute({
            context: { param: '' }, // Invalid input
            runtimeContext: {} as any,
        })

        expect(result.error).toBeDefined()
    })
})

🔧 Configuration

| Env Var | Purpose | Required | | ------------------------------ | ------------------------------------- | ------------- | | SUPABASE | Postgres + PgVector RAG | ✅ | | GOOGLE_GENERATIVE_AI_API_KEY | Gemini LLM/Embeddings | ✅ | | SERPAPI_API_KEY | Search/News/Shopping (10+ tools) | ✅ | | POLYGON_API_KEY | Stock/Crypto quotes/aggs/fundamentals | ✅ | | LANGFUSE_BASE_URL | Langfuse tracing | Observability |

Full: .env.example + src/mastra/config/AGENTS.md

🧪 Testing Strategy (97% Coverage)

AgentStack maintains rigorous testing standards with 97% code coverage across 100+ tests, ensuring production reliability and safe deployments.

Test Commands

# Run complete test suite
npm test

# Generate coverage report
npm run coverage

# Run specific test files
npx vitest src/mastra/tools/tests/polygon-tools.test.ts

# Filter tests by pattern
npx vitest -t "financial"

# Watch mode for development
npx vitest --watch

Testing Philosophy

┌─────────────────────────────────────────────────────────┐
│  Every Tool → Unit Test + Integration Test + Mock      │
│  Every Agent → Evaluation Scorer + Behavior Test       │
│  Every Workflow → E2E Test + Step Validation           │
│  Every API → Contract Test + Response Validation       │
└─────────────────────────────────────────────────────────┘

Test Categories

| Type | Coverage | Tools | Purpose | | --------------------- | -------- | -------------- | ------------------------------- | | Unit Tests | 97% | Vitest | Tool/agent logic in isolation | | Integration Tests | 85% | Vitest + MSW | API interactions, DB operations | | E2E Tests | 60% | Playwright | User flows, critical paths | | Eval Tests | 100% | Custom Scorers | Agent quality metrics |

Mock Strategy

All external API calls are fully mocked for reliable, fast tests:

// Example: Polygon API mock
vi.mock('../config/polygon', () => ({
    polygonClient: {
        aggregates: vi.fn().mockResolvedValue({
            results: [{ c: 150.25, h: 152.0, l: 149.5, v: 1000000 }],
        }),
    },
}))

// Example: Database mock
vi.mock('../config/pg-storage', () => ({
    pgQueryTool: {
        execute: vi.fn().mockResolvedValue({
            data: [{ id: 1, result: 'success' }],
            error: null,
        }),
    },
}))

Writing Tests

// src/mastra/tools/tests/my-tool.test.ts
import { describe, it, expect, vi } from 'vitest'
import { myTool } from '../my-tool'

describe('myTool', () => {
    beforeEach(() => {
        vi.clearAllMocks()
    })

    describe('execute', () => {
        it('returns success for valid input', async () => {
            const result = await myTool.execute({
                context: { param: 'valid-value' },
                runtimeContext: {} as any,
            })

            expect(result.data).toBeDefined()
            expect(result.error).toBeNull()
        })

        it('handles validation errors', async () => {
            const result = await myTool.execute({
                context: { param: '' }, // Invalid
                runtimeContext: {} as any,
            })

            expect(result.data).toBeNull()
            expect(result.error).toContain('validation')
        })

        it('handles external API failures', async () => {
            // Setup mock to throw
            vi.mocked(externalApi).mockRejectedValue(new Error('Network error'))

            const result = await myTool.execute({
                context: { param: 'test' },
                runtimeContext: {} as any,
            })

            expect(result.error).toContain('Network error')
        })
    })
})

🔒 Security & Governance

AgentStack implements enterprise-grade security controls for production deployments, protecting against common vulnerabilities and ensuring data privacy.

Security Layers

┌─────────────────────────────────────────────────────────────┐
│                    Security Architecture                     │
├─────────────────────────────────────────────────────────────┤
│  🔐 Authentication    │  JWT tokens + Role-based access      │
│  🛡️ Authorization     │  RBAC with policy definitions        │
│  🔍 Input Validation  │  Zod schemas for all inputs          │
│  🧹 Output Sanitizing │  HTML/JS sanitization                │
│  🔒 Secrets Handling  │  Automatic masking in logs/traces    │
│  📁 File Security     │  Path traversal prevention           │
└─────────────────────────────────────────────────────────────┘

Key Security Features

| Feature | Implementation | Protection | | ---------------------------- | ---------------------------- | --------------------------------------- | | JWT Authentication | jwt-auth.tool.ts | Secure API access with token validation | | Role-Based Access | src/mastra/policy/acl.yaml | Granular permissions per user/agent | | Path Validation | validateDataPath() | Prevents directory traversal attacks | | HTML Sanitization | JSDOM + Cheerio | Removes scripts/malicious content | | Secrets Masking | maskSensitiveMessageData() | Hides API keys in logs and traces | | Rate Limiting | Built-in throttling | Prevents API abuse and cost overruns | | SQL Injection Prevention | Parameterized queries | Safe database operations |

Security Best Practices

// Always validate file paths
import { validateDataPath } from '../config/utils'

export const fileTool = createTool({
    inputSchema: z.object({
        path: z.string(),
    }),
    execute: async ({ context }) => {
        // Validates and sanitizes the path
        const safePath = validateDataPath(context.path)
        if (!safePath) {
            return { error: 'Invalid path' }
        }
        // Proceed with safePath...
    },
})

// Mask sensitive data in logs
import { maskSensitiveMessageData } from '../config/pg-storage'

logger.info('Processing request', {
    data: maskSensitiveMessageData(requestData),
})

Compliance Ready

  • GDPR: Data anonymization and retention controls
  • SOC 2: Audit trails and access logging
  • ISO 27001: Security controls documentation
  • HIPAA: PHI handling capabilities (with configuration)

📊 Observability (Production-Ready)

Langfuse Exporters:
├── Traces: 100% (spans/tools/agents)
├── Scorers: 10+ (diversity/quality/task-completion)
├── Metrics: Latency/errors/tool-calls
└── Sampling: Always-on + ratio (30-80%)

Custom Scorers: Source diversity, completeness, creativity, response quality.

Dashboard Architecture

The admin dashboard provides comprehensive observability and management:

Routes:

  • /dashboard - Overview with stat cards (agents, workflows, tools, recent activity)
  • /dashboard/agents - Agent management (list, details, tools, evals)
  • /dashboard/workflows - Workflow monitoring and execution history
  • /dashboard/tools - Tool catalog and usage analytics
  • /dashboard/observability - Traces, spans, and performance metrics
  • /dashboard/memory - Memory threads, messages, and working memory
  • /dashboard/vectors - Vector indexes and similarity search
  • /dashboard/logs - System logs with transport filtering
  • /dashboard/telemetry - Performance telemetry and metrics

Components:

// Shared components (_components/)
;-data -
    table.tsx - // Reusable TanStack Table with sorting/filtering
    detail -
    panel.tsx - // Slide-over panel for item details
    empty -
    state.tsx - // Consistent empty states
    error -
    fallback.tsx - // Error boundary with retry
    loading -
    skeleton.tsx - // Skeleton loaders
    sidebar.tsx - // Navigation sidebar
    stat -
    card.tsx - // Metric display cards
    // Agent-specific (agents/_components/)
    agent -
    list.tsx - // Filterable agent list
    agent -
    list -
    item.tsx - // Individual agent card
    agent -
    details.tsx - // Agent configuration details
    agent -
    tab.tsx - // Agent overview tab
    agent -
    tools -
    tab.tsx - // Agent tools tab
    agent -
    evals -
    tab.tsx // Agent evaluations tab

Data Fetching:

All dashboard pages use TanStack Query hooks from lib/hooks/use-dashboard-queries.ts:

import {
    useAgentsQuery,
    useToolsQuery,
    useTracesQuery,
} from '@/lib/hooks/use-dashboard-queries'

function AgentsPage() {
    const { data: agents, isLoading } = useAgentsQuery()
    const { data: tools } = useToolsQuery()

    // Automatic caching, refetching, and error handling
}

🌐 Integrations Matrix

| Category | Tools | Agents | Frontend | | -------------------- | ------------------------------------------------------ | ----------------------------------------- | --------------------------------------- | | 🔍 Search | SerpAPI (News/Trends/Shopping/Scholar/Local/Yelp) | ResearchAgent | Chat interface with citations | | 💰 Financial | Polygon (10+), Finnhub (6+), AlphaVantage (indicators) | StockAnalysis, CryptoAnalysis | Dashboard with charts and metrics | | 📄 RAG | PgVector chunk/rerank/query/graph | Retrieve/Rerank/Answerer | Vector search interface | | 📝 Content | PDF→MD, Web Scraper, Copywriter/Editor | CopywriterAgent, EditorAgent, ReportAgent | Chat with artifact preview | | 🎨 Visual | CSV↔Excalidraw, SVG/XML process | csvToExcalidrawAgent, imageToCsvAgent | Workflow canvas visualization | | 🌐 Orchestration | A2A MCP Server | a2aCoordinatorAgent, codingA2ACoordinator | Network routing panel | | 💻 UI | AI Elements (30), shadcn/ui (35), Radix primitives | Chat/Reasoning/Canvas interfaces | 65 components across 10+ app routes | | 📊 Observability | Langfuse traces, Custom scorers | All agents instrumented | Dashboard with traces/logs/telemetry | | 🔄 State Mgmt | TanStack Query | Memory threads, working memory | 15+ hooks with caching and invalidation |

🤝 Advanced Usage

💬 Chat Interface

The chat interface (/chat) provides a production-ready AI chat experience with 48+ specialized agents:

AI Elements Components (16 integrated):

  • AgentArtifact - Code/document artifacts with preview
  • AgentChainOfThought - Step-by-step reasoning display
  • AgentCheckpoint - Progress checkpoints
  • AgentConfirmation - User confirmations
  • AgentInlineCitation - Source citations
  • AgentPlan - Multi-step plans
  • AgentQueue - Task queues
  • AgentReasoning - Reasoning traces
  • AgentSources - Source documents
  • AgentSuggestions - Follow-up suggestions
  • AgentTask - Individual tasks
  • AgentTools - Tool usage display
  • AgentWebPreview - Web preview iframe

Agent Categories (48+ total):

  • Research (5): researchAgent, researchPaperAgent, knowledgeIndexingAgent, learningExtractionAgent, dane
  • Content (5): copywriterAgent, editorAgent, contentStrategistAgent, scriptWriterAgent, reportAgent
  • Financial (6): stockAnalysisAgent, chartSupervisorAgent, chartTypeAdvisorAgent, chartDataProcessorAgent, chartGeneratorAgent
  • Data (8): dataIngestionAgent, dataTransformationAgent, dataExportAgent, documentProcessingAgent, csvToExcalidrawAgent, imageToCsvAgent, excalidrawValidatorAgent, imageAgent
  • Coding (9): codeArchitectAgent, codeReviewerAgent, testEngineerAgent, refactoringAgent, daneCommitMessage, daneIssueLabeler, daneLinkChecker, daneChangeLog, danePackagePublisher
  • Business (4): legalResearchAgent, contractAnalysisAgent, complianceMonitoringAgent, businessStrategyAgent

Model Providers (40+ models):

  • Google: 8 models (Gemini 2.5 Flash, Pro, Exp variants)
  • OpenAI: 12 models (GPT-5, GPT-4o, o1, o3-mini)
  • Anthropic: 8 models (Claude 4.5, 4 Sonnet/Opus/Haiku)
  • OpenRouter: 12+ models (Llama, Mistral, Qwen)

🌐 Networks Interface

Advanced agent network orchestration (/networks) with routing and coordination:

13 Pre-configured Networks:

  1. Primary Agent Network (8 agents): General routing to specialized agents
  2. Coding Team Network (4 agents): Architecture → Review → Testing → Refactoring
  3. Data Pipeline Network (3 agents): Ingestion → Transformation → Export
  4. Report Generation Network (3 agents): Research → Analysis → Report
  5. Research Pipeline Network (4 agents): Research → Learning → Knowledge Indexing → Synthesis
  6. Content Creation Network (5 agents): Writing → Editing → Strategy → Scripting
  7. Financial Intelligence Network (7 agents): Stock analysis → Charts → Research → Reporting
  8. Learning Network (5 agents): Learning extraction → Knowledge indexing → Research
  9. Marketing Automation Network (6 agents): Social media → SEO → Content → Translation
  10. DevOps Network (7 agents): Architecture → Testing → Deployment → Monitoring
  11. Business Intelligence Network (7 agents): Data ingestion → Analytics → Visualization
  12. Security Network (4 agents): Code review → Compliance → Vulnerability management

Features:

  • Network Routing Panel: Visualizes agent routing decisions in real-time
  • Parallel Execution: Multiple agents work simultaneously
  • A2A Coordination: Inter-agent communication management

🔄 Workflows Interface

Interactive workflow visualization (/workflows) with AI Elements Canvas:

21 Pre-built Workflows:

  1. Weather Workflow: Fetch weather → Analyze → Suggest activities
  2. Content Studio: Research → Write → Edit → Review
  3. Content Review: Fetch → Analyze → Score → Report
  4. Financial Report: Market data → Analysis → Report generation
  5. Document Processing: Upload → Parse → Chunk → Embed → Index
  6. Research Synthesis: Query → Search → Analyze → Synthesize
  7. Learning Extraction: Read → Extract → Summarize → Store
  8. Governed RAG Index: Validate → Chunk → Embed → Upsert
  9. Governed RAG Answer: Query → Retrieve → Rerank → Answer
  10. Spec Generation: Requirements → Design → Spec → Validation
  11. Stock Analysis: Fetch data → Technical analysis → Report
  12. Repo Ingestion: Repository analysis → Code indexing → Knowledge base
  13. Telephone Game: Interactive user input workflows
  14. Changelog Generation: Git diff analysis → AI changelog creation
  15. Marketing Campaign: End-to-end campaign orchestration
  16. Automated Reporting: Scheduled data gathering → Report generation
  17. Data Analysis: Multi-source data ingestion → Transformation → Insights
  18. Financial Analysis: Deep market analysis → Risk assessment → Strategy
  19. Safe Refactoring: Code analysis → Refactor → Test validation
  20. Test Generation: Code analysis → Unit/Integration test creation
  21. New Contributor: Onboarding → Repo analysis → First task guidance

AI Elements Components (8 for workflows):

  • WorkflowCanvas - Main canvas with pan/zoom
  • WorkflowNode - Individual workflow steps
  • WorkflowEdge - Connections between steps
  • WorkflowPanel - Side panel with details
  • WorkflowControls - Canvas controls
  • WorkflowLegend - Node type legend
  • WorkflowOutput - Execution output display

🚀 Advanced Usage

Custom Agent

// src/mastra/agents/my-agent.ts
import { Agent } from '@mastra/core/agent'
export const myAgent = new Agent({
    id: 'my-agent',
    tools: { polygonStockQuotesTool, pgQueryTool },
    instructions: 'Analyze stocks with Polygon + RAG...',
    model: googleAI, // From model registry
    memory: pgMemory,
})
// Auto-registers in index.ts

MCP/A2A Client

# Start server
npm run mcp-server

# Use in Cursor/Claude
# coordinate_a2a_task({task: "AAPL analysis", agents: ["research", "stock"]})

🤝 Contributing

AgentStack is an open-source project powered by a community of developers, researchers, and AI enthusiasts. We welcome contributions of all kinds—from bug fixes and documentation improvements to new tools, agents, and innovative features.

Why Contribute?

  • 🚀 Shape the Future: Help define the standard for production-grade multi-agent systems
  • 📚 Learn & Grow: Work with cutting-edge AI technologies (Mastra, RAG, A2A orchestration)
  • 🌟 Build Your Portfolio: Contribute to a high-impact, enterprise-ready framework
  • 🤝 Join the Community: Collaborate with passionate developers worldwide

Quick Start for Contributors

# 1. Fork the repository on GitHub
# 2. Clone your fork
git clone https://github.com/YOUR_USERNAME/AgentStack.git
cd AgentStack

# 3. Install dependencies
npm ci

# 4. Verify everything works
npm test  # Should pass with 97%+ coverage

# 5. Create a feature branch
git checkout -b feature/your-awesome-contribution

What to Contribute

| Contribution Type | Examples | Impact | | ----------------- | -------------------------------------------------- | ------------------------------ | | New Tools | Financial APIs, data processors, web scrapers | Expands framework capabilities | | New Agents | Domain-specific specialists (legal, medical, etc.) | Enhances AI workforce | | Bug Fixes | Type errors, edge cases, performance issues | Improves reliability | | Documentation | README updates, code comments, tutorials | Helps other developers | | Tests | Increase coverage, add integration tests | Ensures quality | | UI Components | New AI Elements, dashboard features | Improves UX | | Workflows | Multi-step automation patterns | Demonstrates best practices |

Contribution Workflow

%%{init: {'theme': 'dark', 'themeVariables': { 'primaryColor': '#58a6ff', 'primaryTextColor': '#c9d1d9', 'primaryBorderColor': '#30363d', 'lineColor': '#58a6ff', 'sectionBkgColor': '#161b22', 'altSectionBkgColor': '#0d1117', 'sectionTextColor': '#c9d1d9', 'gridColor': '#30363d', 'tertiaryColor': '#161b22' }}}%%
flowchart LR
    A[🍴 Fork] --> B[💻 Code]
    B --> C[🧪 Test]
    C --> D[📤 PR]
    D --> E[✅ Review]
    E --> F[🎉 Merge]

    style A fill:#1565c0,color:#fff
    style B fill:#2e7d32,color:#fff
    style C fill:#ef6c00,color:#fff
    style D fill:#6a1b9a,color:#fff
    style E fill:#00695c,color:#fff
    style F fill:#c62828,color:#fff

Development Standards

Code Quality Checklist

Before submitting your PR, ensure:

  • [ ] Type Safety: All TypeScript compiles with strict mode (npm run typecheck)
  • [ ] Test Coverage: New code has 95%+ coverage (npm test)
  • [ ] Linting: ESLint passes with zero warnings (npm run lint)
  • [ ] Zod Schemas: All tool inputs/outputs use strict validation
  • [ ] Documentation: New features include JSDoc comments
  • [ ] Error Handling: Graceful failures with typed error returns
  • [ ] Observability: Tracing spans for significant operations

Commit Message Convention

We follow Conventional Commits:

<type>(<scope>): <description>

[optional body]

[optional footer(s)]

Examples:

feat(tools): add Alpha Vantage technical indicators

Add support for RSI, MACD, and Bollinger Bands with
comprehensive test coverage and documentation.

Closes #123
docs(readme): update contributing guidelines

Add detailed workflow diagram and code quality checklist
for new contributors.

Pull Request Template

When opening a PR, please include:

## Summary

Brief description of changes

## Type of Change

- [ ] Bug fix
- [ ] New feature
- [ ] Breaking change
- [ ] Documentation update

## Testing

- [ ] Unit tests pass (`npm test`)
- [ ] Type check passes (`npm run typecheck`)
- [ ] Linting passes (`npm run lint`)

## Screenshots (if UI changes)

## Checklist

- [ ] Code follows project style guidelines
- [ ] Self-review completed
- [ ] Documentation updated
- [ ] Tests added for new functionality

Getting Help

Code of Conduct

We are committed to providing a welcoming and inclusive experience for everyone:

  • Be respectful and constructive in all interactions
  • Welcome newcomers and help them get started
  • Focus on what is best for the community
  • Show empathy towards others

Report violations to ssdeanx@gmail.com


🎉 Thank you for considering contributing to AgentStack! Every contribution, no matter how small, helps make this project better for everyone.

📚 Resources

Frontend Routes:

  • Chat Interface: AI chat with 48+ agents using AI Elements and @ai-sdk/react
  • Networks: Advanced agent network orchestration with routing panel
  • Workflows: Interactive workflow visualization with AI Elements Canvas
  • Dashboard: Admin dashboard with agents/tools/workflows/traces/memory/vectors
  • Documentation: Comprehensive docs (AI SDK, components, RAG, security)
  • API Reference: OpenAPI schema and API documentation

Shared Libraries:

  • lib/hooks: TanStack Query hooks for data fetching (15+ hooks)
    • use-dashboard-queries.ts - Agents, workflows, tools, traces, threads, messages, vectors
    • use-mastra.ts - Generic fetch hook with loading/error states
  • lib/types: Zod schemas and TypeScript types
    • mastra-api.ts - Agent, Workflow, Tool, Trace, Message, Vector types
  • lib/: Client SDK, utilities, auth, A2A coordination

Core Components:

🏆 Roadmap

  • [x] Financial Suite: Polygon/Finnhub/AlphaVantage (✅ Live - 30+ endpoints)
  • [x] RAG Pipeline: PgVector + rerank/graph (✅ Live)
  • [x] A2A MCP: Parallel orchestration (✅ Live)
  • [x] 15 Workflows: Sequential, parallel, branch, loop, foreach, suspend/resume (✅ Live)
  • [x] 12 Agent Networks: Routing and coordination (✅ Live)
  • [x] 105 UI Components: AI Elements + shadcn/ui (✅ Live)
  • [x] Chat Interface: Full agent chat UI with AI Elements (✅ Live - 48+ agents)
  • [x] Dashboard: Admin dashboard with TanStack Query (✅ Live - 8 routes)
  • [x] MastraClient SDK: Type-safe client with Zod schemas (✅ Live)
  • [x] Marketing Suite: Social media, SEO, translation, customer support (✅ Live)
  • [x] DevOps Suite: CI/CD, testing, deployment, monitoring (✅ Live)
  • [x] Business Intelligence: Data analytics, visualization, reporting (✅ Live)
  • [x] Security Suite: Code review, compliance, vulnerability management (✅ Live)
  • [ ] LangSmith/Phoenix: Enhanced eval dashboards
  • [ ] Docker/Helm: K8s deployment templates
  • [ ] Multi-tenancy: Tenant isolation and resource management

Star ssdeanx/AgentStack 🐦 Follow @ssdeanx 📘 Docs (Coming Q1 2026)

Last updated: 2026-02-16 | v3.4.0

🧠 Chat

%%{init: {'theme': 'dark', 'themeVariables': { 'primaryColor': '#58a6ff', 'primaryTextColor': '#c9d1d9', 'primaryBorderColor': '#30363d', 'lineColor': '#58a6ff', 'sectionBkgColor': '#161b22', 'altSectionBkgColor': '#0d1117', 'sectionTextColor': '#c9d1d9', 'gridColor': '#30363d', 'tertiaryColor': '#161b22' }}}%%
classDiagram
  direction LR

  class AgentPlanData {
    +string title
    +string description
    +PlanStep[] steps
    +bool isStreaming
    +number currentStep
  }

  class PlanStep {
    +string text
    +bool completed
  }

  class AgentTaskData {
    +string title
    +TaskStep[] steps
  }

  class TaskStep {
    +string id
    +string text
    +TaskStepStatus status
    +string file_name
    +string file_icon
  }

  class TaskStepStatus {
    <<enumeration>>
    pending
    running
    completed
    error
  }

  class ArtifactData {
    +string id
    +string title
    +string description
    +string type
    +string language
    +string content
  }

  class Citation {
    +string id
    +string number
    +string title
    +string url
    +string description
    +string quote
  }

  class QueuedTask {
    +string id
    +string title
    +string description
    +string status
    +Date createdAt
    +Date completedAt
    +string error
  }

  class WebPreviewData {
    +string id
    +string url
    +string title
    +string code
    +string language
    +string html
    +bool editable
    +bool showConsole
    +number height
  }

  class ReasoningStep {
    +string id
    +string label
    +string description
    +string status
    +string[] searchResults
    +number duration
  }

  class AgentSuggestionsProps {
    +string[] suggestions
    +onSelect(suggestion)
    +bool disabled
    +string className
  }

  class AgentSourcesProps {
    +SourceItem[] sources
    +string className
    +number maxVisible
  }

  class SourceItem {
    +string url
    +string title
  }

  class AgentReasoningProps {
    +string reasoning
    +bool isStreaming
    +number duration
    +string className
  }

  class AgentToolsProps {
    +ToolInvocation[] tools
    +string className
  }

  class ConfirmationSeverity {
    <<enumeration>>
    info
    warning
    danger
  }

  class InlineCitationToken {
    <<union>>
    text
    citation
  }

  class ChatUtils {
    +extractPlanFromText(text) AgentPlanData
    +parseReasoningToSteps(reasoning) ReasoningStep[]
    +tokenizeInlineCitations(content, sources) InlineCitationToken[]
    +getSuggestionsForAgent(agentId) string[]
  }

  class AgentPlan {
    +AgentPlanData plan
    +onExecuteCurrentStep()
    +onCancel()
    +onApprove()
  }

  class AgentTask {
    +AgentTaskData task
  }

  class AgentArtifact {
    +ArtifactData artifact
    +onCodeUpdate(artifactId, newCode)
  }

  class AgentInlineCitation {
    +Citation[] citations
    +string text
  }

  class AgentSuggestions {
    +AgentSuggestionsProps props
  }

  class AgentSources {
    +AgentSourcesProps props
  }

  class AgentReasoning {
    +AgentReasoningProps props
  }

  class AgentTools {
    +AgentToolsProps props
  }

  class AgentQueue {
    +QueuedTask[] tasks
  }

  class AgentWebPreview {
    +WebPreviewData preview
    +onCodeChange(code)
  }

  class AgentCodeSandbox {
    +onCodeChange(code)
  }

  %% Relationships between data types
  AgentPlanData --> "*" PlanStep
  AgentTaskData --> "*" TaskStep
  TaskStep --> TaskStepStatus
  AgentSourcesProps --> "*" SourceItem
  AgentToolsProps --> "*" ToolInvocation

  %% Components depending on shared chat types
  AgentPlan --> AgentPlanData
  AgentTask --> AgentTaskData
  AgentArtifact --> ArtifactData
  AgentInlineCitation --> Citation
  AgentSuggestions --> AgentSuggestionsProps
  AgentSources --> AgentSourcesProps
  AgentReasoning --> AgentReasoningProps
  AgentTools --> AgentToolsProps
  AgentQueue --> QueuedTask
  AgentWebPreview --> WebPreviewData
  AgentCodeSandbox --> WebPreviewData

  %% Utilities using shared types
  ChatUtils --> AgentPlanData
  ChatUtils --> ReasoningStep
  ChatUtils --> InlineCitationToken
  ChatUtils --> AgentSuggestionsProps

Contract & API

Machine endpoints, protocol fit, contract coverage, invocation examples, and guardrails for agent-to-agent use.

MissingGITHUB MCP

Contract coverage

Status

missing

Auth

None

Streaming

No

Data region

Unspecified

Protocol support

MCP: self-declared

Requires: none

Forbidden: none

Guardrails

Operational confidence: low

No positive guardrails captured.
Invocation examples
curl -s "https://xpersona.co/api/v1/agents/mcp-ssdeanx-agentstack/snapshot"
curl -s "https://xpersona.co/api/v1/agents/mcp-ssdeanx-agentstack/contract"
curl -s "https://xpersona.co/api/v1/agents/mcp-ssdeanx-agentstack/trust"

Reliability & Benchmarks

Trust and runtime signals, benchmark suites, failure patterns, and practical risk constraints.

Missingruntime-metrics

Trust signals

Handshake

UNKNOWN

Confidence

unknown

Attempts 30d

unknown

Fallback rate

unknown

Runtime metrics

Observed P50

unknown

Observed P95

unknown

Rate limit

unknown

Estimated cost

unknown

Do not use if

Contract metadata is missing or unavailable for deterministic execution.
No benchmark suites or observed failure patterns are available.

Media & Demo

Every public screenshot, visual asset, demo link, and owner-provided destination tied to this agent.

Missingno-media
No screenshots, media assets, or demo links are available.

Related Agents

Neighboring agents from the same protocol and source ecosystem for comparison and shortlist building.

Self-declaredprotocol-neighbors
GITLAB_AI_CATALOGgitlab-mcp

Rank

83

A Model Context Protocol (MCP) server for GitLab

Traction

No public download signal

Freshness

Updated 2d ago

MCP
GITLAB_PUBLIC_PROJECTSgitlab-mcp

Rank

80

A Model Context Protocol (MCP) server for GitLab

Traction

No public download signal

Freshness

Updated 2d ago

MCP
GITLAB_AI_CATALOGrmcp-openapi

Rank

74

Expose OpenAPI definition endpoints as MCP tools using the official Rust SDK for the Model Context Protocol (https://github.com/modelcontextprotocol/rust-sdk)

Traction

No public download signal

Freshness

Updated 2d ago

MCP
GITLAB_AI_CATALOGrmcp-actix-web

Rank

72

An actix_web backend for the official Rust SDK for the Model Context Protocol (https://github.com/modelcontextprotocol/rust-sdk)

Traction

No public download signal

Freshness

Updated 2d ago

MCP
Machine Appendix

Contract JSON

{
  "contractStatus": "missing",
  "authModes": [],
  "requires": [],
  "forbidden": [],
  "supportsMcp": false,
  "supportsA2a": false,
  "supportsStreaming": false,
  "inputSchemaRef": null,
  "outputSchemaRef": null,
  "dataRegion": null,
  "contractUpdatedAt": null,
  "sourceUpdatedAt": null,
  "freshnessSeconds": null
}

Invocation Guide

{
  "preferredApi": {
    "snapshotUrl": "https://xpersona.co/api/v1/agents/mcp-ssdeanx-agentstack/snapshot",
    "contractUrl": "https://xpersona.co/api/v1/agents/mcp-ssdeanx-agentstack/contract",
    "trustUrl": "https://xpersona.co/api/v1/agents/mcp-ssdeanx-agentstack/trust"
  },
  "curlExamples": [
    "curl -s \"https://xpersona.co/api/v1/agents/mcp-ssdeanx-agentstack/snapshot\"",
    "curl -s \"https://xpersona.co/api/v1/agents/mcp-ssdeanx-agentstack/contract\"",
    "curl -s \"https://xpersona.co/api/v1/agents/mcp-ssdeanx-agentstack/trust\""
  ],
  "jsonRequestTemplate": {
    "query": "summarize this repo",
    "constraints": {
      "maxLatencyMs": 2000,
      "protocolPreference": [
        "MCP"
      ]
    }
  },
  "jsonResponseTemplate": {
    "ok": true,
    "result": {
      "summary": "...",
      "confidence": 0.9
    },
    "meta": {
      "source": "GITHUB_MCP",
      "generatedAt": "2026-04-17T02:59:01.468Z"
    }
  },
  "retryPolicy": {
    "maxAttempts": 3,
    "backoffMs": [
      500,
      1500,
      3500
    ],
    "retryableConditions": [
      "HTTP_429",
      "HTTP_503",
      "NETWORK_TIMEOUT"
    ]
  }
}

Trust JSON

{
  "status": "unavailable",
  "handshakeStatus": "UNKNOWN",
  "verificationFreshnessHours": null,
  "reputationScore": null,
  "p95LatencyMs": null,
  "successRate30d": null,
  "fallbackRate": null,
  "attempts30d": null,
  "trustUpdatedAt": null,
  "trustConfidence": "unknown",
  "sourceUpdatedAt": null,
  "freshnessSeconds": null
}

Capability Matrix

{
  "rows": [
    {
      "key": "MCP",
      "type": "protocol",
      "support": "unknown",
      "confidenceSource": "profile",
      "notes": "Listed on profile"
    },
    {
      "key": "ai",
      "type": "capability",
      "support": "supported",
      "confidenceSource": "profile",
      "notes": "Declared in agent profile metadata"
    },
    {
      "key": "agents",
      "type": "capability",
      "support": "supported",
      "confidenceSource": "profile",
      "notes": "Declared in agent profile metadata"
    },
    {
      "key": "mastra",
      "type": "capability",
      "support": "supported",
      "confidenceSource": "profile",
      "notes": "Declared in agent profile metadata"
    },
    {
      "key": "framework",
      "type": "capability",
      "support": "supported",
      "confidenceSource": "profile",
      "notes": "Declared in agent profile metadata"
    }
  ],
  "flattenedTokens": "protocol:MCP|unknown|profile capability:ai|supported|profile capability:agents|supported|profile capability:mastra|supported|profile capability:framework|supported|profile"
}

Facts JSON

[
  {
    "factKey": "vendor",
    "category": "vendor",
    "label": "Vendor",
    "value": "Deanmachines",
    "href": "https://deanmachines.com",
    "sourceUrl": "https://deanmachines.com",
    "sourceType": "profile",
    "confidence": "medium",
    "observedAt": "2026-02-25T03:18:27.712Z",
    "isPublic": true
  },
  {
    "factKey": "protocols",
    "category": "compatibility",
    "label": "Protocol compatibility",
    "value": "MCP",
    "href": "https://xpersona.co/api/v1/agents/mcp-ssdeanx-agentstack/contract",
    "sourceUrl": "https://xpersona.co/api/v1/agents/mcp-ssdeanx-agentstack/contract",
    "sourceType": "contract",
    "confidence": "medium",
    "observedAt": "2026-02-25T03:18:27.712Z",
    "isPublic": true
  },
  {
    "factKey": "traction",
    "category": "adoption",
    "label": "Adoption signal",
    "value": "17 GitHub stars",
    "href": "https://github.com/ssdeanx/AgentStack",
    "sourceUrl": "https://github.com/ssdeanx/AgentStack",
    "sourceType": "profile",
    "confidence": "medium",
    "observedAt": "2026-02-25T03:18:27.712Z",
    "isPublic": true
  },
  {
    "factKey": "handshake_status",
    "category": "security",
    "label": "Handshake status",
    "value": "UNKNOWN",
    "href": "https://xpersona.co/api/v1/agents/mcp-ssdeanx-agentstack/trust",
    "sourceUrl": "https://xpersona.co/api/v1/agents/mcp-ssdeanx-agentstack/trust",
    "sourceType": "trust",
    "confidence": "medium",
    "observedAt": null,
    "isPublic": true
  }
]

Change Events JSON

[]

Sponsored

Ads related to agentstack and adjacent AI workflows.