Sandbox
@ssdeanx/AgentStack

Mastra multi-agent framework with MCP orchestration

AgentStack packages a production-style multi-agent stack on Mastra. It combines specialized agents, workflows, supervisor networks, MCP/A2A routing, observability, and workspace controls so you can build agent systems with shared tools and governed execution.

44 starsβ€’10 forksβ€’TypeScriptβ€’Updated 4mo ago
Who it's for

Builders who want reusable agent orchestration, tool use, and tracing in one TypeScript codebase.

What it delivers

You can build and run coordinated agent workflows with shared tools, memory, tracing, and guardrails instead of wiring each piece yourself.

What it does

Specialized agents

Defines 25+ agents for tasks like research, stock analysis, writing, and review.

Supervisor networks

Uses coordinator agents to route work to subagents through delegation hooks.

MCP and A2A orchestration

Coordinates agents through MCP tools and A2A communication for multi-agent flows.

RAG pipelines

Includes semantic search, chunking, reranking, and graph-based retrieval for document work.

Observability

Tracks agent runs, tool calls, and workflow steps with tracing and Langfuse-ready hooks.

Workspace and sandbox support

Supports local, AgentFS, and Daytona workspaces with persistence and approval controls.

Rules and agent instructions

Provides repo-level guidance in `AGENTS.md`, `.github/instructions`, `.windsurf/rules`, and related files.

How to get it

  1. 1Run
    # Start server
    npm run mcp-server
    
    # Use in Cursor/Claude
    # coordinate_a2a_task({task: "AAPL analysis", agents: ["research", "stock"]})

README

πŸš€ AgentStack

Configuration

Development

Home Page v1.0.0

Node.js TypeScript Next.js React License

Agents Tools Workflows Networks UI Components

Tests Zod ESLint

GitHub GitMCP wakatime

AgentStack is a production-grade AI agent platform built on Mastra, delivering 57 enterprise tools, 25+ specialized agents, 10+ workflows, 12+ supervisor networks, 105 UI components (50+ AI Elements + 55+ base), and A2A/MCP orchestration for scalable AI systems. Features supervisor networks with delegation hooks, workspace management (AgentFS/Daytona/Local), TanStack Query integration, and LibSQL-backed persistence for agents, workspaces, supervisor networks, and auth. Focuses on financial intelligence, RAG pipelines, enterprise observability, secure governance, and AI chat interfaces.

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

@ai-sdk/google @ai-sdk/react Langfuse libSQL Vector Search

Gemini OpenAI Anthropic

🎯 Why AgentStack?

AgentStack bridges the gap between basic AI chatbots and enterprise-grade multi-agent orchestration. While other AI agent platforms offer simple automation, AgentStack delivers the observability, security, and scalability required for production deployment.

FeatureAgentStackFleece AIBotpressVellum AI
Production Observabilityβœ… Real-time traces via TanStack + Langfuse ready⚠️ Basic⚠️ Basicβœ… Partial
Dataset Managementβœ… Full dataset/eval/experiment API with versioning❌ None❌ None⚠️ Basic
Supervisor Networksβœ… 12+ coordinator agents with delegation hooks❌ None❌ None❌ None
Financial Intelligenceβœ… Polygon/Finnhub/AlphaVantage (30+ endpoints)❌ None❌ None❌ None
RAG Pipelineβœ… LibSQL HNSW + rerank + graphRAG⚠️ Basic⚠️ Basicβœ… External
Multi-Agent Orchestrationβœ… A2A MCP + supervisor networks (25+ agents)βœ… Advancedβœ… Basicβœ… Partial
Live Browser Automationβœ… Local Chrome/CDP browser agent + shared runtime⚠️ Basic⚠️ Partial⚠️ Partial
Workspaces / Sandboxesβœ… AgentFS + Daytona + local sandboxes + persistence⚠️ Basic❌ None⚠️ Partial
Enterprise Securityβœ… Better Auth + RBAC + path traversal protection + HTML sanitization⚠️ Partial⚠️ Partialβœ… Partial
Type Safetyβœ… Zod schemas everywhere (57 tools)⚠️ Limited⚠️ Limitedβœ… Partial
UI Componentsβœ… 105 components (AI Elements + shadcn/ui)βœ… 30+βœ… 50+βœ… 30+
Testingβœ… Vitest + 97% coverage + comprehensive mocks⚠️ Partial⚠️ Partialβœ… Partial

πŸš€ Production-Ready from Day One

While other AI agent platforms offer basic chatbot functionality, AgentStack provides enterprise-grade multi-agent orchestration:

  • Zero-config RAG: LibSQL with 3072D embeddings works out of the box
  • Supervisor Networks: 12+ coordinator agents with delegation hooks and scoring
  • Workspace Management: AgentFS, Daytona, and local sandboxes with LSP support and LibSQL-backed persistence
  • Financial Intelligence: Polygon, Finnhub, AlphaVantage with 30+ endpoints
  • Full Observability: Every agent call, tool execution, and workflow step is traced
  • Enterprise Security: Better Auth, RBAC, path validation, HTML sanitization, LibSQL session storage

✨ Core Capabilities

  • πŸ’° Financial Intelligence: 30+ tools (Polygon quotes/aggs/fundamentals, Finnhub analysis, AlphaVantage indicators)
  • πŸ” Semantic RAG: LibSQL (3072D embeddings) + MDocument chunking + rerank + graph traversal
  • πŸ“Š Dataset Management: Full dataset API with versioning, experiments, and evaluation
  • πŸ€– 25+ Agents: Individual specialized agents (research, stock analysis, copywriting, etc.)
  • πŸ“‹ 10+ Workflows: Multi-step orchestrated processes (weather analysis, content creation, financial reports)
  • 🌐 12+ Supervisor Networks: Coordinator agents that route tasks to specialized agents using delegation hooks (primary router, coding team, financial intelligence, content creation, etc.)
  • 🧭 Live Browser Automation: Shared Chrome/CDP browser runtime for local verification, screenshots, and interaction testing
  • 🧩 Workspaces & Sandboxes: AgentFS, Daytona, and local sandbox support with persistent LibSQL-backed state
  • πŸ”Œ 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)
  • πŸ“Š Enterprise Observability: Default tracing + Langfuse integration + 10+ custom scorers + middleware logging
  • πŸ›‘οΈ Enterprise Security: JWT auth, RBAC, path validation, HTML sanitization, secrets masking, middleware protection
  • ⚑ Extensible: Model registry (Gemini/OpenAI/Anthropic/OpenRouter), Zod schemas everywhere, MastraClient SDK integration

βš›οΈ TanStack Query Integration

Production-grade data fetching with comprehensive React hooks:

// lib/hooks/use-mastra-query.ts - 1590+ lines of typed hooks
import { useAgentsQuery } from '@/lib/hooks/use-mastra-query'

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

    // 15+ specialized hooks for agents, workflows, tools, memory, vectors
    // Automatic caching, background refetching, optimistic updates
    // Type-safe with Zod schemas throughout
}

Key Features:

  • 1590+ Lines: Comprehensive hook coverage for all Mastra APIs
  • Type Safety: Full TypeScript with Zod schema validation
  • Caching: Intelligent cache management with React Query
  • Real-time: Automatic background updates and invalidation
  • DevTools: Integrated with @tanstack/react-query-devtools

πŸ“Š Dataset Management & Evaluation

Complete dataset and evaluation pipeline with versioning and experiments:

// lib/hooks/use-mastra-query.ts - Full dataset API
const { data: datasets } = useDatasets()
const { data: experiments } = useDatasetExperiments(datasetId)

// Dataset operations
const createDataset = useCreateDatasetMutation()
const addItems = useAddDatasetItemsMutation()
const runExperiment = useTriggerDatasetExperimentMutation()

Features:

  • Dataset Versioning: Full history tracking and rollback capabilities
  • Experiment Management: Compare model performance across datasets
  • Evaluation Scorers: Custom scoring functions for quality assessment
  • Batch Operations: Efficient bulk data operations
  • Type Safety: Full TypeScript support with Zod validation

πŸ” Observability & Monitoring

Enterprise-grade observability with easy Langfuse integration:

// src/mastra/index.ts - Default observability setup
observability: new Observability({
  configs: {
    default: {
      sampling: { type: SamplingStrategyType.RATIO, probability: 0.75 },
      spanOutputProcessors: [new SensitiveDataFilter({...})],
      exporters: [new DefaultExporter({...})],
      // Easy Langfuse integration: uncomment and configure
      // exporters: [new LangfuseExporter({...})],
    }
  }
})

Features:

  • Default Tracing: Built-in observability with no setup required
  • Real-time Trace Viewing: View traces in real-time via TanStack Query hooks
  • Langfuse Ready: Drop-in integration for advanced analytics and persistence
  • Custom Scorers: 10+ evaluation metrics for agent performance
  • Sensitive Data Protection: Automatic redaction of credentials
  • Performance Monitoring: Latency, token usage, error tracking

Real-time Trace Monitoring:

// View traces in real-time with TanStack hooks
const { data: traces } = useTraces({ limit: 10 })
const { data: trace } = useTrace(traceId)

// Monitor agent performance metrics
const { data: scores } = useScoresByRun({ runId })

🌐 Middleware & Request Context

AgentStack uses server-side Mastra middleware to populate request context for agents, tools, workflows, and supervisor routes. The frontend does not import these helpers directly.

// src/mastra/index.ts - Middleware configuration
middleware: [
  async (c, next) => {
    const authHeader = c.req.header('Authorization') ?? ''
    const requestContext = c.get('requestContext')

    const authenticatedUser = await getAuthenticatedUser({
      mastra,
      token: authHeader.startsWith('Bearer ')
        ? authHeader.slice('Bearer '.length)
        : '',
      request: c.req.raw,
    })

    if (requestContext?.set) {
      requestContext.set('userId', authenticatedUser?.user.id)
      requestContext.set(
        'role',
        authenticatedUser?.user.role === 'admin' ? 'admin' : 'user'
      )
      requestContext.set('language', 'en')
      requestContext.set('provider-id', 'google')
      requestContext.set(
        'model-id',
        'gemini-3.1-flash-lite-preview'
      )
    }

    await next()
  },
]

How it works:

  • Server-only request context: defined in src/mastra/agents/request-context.ts
  • Auth integration: src/mastra/auth.ts stores Better Auth data in LibSQL
  • Role-based access: role is either admin or user
  • Model overrides: provider-id and model-id can be passed through request context
  • Workspace identity: workspaceId, threadId, and resourceId are reserved for server-side routing and persistence
  • Localization: language and region can still be inferred server-side
  • LibSQL fallback: Turso URLs are optional; if missing, the app falls back to local file:./database.db

πŸ”§ Harness - Multi-Mode Agent Orchestration (Alpha)

Advanced multi-mode agent orchestration with state persistence and workspace management:

// src/mastra/harness.ts - 8 specialized agent modes
export const mainHarness = new Harness({
    id: 'agentstack-harness',
    resourceId: 'agentstack',
    storage: pgStore,
    workspace: mainWorkspace,

    modes: [
        { id: 'plan', name: 'Planner', agent: codeArchitectAgent },
        { id: 'code', name: 'Builder', agent: codeArchitectAgent },
        { id: 'review', name: 'Reviewer', agent: codeReviewerAgent },
        { id: 'test', name: 'Tester', agent: testEngineerAgent },
        { id: 'refactor', name: 'Refactorer', agent: refactoringAgent },
        { id: 'research', name: 'Researcher', agent: researchAgent },
        { id: 'edit', name: 'Editor', agent: editorAgent },
        { id: 'report', name: 'Reporter', agent: reportAgent },
    ],
})

Available Modes:

  • πŸ—οΈ Plan: Architecture and planning (codeArchitectAgent)
  • πŸ’» Code: Implementation and coding (codeArchitectAgent)
  • πŸ” Review: Code review and quality assessment (codeReviewerAgent)
  • πŸ§ͺ Test: Test generation and validation (testEngineerAgent)
  • πŸ”„ Refactor: Code refactoring and optimization (refactoringAgent)
  • πŸ”¬ Research: Research and information gathering (researchAgent)
  • ✏️ Edit: Content editing and refinement (editorAgent)
  • πŸ“Š Report: Report generation and synthesis (reportAgent)

Key Features:

  • State Persistence: Thread management with LibSQL storage
  • Workspace Integration: Full filesystem and sandbox access
  • Mode Switching: Dynamic agent mode transitions
  • Tool Approvals: Security controls for sensitive operations
  • Event Streaming: Real-time progress and result streaming

Usage (Alpha):

// Switch to planning mode
await harness.switchMode('plan')
await harness.execute('Design a new authentication system')

// Switch to implementation mode
await harness.switchMode('code')
await harness.execute('Implement the auth system using JWT')

// Switch to testing mode
await harness.switchMode('test')
await harness.execute('Generate comprehensive tests for auth')

⚠️ Alpha Status: The harness is currently in active development. APIs may change without notice.

πŸ—οΈ Workspace Management

Multi-provider workspace system with LSP support:

// src/mastra/workspaces.ts - 14 workspace variants
export const workspaceVariants = {
    mainWorkspace, // Local filesystem + sandbox
    agentFsWorkspace, // AgentFS integration
    daytonaWorkspace, // Daytona cloud sandboxes
    localReadOnlyWorkspace, // Read-only operations
    localApprovalWorkspace, // Manual approval required
    localLspWorkspace, // TypeScript/ESLint LSP
    // ... 8 more variants
}

Providers:

  • Local: Filesystem and sandbox with process management
  • AgentFS: Distributed filesystem with persistence
  • Daytona: Cloud-based development environments
  • LSP: TypeScript and ESLint language server integration
  • Approval: Security-controlled operations

Features:

  • Process Management: Spawn, kill, and monitor workspace processes
  • LSP Integration: Real-time TypeScript/ESLint diagnostics
  • Security Controls: Path validation and approval workflows
  • Multi-tenant: Isolated workspaces with proper boundaries

🌟 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 libSQL:

// 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 (Supervisor Agents)

Supervisor agents that coordinate multiple specialized agents using delegation hooks:

// Networks are supervisor agents that route tasks to specialized subagents
const result = await agentNetwork.execute({
    query: 'Analyze renewable energy market trends',
    // Uses delegation hooks to route to researchAgent, learningAgent, etc.
})
// β†’ Supervisor agent analyzes request and delegates to appropriate subagents
// β†’ Results synthesized into unified response

Network Architecture:

  • Supervisor Pattern: Networks are supervisor agents, not parallel execution
  • Delegation Hooks: Use onDelegationStart/onDelegationComplete for coordination
  • Scoring System: Custom scorers ensure task completion and synthesis quality
  • Context Preservation: Maintain conversation context across delegations

Pre-configured Networks:

  • Primary Network: Routes to research, stock, weather, content, support agents
  • Coding Team Network: Architecture β†’ Code Review β†’ Testing β†’ Refactoring
  • Financial Intelligence Network: Research β†’ Analysis β†’ Charts β†’ Reports
  • Content Creation Network: Writing β†’ Editing β†’ Strategy β†’ SEO

πŸ“Š 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

// Supervisor network coordinates specialized agents
const report = await financialIntelligenceNetwork.execute({
    symbol: 'TSLA',
    includeTechnicalAnalysis: true,
    includeNewsSentiment: true,
    generateCharts: true,
})
// β†’ Supervisor network delegates to: researchAgent β†’ stockAnalysisAgent β†’ chartGeneratorAgent β†’ reportAgent
// β†’ 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

// Supervisor network coordinates coding team
const result = await codingTeamNetwork.execute({
    task: 'Refactor authentication module',
    code: './src/auth/*',
    requirements: [
        'Improve security',
        'Add rate limiting',
        'Better error handling',
    ],
})
// β†’ Supervisor network delegates: codeArchitectAgent β†’ codeReviewerAgent β†’ testEngineerAgent β†’ refactoringAgent
// β†’ Each agent handles specific aspect using delegation hooks

Features:

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

πŸ“Š Content Creation Studio

// Supervisor network orchestrates content pipeline
const content = await contentCreationNetwork.execute({
    topic: 'Sustainable investing trends',
    formats: ['blog', 'social', 'newsletter'],
    tone: 'professional',
    seoOptimize: true,
})
// β†’ Supervisor network delegates: copywriterAgent β†’ editorAgent β†’ contentStrategistAgent β†’ seoAgent
// β†’ Each agent specializes in different aspect of content creation

Features:

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

πŸ” Research Synthesis Engine

// Supervisor network coordinates research pipeline
const research = await researchPipelineNe

Files in the repo

Repository payloadβ€’48 top-level entries
  • .agent
  • .agents
  • .github
  • .kilocode
  • .sisyphus
  • .storybook
  • .trunk
  • .windsurf
  • app
  • better-auth_migrations
  • conductor
  • convex
  • docs
  • hooks
  • lib
  • memory-bank
  • rule-tests
  • rules
  • src
  • tests
  • types
  • ui
  • utils
  • .env.example
  • .gitignore
  • .markdownlint.json
  • AGENTS.md
  • auth.ts
  • components.json
  • eslint.config.js
  • free-models.md
  • llms.txt
  • mdx-components.tsx
  • next.config.ts
  • package-lock.json
  • package.json
  • page-2026-04-15T07-04-23-082Z.png
  • postcss.config.mjs
  • prettier.config.js
  • README.md
  • robots.txt
  • sgconfig.yml
  • sitemap.xml
  • SKILL.md
  • skills-lock.json
  • tsconfig.cli.json
  • tsconfig.json
  • vitest.config.ts

Discussion (0)

Ask about usage, or say what you built with it

Sign in to join the discussion.

No comments yet. Be the first to say what this is good for.

More frameworks & sdks

HKUDS/nanobotFrameworks & SDKs

Ultra-lightweight, open-source, self-hosted personal AI agent framework in Python with WebUI, tools, memory, MCP, multi-agent workflows, automation, and chat apps

48k
microsoft/
SkillOpt
microsoft/SkillOptFrameworks & SDKs

SkillOpt is a text-space optimizer that trains reusable natural-language skills for frozen LLM agents through trajectory-driven edits, validation-gated updates, and deployable best_skill.md artifacts.

17k
omnigent-ai/omnigentFrameworks & SDKs

Omnigent is an open-source AI agent framework and meta-harness: orchestrate Claude Code, Codex, Cursor, Pi, and custom agents β€” swap harnesses without rewriting, enforce policies and sandboxing, and collaborate in real time from any device.

9.8k
kyegomez/
OpenMythos
kyegomez/OpenMythosFrameworks & SDKs

A theoretical reconstruction of the Claude Mythos architecture, built from first principles using the available research literature.

15k
D4Vinci/ScraplingFrameworks & SDKs

πŸ•·οΈ An adaptive Web Scraping framework that handles everything from a single request to a full-scale crawl!

80k