Token导航 LogoToken导航TokenDH.com
Agent Stack logo
AI代理stdio官方级别未说明来源级核验

Agent Stack

MCP Server

vitest

AgentStack是一个生产级的AI代理平台,提供57种企业工具、25+专业代理、10+工作流和12+监督网络,专注于金融智能、RAG管道和企业可观测性。

工具数

0

提示词数

0

GitHub Stars

32

资源数

0
AI代理TypeScriptClaudeClaudeCursorWindsurf

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

作者 / 组织

ssdeanx

提供方

ssdeanx

最后核验

2026/5/17 20:22

运行时

Node.js

快速接入

先看主来源和安装命令,再打开仓库或文档;下面只保留这个条目的关键接入事实。

命令预览

npx vitest src/mastra/tools/tests/my-tool.test.ts

详细介绍

🚀 AgentStack 的

配置

发展

Home Page v1.0.0

](https://nodejs.org/) ![TypeScript](https://www.typescriptlang.org/) ![Next.js](https://nextjs.org/) ![React](https://react.dev/) ![License](LICENSE)

![Agents](src/mastra/agents) ![Tools](src/mastra/tools) ![Workflows](src/mastra/workflows) ![Networks](src/mastra/networks) ![UI Components](ui/)

![Tests](https://vitest.dev/) ![Zod](https://zod.dev/) ![ESLint](https://eslint.org/)

](https://github.com/ssdeanx/AgentStack) ![GitMCP](https://gitmcp.io/ssdeanx/AgentStack) ![wakatime](https://wakatime.com/badge/user/7a2fb9a0-188b-4568-887f-7645f9249e62/project/e52d02a1-f64a-4f8d-bc13-caaa2dc37461)

AgentStack 的 是一个 生产级AI代理平台 以Mastra为基础,交付 57个企业工具, 25+专业代理商, 10+工作流程, 12+主管网络, 105个UI组件 (50+AI元素+55+基础),以及 A2A/MCP编排 用于可扩展的AI系统。特性 带有委派挂钩的主管网络, 工作空间管理 (代理商/代托纳/当地), TanStack查询集成,以及 LibSQL支持的持久性 用于代理、工作区、主管网络和身份验证。专注于 金融情报, RAG管道, 企业可观察性, 安全治理,以及 AI聊天界面.

![@mastra/core](https://www.npmjs.com/package/@mastra/core) ![libSQL](https://libsql.org/) ![@mastra/rag](https://www.npmjs.com/package/@mastra/rag) ![@mastra/memory](https://www.npmjs.com/package/@mastra/memory) ![@mastra/ai-sdk](https://www.npmjs.com/package/@mastra/ai-sdk)

![@ai-sdk/google](https://www.npmjs.com/package/@ai-sdk/google) ![@ai-sdk/react](https://www.npmjs.com/package/@ai-sdk/react) ![Langfuse](https://langfuse.com/) ![libSQL Vector Search](https://libsql.org/)

![Gemini](https://ai.google.dev/) ![OpenAI](https://openai.com/) ![Anthropic](https://anthropic.com/)

🎯 为什么选择AgentStack?

AgentStack弥合了基本AI聊天机器人和企业级多代理编排之间的差距。虽然其他AI代理平台提供简单的自动化,但AgentStack提供了生产部署所需的可观察性、安全性和可扩展性。

功能代理堆叠羊毛AI植酸酶丝绒AI
生产可观察性通过TanStack+Langfuse进行实时跟踪⚠️ 基础⚠️ 基础✅ 部分
数据集管理完整数据集/评估/实验API(带版本控制)❌ 无❌ 无⚠️ 基础
主管网络12+带委派挂钩的协调员代理❌ 无❌ 无❌ 没有
金融情报Polygon/Finnhub/AlphaVantage(30+端点)❌ 无❌ 无❌ 没有
RAG 流程LibSQL HNSW+重新存储+图形RAG⚠️ 基础⚠️ 基础✅ 外部
多代理编排A2A MCP+监控网络(25+代理)✅ 高级✅ 基础✅ 部分
实时浏览器自动化本地Chrome/CDP浏览器代理+共享运行时⚠️ 基础⚠️ 部分⚠️ 部分
工作区/沙盒AgentFS+代托纳+本地沙盒+持久化⚠️ 基础❌ 无⚠️ 部分
企业安全更好的Auth+RBAC+路径遍历保护+HTML净化⚠️ 部分⚠️ 部分✅ 部分
类型安全Zod模式无处不在(57个工具)⚠️ 有限⚠️ 有限✅ 部分
UI组件105个组件(AI元素+shadcn/ui)✅ 30+✅ 50+✅ 30+
测试Vitest+97%覆盖率+全面模拟⚠️ 部分⚠️ 部分✅ 部分

🚀 从第一天开始生产准备就绪

虽然其他AI代理平台提供基本的聊天机器人功能,但AgentStack提供企业级多代理编排:

  • 零配置RAG:带有3072D嵌入的LibSQL开箱即用
  • 主管网络:12名以上具有代表团挂钩和计分功能的协调员
  • 工作空间管理:支持LSP和LibSQL支持持久性的AgentFS、Daytona和本地沙盒
  • 金融情报:Polygon、Finnhub、AlphaVantage,拥有30多个端点
  • 完全可观察性:跟踪每个代理调用、工具执行和工作流步骤
  • 企业安全:更好的身份验证、RBAC、路径验证、HTML净化、LibSQL会话存储

核心能力

  • 💰 金融情报:30多种工具(多边形报价/标记/基本面、Finnhub分析、AlphaVantage指标)
  • 🔍 语义RAG:LibSQL(3072D嵌入)+MDocument分块+重排序+图遍历
  • 📊 数据集管理:完整的数据集API,包含版本控制、实验和评估
  • 🤖 25+代理:个人专业代理(研究、股票分析、文案撰写等)
  • 📋 10+工作流程:多步骤编排流程(天气分析、内容创建、财务报告)
  • 🌐 12+主管网络:使用委托挂钩将任务路由到专门代理的协调代理(主路由器、编码团队、金融情报、内容创建等)
  • 🧭 实时浏览器自动化:共享Chrome/CDP浏览器运行时,用于本地验证、截图和交互测试
  • 🧩 工作区和沙盒:AgentFS、Daytona和本地沙盒支持,具有持久的LibSQL支持状态
  • 🔌 A2A/MCP:MCP服务器协调并行代理(研究+股票→报告),A2A跨代理通信协调员
  • 🎨 105个UI组件:AI元素(50个聊天/推理/画布组件)+shadcn/ui(55个基本图元)
  • 📊 企业可观察性:默认跟踪+Langfuse集成+10+自定义评分器+中间件日志
  • 🛡️ 企业安全:JWT身份验证、RBAC、路径验证、HTML净化、秘密屏蔽、中间件保护
  • ⚡ 可扩展:模型注册表(Gemini/OpenAI/Anthropic/OpenRouter),Zod模式无处不在,MastraClient SDK集成

⚛️ TanStack查询集成

使用全面的React钩子获取生产级数据:

// 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
}

主要特点:

  • 1590+条线路:全面覆盖所有Mastra API
  • 类型安全:带Zod模式验证的完整TypeScript
  • 缓存:使用React Query进行智能缓存管理
  • 实时:自动背景更新和无效
  • 开发者工具:与@tanstack/react-query开发工具集成

📊 数据集管理与评估

完整的数据集和评估流程,包括版本控制和实验:

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

特征:

  • 数据集版本控制:完整的历史跟踪和回滚功能
  • 实验管理:比较不同数据集的模型性能
  • 评估评分员:用于质量评估的自定义评分功能
  • 批量操作:高效的批量数据操作
  • 类型安全:通过Zod验证完全支持TypeScript

🔍 可观测性和监测

企业级可观察性,易于Langfuse集成:

// 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({...})],
    }
  }
})

特征:

  • 默认跟踪:内置可观察性,无需设置
  • 实时跟踪查看:通过TanStack查询钩子实时查看跟踪
  • 廊坊准备就绪:直接集成高级分析和持久性
  • 自定义评分器:10多个代理绩效评估指标
  • 敏感数据保护:自动编辑凭据
  • 性能监控:延迟、令牌使用、错误跟踪

实时跟踪监控:

// 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 })

🌐 中间件和请求上下文

AgentStack使用服务器端Mastra中间件为代理、工具、工作流和主管路由填充请求上下文。前端不会直接导入这些助手。

// 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()
  },
]

它是如何工作的:

  • 仅服务器请求上下文:定义于 src/mastra/agents/request-context.ts
  • 身份验证集成: src/mastra/auth.ts 在LibSQL中存储更好的身份验证数据
  • 基于角色的访问: role 要么 adminuser
  • 模型覆盖: provider-idmodel-id 可以通过请求上下文传递
  • 工作区标识: workspaceId, threadId,以及 resourceId 保留用于服务器端路由和持久性
  • 本地化:仍然可以在服务器端推断语言和地区
  • LibSQL回退:Turso URL是可选的;如果丢失,应用程序将回退到本地 file:./database.db

🔧 线束-多模式代理编排 (阿尔法)

具有状态持久性和工作区管理的高级多模式代理编排:

// 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 },
    ],
})

可用模式:

  • 🏗️ 计划:架构和规划(codeArchitectAgent)
  • 💻 代码:实现和编码(codeArchitectAgent)
  • 🔍 审查:代码审查和质量评估(codeReviewerAgent)
  • 🧪 测试:测试生成和验证(testEngineerAgent)
  • 🔄 重构:代码重构和优化(reformingAgent)
  • 🔬 研究:研究和信息收集(researchAgent)
  • ✏️ 编辑:内容编辑和优化(editorAgent)
  • 📊 报告:报告生成和合成(reportAgent)

主要特点:

  • 状态持久性:使用LibSQL存储进行线程管理
  • 工作空间集成:完整的文件系统和沙盒访问
  • 模式切换:动态代理模式转换
  • 工具批准:敏感行动的安全控制
  • 事件流:实时进度和结果流

用法(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状态:该线束目前正在积极开发中。API可能会更改,恕不另行通知。

🏗️ 工作空间管理

支持LSP的多提供商工作空间系统:

// 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
}

供应商:

  • 本地:具有进程管理的文件系统和沙盒
  • AgentFS:具有持久性的分布式文件系统
  • 代托纳:基于云的开发环境
  • 语言服务器协议:TypeScript和ESLint语言服务器集成
  • 批准:安保控制行动

特征:

  • 进程管理:生成、终止和监视工作区进程
  • LSP集成:实时TypeScript/ESLint诊断
  • 安全控制:路径验证和审批工作流
  • 多用户:具有适当边界的隔离工作区

🌟 功能亮点

💰 金融智能套件

来自30多个端点的实时市场数据:

// 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

支持的数据提供程序:

  • Polygon.io:实时报价、历史汇总、基本面
  • Finnhub:公司简介、内幕交易、收益惊喜
  • 阿尔法Vantage:技术指标(RSI、MACD、布林带)

🔍 RAG生产管道

使用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

特征:

  • 10分块策略:语义、递归、标记感知
  • 3072D嵌入:双子座嵌入-001
  • 混合搜索:向量相似度+BM25重新排序
  • 图遍历:关系感知上下文扩展

🤖 代理网络(监督代理)

使用委托挂钩协调多个专业代理的主管代理:

// 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

网络架构:

  • 主管模式:网络是监督代理,而不是并行执行
  • 代表团挂钩:使用 onDelegationStart/onDelegationComplete 为了协调
  • 评分系统:自定义评分器确保任务完成和综合质量
  • 上下文保护:保持各代表团之间的对话背景

预配置网络:

  • 主要网络:研究路线、库存、天气、内容、支持代理
  • 编码团队网络:建筑→ 代码审查→ 测试→ 重构
  • 金融情报网:研究→ 分析→ 图表→ 报告
  • 内容创作网络:写作→ 编辑→ 策略→ SEO

📊 完全可观察性

与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)

仪表板视图:

  • 实时跟踪可视化
  • 性能指标(延迟、错误率)
  • 按代理/工作流进行成本跟踪
  • 自定义评分分析

🎨 AI元素UI库

50+生产就绪的React组件:

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

// Render streaming AI responses

// Display code artifacts with syntax highlighting

// Show source citations

🚀 你能建造什么

由AgentStack支持的现实世界应用程序:

📈 财务分析平台

// 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

特征:

  • 来自多个提供商的实时市场数据
  • 自动技术分析(RSI、MACD、布林带)
  • 基于SerpAPI的新闻情绪分析
  • 交互式图表生成
  • 带源引用的PDF报告导出

📚 企业知识库

// 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

特征:

  • 使用递归爬行进行Web抓取
  • PDF/CSV/JSON文档处理
  • 语义组块的10种策略
  • 混合搜索(矢量+关键字)
  • 每个答案的来源归因

🤖 AI编程助手

// 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

特征:

  • 多代理代码审查管道
  • 自动测试生成
  • 安全漏洞检测
  • Types/React专业知识
  • GitHub集成用于PR自动化

📊 内容创作工作室

// 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

特征:

  • 多格式内容生成
  • 搜索引擎优化与关键字研究
  • 色调和风格的一致性
  • 社交媒体后一代
  • 编辑日历集成

🔍 研究合成发动机

// Supervisor network coordinates research pipeline
const research = await researchPipelineNetwork.execute({
    query: 'Latest advances in LLM safety',
    sources: ['arxiv', 'serpapi', 'web'],
    synthesizeFindings: true,
    generateReport: true,
})
// → Supervisor network delegates: researchAgent → documentProcessingAgent → knowledgeIndexingAgent → reportAgent
// → Research → Process → Index → Synthesize results

特征:

  • ArXiv论文分析
  • 带有内容提取的网络抓取
  • 引文跟踪和验证
  • 跨来源的共识检测
  • 自动生成报告

🏗️ 系统架构

%%{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
• 50 Chat/Reasoning/Canvas Components
• Real-time Streaming]
        Base[shadcn/ui Foundation
• 55 Base Primitives
• Accessible & Themable]
        App[Next.js 16 App Router
• React 19 + Server Components
• Tailwind CSS 4 + oklch]
        Query[TanStack Query
• 1590+ Lines of Hooks
• Type-Safe Data Fetching]
    end

    subgraph "🌐 External Interfaces"
        direction LR
        Client[MCP Clients
Cursor / Claude / Windsurf]
        API[REST API
OpenAPI + Typed SDK]
        SDK[MastraClient SDK
Supervisor Agent Integration]
    end

    subgraph "⚡ AgentStack Runtime"
        direction TB
        Coord[A2A Coordinator
Parallel Agent Orchestration]
        Supervisor[Supervisor Agents
• Scoring & Delegation
• Context-Aware Prompts]

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

        subgraph "Tool Ecosystem"
            Tools[57 Enterprise Tools]
            APIs[Financial APIs
Polygon / Finnhub / AlphaVantage]
            Search[Search & Research
SerpAPI / ArXiv / Web Scraping]
            RAG[RAG Pipeline
LibSQL + Embeddings]
        end

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

        subgraph "Workspace Management"
            Workspaces[14 Workspace Variants
• AgentFS • Daytona • Local]
            LSP[LSP Integration
TypeScript • ESLint]
            Security[Security Controls
Approval • Path Validation]
        end

        subgraph "Supervisor Networks"
            Networks[12+ Supervisor Networks]
            Routing[Delegation Hooks]
            Coordination[Subagent Orchestration]
        end
    end

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

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

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

    Client --> Coord
    API --> Coord

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

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

    Workflows --> Agents
    %% Networks (supervisors) delegate to subagents
    Networks --> Agents

    Tools --> VectorStore
    Tools --> Relational

    Workspaces --> LSP
    Workspaces --> Security

    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,Query frontend
    class Coord,Agents,Tools,Workflows,Networks,Research,Financial,Coding,Content,APIs,Search,RAG,Sequential,Parallel,Suspense,Routing,Coordination,Supervisor,Workspaces,LSP,Security runtime
    class VectorStore,Relational,Cache storage
    class Tracing,Metrics,Analytics observe
    class Client,API,SDK external

🔍 聊天UI后端架构

%%{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

📊 系统流程图

%%{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 {
      >
      +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  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管道(生产级)

%%{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
PDF/Web/MDX] --> B{MDocument
Chunker}
        B -->|10 Strategies| C[Chunks +
Metadata]
        C --> D[text-embedding-004
3072D Vectors]
        D --> E[(LibSQL
HNSW Index)]
    end

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

    subgraph Generation ["💬 Answer Pipeline"]
        L --> M[Supervisor Agent
Scoring & Synthesis]
        M --> N[Generated
Response]
        N --> O[Citations
Verification]
        O --> P[Sources +
Confidence Score]
    end

    subgraph Observability ["📊 Full Observability"]
        M -.->|Spans| Q[Langfuse
Traces]
        E -.->|Usage| Q
        N -.->|Metrics| R[Custom Scorers
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

🤝 流程图

%%{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

🚀 钩子 (制作前5分钟)

%%{init: {'theme': 'dark', 'themeVariables': { 'primaryColor': '#58a6ff', 'primaryTextColor': '#c9d1d9', 'primaryBorderColor': '#30363d', 'lineColor': '#58a6ff', 'sectionBkgColor': '#161b22', 'altSectionBkgColor': '#0d1117', 'sectionTextColor': '#c9d1d9', 'gridColor': '#30363d', 'tertiaryColor': '#161b22' }}}%%
classDiagram
  class MastraQueryHooks {
    >
    %% Core access
    +useAgents()
    +useAgent(agentId, requestContext)
    +useAgentModelProviders()
    +useAgentSpeakers(agentId, requestContext)
    +useAgentListener(agentId, requestContext)

    %% Tools and processors
    +useTools(requestContext)
    +useTool(toolId, requestContext)
    +useToolProviders()
    +useToolProvider(providerId)
    +useToolProviderToolkits(providerId)
    +useToolProviderTools(providerId, params)
    +useToolProviderToolSchema(providerId, toolSlug)
    +useProcessors(requestContext)
    +useProcessor(processorId, requestContext)
    +useProcessorProviders()
    +useProcessorProvider(providerId)
    +useProcessorExecuteMutation(processorId)

    %% Workflows and runs
    +useWorkflows(requestContext, partial)
    +useWorkflow(workflowId, requestContext)
    +useWorkflowRun(workflowId, runId, options)
    +useWorkflowRuns(workflowId, params, requestContext)
    +useWorkflowSchema(workflowId)
    +useWorkflowStartMutation(workflowId)
    +useWorkflowStartAsyncMutation(workflowId)
    +useWorkflowDeleteRunMutation(workflowId)
    +useWorkflowResumeMutation(workflowId)
    +useWorkflowResumeAsyncMutation(workflowId)
    +useWorkflowCancelMutation(workflowId)
    +useWorkflowRestartMutation(workflowId)
    +useWorkflowRestartAsyncMutation(workflowId)
    +useWorkflowTimeTravelMutation(workflowId)
    +useWorkflowTimeTravelAsyncMutation(workflowId)

    %% Memory and threads
    +useThreads(params)
    +useThread(threadId, agentId, requestContext)
    +useThreadMessages(threadId, opts)
    +useThreadMessagesPaginated(threadId, opts)
    +useWorkingMemory(params)
    +useMemorySearch(params)
    +useMemoryStatus(agentId, requestContext, opts)
    +useMemoryConfig(params)
    +useObservationalMemory(params)
    +useAwaitBufferStatus(params)
    +useCreateThreadMutation()
    +useDeleteThreadMutation()
    +useUpdateMemoryThreadMutation(threadId, agentId)
    +useUpdateWorkingMemoryMutation(agentId, threadId)
    +useSaveMessageToMemoryMutation()
    +useDeleteThreadMessagesMutation(threadId, agentId)
    +useCloneThreadMutation(threadId, agentId)

    %% Stored agents and versions
    +useStoredAgents(params)
    +useStoredAgent(id, requestContext, options)
    +useStoredAgentVersions(storedAgentId, params, requestContext)
    +useStoredAgentVersion(storedAgentId, versionId, requestContext)
    +useCompareStoredAgentVersions(storedAgentId, fromId, toId, requestContext)
    +useCreateStoredAgentMutation()
    +useUpdateStoredAgentMutation(storedAgentId)
    +useDeleteStoredAgentMutation(storedAgentId)
    +useCreateStoredAgentVersionMutation(storedAgentId)
    +useActivateStoredAgentVersionMutation(storedAgentId)
    +useRestoreStoredAgentVersionMutation(storedAgentId)
    +useDeleteStoredAgentVersionMutation(storedAgentId)

    %% Stored prompt blocks
    +useStoredPromptBlocks(params)
    +useStoredPromptBlock(id, requestContext, options)
    +useStoredPromptBlockVersions(storedPromptBlockId, params, requestContext)
    +useStoredPromptBlockVersion(storedPromptBlockId, versionId, requestContext)
    +useCompareStoredPromptBlockVersions(storedPromptBlockId, fromId, toId, requestContext)
    +useCreateStoredPromptBlockMutation()
    +useUpdateStoredPromptBlockMutation(storedPromptBlockId)
    +useDeleteStoredPromptBlockMutation(storedPromptBlockId)
    +useCreateStoredPromptBlockVersionMutation(storedPromptBlockId)
    +useActivateStoredPromptBlockVersionMutation(storedPromptBlockId)
    +useRestoreStoredPromptBlockVersionMutation(storedPromptBlockId)
    +useDeleteStoredPromptBlockVersionMutation(storedPromptBlockId)

    %% Stored scorers
    +useStoredScorers(params)
    +useStoredScorer(id, requestContext, options)
    +useStoredScorerVersions(storedScorerId, params, requestContext)
    +useStoredScorerVersion(storedScorerId, versionId, requestContext)
    +useCompareStoredScorerVersions(storedScorerId, fromId, toId, requestContext)
    +useCreateStoredScorerMutation()
    +useUpdateStoredScorerMutation(storedScorerId)
    +useDeleteStoredScorerMutation(storedScorerId)
    +useCreateStoredScorerVersionMutation(storedScorerId)
    +useActivateStoredScorerVersionMutation(storedScorerId)
    +useRestoreStoredScorerVersionMutation(storedScorerId)
    +useDeleteStoredScorerVersionMutation(storedScorerId)

    %% Stored MCP clients and skills
    +useStoredMcpClients(params)
    +useStoredMcpClient(id, requestContext)
    +useCreateStoredMcpClientMutation()
    +useUpdateStoredMcpClientMutation(storedMcpClientId)
    +useDeleteStoredMcpClientMutation(storedMcpClientId)
    +useStoredSkills(params)
    +useStoredSkill(id, requestContext)
    +useCreateStoredSkillMutation()
    +useUpdateStoredSkillMutation(storedSkillId)
    +useDeleteStoredSkillMutation(storedSkillId)

    %% Vectors and embedders
    +useVectorIndexes()
    +useVectorDetails(indexName)
    +useVectors()
    +useEmbedders()
    +useVectorQueryMutation(vectorName, indexName)
    +useVectorUpsertMutation(vectorName, indexName)

    %% Workspaces and skills
    +useWorkspaces()
    +useWorkspace(id)
    +useWorkspaceInfo(id)
    +useWorkspaceFiles(id, params)
    +useWorkspaceReadFile(id, path)
    +useWorkspaceSearch(id, params)
    +useWorkspaceSkills(id)
    +useWorkspaceSearchSkills(workspaceId, params)
    +useWorkspaceSkill(workspaceId, skillName)
    +useWorkspaceSkillReferences(workspaceId, skillName)
    +useWorkspaceSkillReference(workspaceId, skillName, referencePath)
    +useWorkspaceWriteFileMutation(workspaceId)
    +useWorkspaceDeleteMutation(workspaceId)
    +useWorkspaceMkdirMutation(workspaceId)
    +useWorkspaceRenameMutation(workspaceId)

    %% A2A and Agent Builder
    +useA2ASendMessageMutation(agentId)
    +useA2ASendStreamingMessageMutation(agentId)
    +useA2AGetTask(agentId, params)
    +useA2ACancelTaskMutation(agentId)
    +useAgentBuilderActions()
    +useAgentBuilderAction(actionId)
    +useAgentBuilderRuns(actionId, params)
    +useAgentBuilderRun(actionId, runId, options)
    +useAgentBuilderCreateRunMutation(actionId)
    +useAgentBuilderStartAsyncMutation(actionId)
    +useAgentBuilderStartRunMutation(actionId)
    +useAgentBuilderResumeMutation(actionId)
    +useAgentBuilderResumeAsyncMutation(actionId)
    +useAgentBuilderCancelRunMutation(actionId)
  }

  class MastraClient {
    +listTools(requestContext)
    +getTool(toolId)
    +listToolProviders()
    +getToolProvider(providerId)
    +listProcessors(requestContext)
    +getProcessor(processorId)
    +listStoredAgents(params)
    +getStoredAgent(id)
    +listStoredPromptBlocks(params)
    +getStoredPromptBlock(id)
    +listStoredScorers(params)
    +getStoredScorer(id)
    +listStoredMCPClients(params)
    +getStoredMCPClient(id)
    +listStoredSkills(params)
    +getStoredSkill(id)
    +listWorkflows(requestContext, partial)
    +getWorkflow(workflowId)
    +getWorkingMemory(params)
    +searchMemory(params)
    +getObservationalMemory(params)
    +awaitBufferStatus(params)
    +listVectors()
    +listEmbedders()
    +getWorkspace(id)
    +getA2A(agentId)
    +getAgentBuilderActions()
    +getAgentBuilderAction(actionId)
  }

  class ReactQueryClient {
    +useQuery(options)
    +useMutation(options)
    +invalidateQueries(options)
  }

  MastraQueryHooks ..> MastraClient : uses
  MastraQueryHooks ..> ReactQueryClient : uses
  MastraClient  MastraClientStoredAgent : stored agent hooks
  MastraQueryHooks ..> MastraClientWorkflow : workflow hooks
  MastraQueryHooks ..> MastraClientProcessor : processor hooks
  MastraQueryHooks ..> MastraClientAgentBuilderAction : agent builder hooks

1.️⃣ 先决条件

在开始之前,请确保您已经:

需求版本目的安装
Node.js≥20.9.0运行时间下载
libSQL-身份验证、代理、工作区和主管的主要持久性图尔索 或本地文件回退(file:./database.db)
API密钥-LLM和工具请参阅 配置 在......下面

本地libSQL的一行代码:

echo "TURSO_DATABASE_URL=file:./data/mastra.db" >> .env

2.️⃣ 克隆和安装

# 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.️⃣ 配置环境

# 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)
# - TURSO_DATABASE_URL (for libSQL)

快速.env设置:

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

# Database - libSQL
echo "TURSO_DATABASE_URL=file:./data/mastra.db" >> .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.️⃣ 启动开发服务器

# 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)

预期启动输出:

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

5.️⃣ 验证并开始构建

打开浏览器并导航到:

URL你会看到什么
http://localhost:3000带有代理概述的登录页面
http://localhost:3000/chat人工智能聊天界面,有48个以上的代理
http://localhost:3000/dashboard带有跟踪和指标的管理仪表板
http://localhost:3000/workflows交互式工作流画布

测试您的设置:

# Run the test suite
npm test

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

______________________________________________________________________

🎉 你准备好了! 结账 发展 开始构建自定义工具和代理。

Next.js+Mastra客户端SDK

前端使用 @mastra/client-js 使用TanStack Query进行稳健的状态管理:

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

// lib/hooks/use-mastra-query.ts - 1590+ lines of TanStack Query hooks
import { useQuery } from '@tanstack/react-query'
import { mastraClient } from '@/lib/mastra-client'

// lib/types/ - Zod schemas and TypeScript types
import { z } from 'zod'

主要特点:

  • 类型安全:使用Zod架构验证的所有API响应
  • 缓存:集中查询键,实现高效缓存管理
  • 突变:使用ExecuteToolmutation,使用CreateThreadmutation,以及使用VectorQuerymutation
  • 实时:自动缓存失效和重新提取突变
  • 错误处理:内置加载/错误状态

客户端组件中的用法:

"use client";
import { useAgents } from "@/lib/hooks/use-mastra-query";

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

  if (isLoading) return 
Loading agents...
;
  if (error) return 
Error: {error.message}
;

  return agents.map(agent => );
}

页:

  • / -带有代理概述的登录页面
  • /test -服务器操作演示(SSR)
  • /chat -使用AI Elements和@AI sdk/react与48多名代理进行AI聊天
  • /networks -具有路由功能的高级代理网络编排
  • /workflows -具有11个以上工作流的交互式工作流画布
  • /dashboard -带有TanStack查询挂钩的管理仪表板,用于代理/工具/工作流/跟踪/内存/向量
  • /tools -工具文档和执行界面
  • /docs -全面的文档(AI SDK、组件、RAG、安全性、运行时上下文)
  • /api-reference -OpenAPI架构和API文档

共享库:

  • lib/mastra-client.ts -前端MastraClient配置
  • lib/hooks/ -用于数据提取的TanStack查询挂钩(1590+行)

- use-mastra-query.ts -用于代理、工作流、数据集、评估和可观察性的全面挂钩

  • lib/types/ -Zod模式和TypeScript类型(自动生成)
  • lib/utils.ts -共享实用程序(cn、formatDate等)
  • lib/a2a.ts -代理间协调实用程序
  • lib/auth.ts -身份验证实用程序
  • src/mastra/auth.ts -更好的Auth+LibSQL服务器身份验证配置
  • src/mastra/workspaces.ts -工作区、沙箱、AgentFS和LibSQL支持的工作区存储
  • src/mastra/agents/request-context.ts -服务器端请求上下文架构和帮助程序
  • src/mastra/tools/request-context.utils.ts -工具端请求上下文助手

MCP服务器(A2A)

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

生产

npm run build
npm run start

性能指标

AgentStack专为高性能生产工作负载而设计,具有全面的基准测试和优化功能:

系统基准

度量详细信息
冷启动\>Script: Start remote-debug Chrome

Script->>Chrome: Launch Chrome with CDP enabled Chrome-->>CDP: Publish DevTools endpoint BrowserAgent->>CDP: Connect via CHROME_CDP_URL BrowserAgent->>Browser: Reuse shared browser session BrowserAgent->>App: Navigate, click, type, inspect App-->>BrowserAgent: DOM, console, screenshots BrowserAgent-->>Dev: Structured result


|端点|RPS|平均延迟|用例|
| -------------------- | --- | ----------- | ---------------------------------- |
| `/api/chat` |150 | 180毫秒|与主管代理进行人工智能聊天|
| `/api/workflow` |85 | 420毫秒|多步骤工作流程|
| `/api/rag/query` |200|95ms|矢量相似性搜索|
| `/api/dataset` |180|120ms|数据集操作和实验|
| `/api/tools/execute` |120|250ms|刀具执行|
| `/api/observability` |95|140ms|跟踪和指标检索|
| `/api/network` |75 | 350毫秒|代理网络编排|
| `/api/workspace` |110|120ms|工作区文件操作|

### **可观察性性能**

Tracing overhead: {

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 libsqlStorage.createIndex({ tableName: 'embeddings', indexName: 'hnsw_cosine_idx', metric: 'cosine', method: 'hnsw', // Faster than ivfflat for most workloads efConstruction: 128, efSearch: 64, })


______________________________________________________________________

## 📁 **结构**

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

├── app/ (24 directories, 298+ files, 1.2MB+) │ ├── about/ (410.0B) │ │ └── page.tsx │ ├── api/ (6 files, 6.6KB) │ │ ├── chat/ route.ts │ │ ├── chat-extra/ route.ts │ │ ├── completion/ route.ts │ │ ├── contact/ route.ts │ │ └── v0/ route.ts │ ├── api-reference/ (5 files, 38.0KB) │ │ ├── agents/ page.mdx │ │ ├── openapi-schema/ page.mdx │ │ ├── tools/ page.mdx │ │ ├── workflows/ page.mdx │ │ └── page.tsx │ ├── blog/ (4 files, 13.4KB) │ │ ├── hello-world-agentstack/ page.mdx │ │ ├── session-summary/ page.tsx │ │ └── layout.tsx │ ├── careers/ page.tsx │ ├── changelog/ page.tsx │ ├── chat/ (16 directories, 27+ files, 175.7KB+) │ │ ├── components/ (16 files, 93.5KB) │ │ │ └── AI Elements: agent-artifact, agent-chain-of-thought, agent-sources, etc. │ │ ├── config/ (7 files, 50.4KB) │ │ │ └── Model configs: google-models, anthropic-models, openai-models, etc. │ │ ├── helpers/ tool-part-transform.ts │ │ ├── dataset/ dataset management │ │ ├── harness/ evaluation tools │ │ ├── logs/ logging interfaces │ │ ├── mcp-a2a/ MCP coordination │ │ ├── observability/ tracing & metrics │ │ ├── providers/ chat providers │ │ ├── tools/ tool interfaces │ │ ├── workflows/ workflow execution │ │ └── workspaces/ workspace management │ ├── [other app routes...] │ └── page.tsx

├── lib/ (React utilities & hooks) │ ├── hooks/ (1590+ lines of TanStack Query hooks) │ │ └── use-mastra-query.ts (comprehensive data fetching) │ ├── types/ (Zod schemas & TypeScript types, auto-generated) │ ├── mastra-client.ts (SDK configuration) │ └── [utilities & helpers]

├── src/mastra/ (22 directories, backend orchestration) │ ├── index.ts (25+ agents, 10+ workflows, 12+ networks, middleware) │ ├── agents/ (31 agent definitions) │ │ ├── supervisor-agent.ts (scoring & delegation) │ │ └── [specialized agents: research, copywriter, stock analysis, etc.] │ ├── workflows/ (10+ multi-step workflows) │ ├── networks/ (12+ supervisor networks - primary coordination) │ │ ├── agentNetwork (primary router to all specialized agents) │ │ ├── codingTeamNetwork (architecture → review → test → refactor) │ │ ├── financialIntelligenceNetwork (research → analysis → charts) │ │ └── [other domain-specific supervisor networks] │ ├── tools/ (57 enterprise tools) │ ├── config/ (model & storage configuration) │ ├── workspaces.ts (14 workspace variants: AgentFS, Daytona, Local) │ ├── harness.ts (multi-mode agent orchestration - ⚠️ alpha) │ ├── a2a/ (agent-to-agent coordination) │ ├── mcp/ (MCP servers) │ └── [processors, evals, middleware, etc.]

├── [other directories: docs, scripts, tests, etc.]


## 🛠️ **发展**

使用AgentStack构建旨在直观高效。以下是您的开发工作流程:

### **创建自定义工具**

// 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' } }, })


**工具开发最佳实践:**

- ✅ 始终为输入和输出定义严格的Zod模式
- ✅ 保持工具无状态和纯粹(代理处理编排)
- ✅ 包括对键入的返回进行全面的错误处理
- ✅ 添加带有模拟外部依赖关系的Vitest测试
- ✅ 使用结构化日志记录实现可观察性

### **创建自定义代理**

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

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, libsqlQueryTool, }, memory: LibsqlMemory, // Enable conversation memory })


### **实时浏览器自动化**

AgentStack可以通过Chrome DevTools附加到本地Chrome会话
协议(CDP)。这为实时浏览器代理和共享浏览器提供了动力
运行时。

#### 在远程调试模式下启动Chrome

npm run chrome:debug


该脚本启动Chrome时包含:

chrome.exe --remote-debugging-port=9222 --user-data-dir="%TEMP%\\chrome-debug"


#### 环境变量

CHROME_CDP_URL=http://127.0.0.1:9222 CHROME_REMOTE_DEBUGGING_URL=http://127.0.0.1:9222


#### 浏览器运行时包

|包装|版本|用途|
| --- | --- | --- |
| `@mastra/agent-browser` | `^0.1.0` |CDP上的浏览器代理集成|
| `@mastra/stagehand` | `^0.1.0` |共享浏览器自动化助手|
| `playwright` | `^1.59.1` |浏览器自动化/验证|
| `@mastra/core` | `^1.24.1` |代理运行时和浏览器编排|

#### 运作原理

sequenceDiagram participant Dev as Developer participant Script as npm run chrome:debug participant Chrome as Local Chrome participant CDP as CHROME_CDP_URL 127.0.0.1:9222 participant Agent as browserAgent / shared browser participant Page as Target Web App

Dev->>Script: Start Chrome in remote-debug mode Script->>Chrome: Launch with remote debugging enabled Chrome-->>CDP: Expose DevTools endpoint Agent->>CDP: Connect through agentBrowser Agent->>Page: Navigate / click / type / inspect Page-->>Agent: DOM, console, screenshots, network state Agent-->>Dev: Structured result


#### 浏览器代理文件

- `src/mastra/agents/browserAgent.ts` 使用共享浏览器运行时。
- `src/mastra/browsers.ts` 集中Chrome CDP配置。
- `src/mastra/config/libsql.ts` 提供共享的LibSQL支持向量和
  代理和工作流使用的内存工具。

**代理开发最佳实践:**

- ✅ 用例子写清楚、详细的说明
- ✅ 为每个代理编写3-5个重点工具(避免工具膨胀)
- ✅ 为会话代理使用内存
- ✅ 添加用于质量监控的评估评分器
- ✅ 记录预期的输入/输出

### **开发命令**

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


### **测试策略**

// 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() }) })


## 🔧 **配置**

|环境变量|目的|必填|
| ------------------------------ | ------------------------------------- | ------------- |
| `TURSO_DATABASE_URL` |用于auth/RAG的LibSQL持久性|✅            |
| `GOOGLE_GENERATIVE_AI_API_KEY` |双子座法学硕士/嵌入|✅            |
| `SERPAPI_API_KEY` |搜索/新闻/购物(10+工具)|✅            |
| `POLYGON_API_KEY` |股票/加密货币报价/价格/基本面|✅            |
| `LANGFUSE_BASE_URL` |Langfuse追踪|可观察性|

**满的**: `.env.example` + `src/mastra/config/AGENTS.md`

## 🧪 **测试策略(97%覆盖率)**

AgentStack保持了严格的测试标准,在100多个测试中实现了97%的代码覆盖率,确保了生产可靠性和安全部署。

### **测试命令**

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


### **测试原理**

┌─────────────────────────────────────────────────────────┐ │ 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 │ └─────────────────────────────────────────────────────────┘


### **测试类别**

|类型|覆盖范围|工具|目的|
| --------------------- | -------- | -------------- | ------------------------------- |
| **单元测试** |97%| Vitest |工具/代理逻辑隔离|
| **集成测试** |85%| Vitest+MSW | API交互,DB操作|
| **E2E测试** |60%|编剧|用户流,关键路径|
| **评估测试** |100%|自定义评分器|代理质量指标|

### **模拟策略**

所有外部API调用都被完全嘲笑为可靠、快速的测试:

// 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/libsql', () => ({ libsqlQueryTool: { execute: vi.fn().mockResolvedValue({ data: [{ id: 1, result: 'success' }], error: null, }), }, }))


### **写作测试**

// 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') }) }) })


## 🔒 **安全与治理**

AgentStack为生产部署实施了企业级安全控制,防止常见漏洞并确保数据隐私。

### **安全层**

┌─────────────────────────────────────────────────────────────┐ │ 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 │ └─────────────────────────────────────────────────────────────┘


### **关键安全功能**

|功能|实现|保护|
| ---------------------------- | ---------------------------- | --------------------------------------- |
| **JWT身份验证** | `jwt-auth.tool.ts` |通过令牌验证确保API访问安全|
| **基于角色的访问** | `src/mastra/policy/acl.yaml` |每个用户/代理的精细权限|
| **路径验证** | `validateDataPath()` |防止目录遍历攻击|
| **HTML净化** |JSDOM+Cheerio |删除脚本/恶意内容|
| **秘密面具** | `maskSensitiveMessageData()` |在日志和跟踪中隐藏API密钥|
| **速率限制** |内置节流|防止API滥用和成本超支|
| **SQL注入防护** |参数化查询|安全的数据库操作|

### **安全最佳实践**

// 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/libsql'

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


### **合规就绪**

- ✅ **GDPR 数据保护**:数据匿名化和保留控制
- ✅ **SOC 2**:审计跟踪和访问日志记录
- ✅ **ISO 27001**:安全控制文件
- ✅ **《健康保险可携性和责任法案》**:PHI处理能力(带配置)

## 📊 **可观察性(生产就绪)**

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


**自定义评分器**来源多样性、完整性、创造性、响应质量。

### 仪表板架构

管理仪表板提供全面的可观察性和管理:

**路线:**

- `/dashboard` -统计卡概述(代理、工作流程、工具、最近的活动)
- `/dashboard/agents` -代理管理(列表、详细信息、工具、评估)
- `/dashboard/workflows` -工作流监控和执行历史
- `/dashboard/tools` -工具目录和使用分析
- `/dashboard/observability` -跟踪、跨度和性能指标
- `/dashboard/memory` -内存线程、消息和工作内存
- `/dashboard/vectors` -矢量索引和相似性搜索
- `/dashboard/logs` -带传输过滤的系统日志
- `/dashboard/telemetry` -性能遥测和指标

**组件:**

// 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


**数据获取:**

所有仪表板页面都使用TanStack查询挂钩 `lib/hooks/use-mastra-query.ts`:

import { useAgents, useTools, useTraces } from '@/lib/hooks/use-mastra-query'

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

// Automatic caching, refetching, and error handling }


## 🌐 **集成矩阵**

|类别|工具|代理|前端|
| -------------------- | ------------------------------------------------------ | ----------------------------------------- | --------------------------------------- |
| **🔍 搜索** |SerpAPI(新闻/趋势/购物/学者/本地/Yelp)| ResearchAgent |引用聊天界面|
| **💰 金融的** |Polygon(10+)、Finnhub(6+)、AlphaVantage(指标)|股票分析、加密货币分析|带图表和指标的仪表板|
| **📄 检索增强生成** |libSQL块/重新排序/查询/图形|检索/重新排序/应答器|向量搜索界面|
| **📝 内容** | PDF→MD、Web Scraper、Copywriter/Editor | CopywriterAgent、EditorAgent、ReportAgent |与工件预览聊天|
| **🎨 视觉** |CSV↔Excalidraw、SVG/XML过程|csvToExcalidrawAgent、imageToCsvAgent |工作流画布可视化|
| **🌐 编排** |A2A MCP服务器|A2A协调器代理,编码A2A协调器|网络路由面板|
| **💻 用户界面** |AI元素(30)、shadcn/ui(35)、Radix原语|聊天/推理/画布接口| 10多个应用程序路由中的65个组件|
| **📊 可观测性** |Langfuse跟踪,自定义评分器|所有代理都配备了仪器|带有跟踪/日志/遥测的仪表板|
| **🔄 州管理** |TanStack查询|内存线程、工作内存|15+个带缓存和无效的钩子|

## 🤝 **高级用法**

### 💬 聊天界面

聊天界面(`/chat`)通过48多名专业代理提供生产就绪的AI聊天体验:

**AI元素组件** (16个集成):

- `AgentArtifact` -带预览的代码/文档工件
- `AgentChainOfThought` -逐步推理显示
- `AgentCheckpoint` -进度检查点
- `AgentConfirmation` -用户确认
- `AgentInlineCitation` -来源引用
- `AgentPlan` -多步骤计划
- `AgentQueue` -任务队列
- `AgentReasoning` -推理痕迹
- `AgentSources` -源文件
- `AgentSuggestions` -后续建议
- `AgentTask` -个人任务
- `AgentTools` -工具使用显示
- `AgentWebPreview` -Web预览iframe

**代理类别** (总计48+):

- **研究** (5) :researchAgent、researchPaperAgent、知识索引Agent、learningExtractAgent、dane
- **内容** (5) :文案代理、编辑代理、内容策略师代理、编剧代理、报告代理
- **金融的** (6) :股票分析代理、图表监管代理、图表类型咨询代理、图表数据处理代理、图表生成器代理
- **数据** (8) :数据摄取代理、数据转换代理、数据导出代理、文档处理代理、csvToExcalidrawAgent、imageToSvAgent、excalidrawValidatorAgent、imageAgent
- **编程** (9) :codeArchitectAgent、codeReviewerAgent、testEngineerAgent、重构Agent、daneCommitMessage、daneIssueLabeler、daneLinkChecker、daneChangeLog、danePackagePublisher
- **商业** (4) :法律研究代理、合同分析代理、合规监控代理、商业战略代理

**模型提供商** (40+型号):

- **谷歌**:8个型号(Gemini 2.5 Flash、Pro、Exp变体)
- **开放人工智能**:12个型号(GPT-5、GPT-4o、o1、o3 mini)
- **Anthropic**:8款(克劳德4.5,4首十四行诗/歌剧/俳句)
- **开放路由**:12款以上型号(Llama、Mistral、Qwen)

### 🌐 网络接口

高级代理网络编排(`/networks`)通过路由和协调:

**13个预配置网络:**

1. **主代理网络** (8个代理):一般路由到专业代理
1. **编码团队网络** (4个代理):架构→ 审查→ 测试→ 重构
1. **数据管道网络** (3种药物):摄入→ 转变→ 出口
1. **报表生成网络** (3名代理人):研究→ 分析→ 报告
1. **研究管道网络** (4名代理人):研究→ 学习→ 知识索引→ 合成
1. **内容创作网络** (5名代理人):写作→ 编辑→ 策略→ 脚本编写
1. **金融情报网** (7名代理人):股票分析→ 图表→ 研究→ 报告
1. **学习网络** (5个代理):学习提取→ 知识索引→ 研究
1. **营销自动化网络** (6名代理人):社交媒体→ SEO → 内容→ 翻译
1. **DevOps网络** (7个代理):架构→ 测试→ 部署→ 监控
1. **商业智能网络** (7个代理):数据摄取→ 分析→ 可视化
1. **安全网络** (4名代理人):代码审查→ 遵从→ 漏洞管理

**特征:**

- **网络路由面板**:实时可视化代理路由决策
- **并行执行**:多个代理同时工作
- **A2A协调**:代理间通信管理

### 🔄 工作流界面

交互式工作流可视化(`/workflows`)使用AI元素画布:

**21个预构建工作流:**

1. **天气工作流程**:获取天气→ 分析→ 建议活动
1. **内容工作室**:研究→ 写→ Edit → 审查
1. **内容审查**:提取→ 分析→ 得分→ 报告
1. **财务报告**:市场数据→ 分析→ 报告生成
1. **文档处理**:上传→ 解析→ 块→ 嵌入→ Index
1. **研究综合**:查询→ 搜索→ 分析→ 合成
1. **学习提取**:阅读→ 提取→ 总结→ Store
1. **治理RAG指数**:验证→ 块→ 嵌入→ 更新插入
1. **受政府监管的RAG答案**:查询→ 检索→ 重排序→ 回答
1. **规格生成**:要求→ 设计→ Spec → 验证
1. **股票分析**:获取数据→ 技术分析→ 报告
1. **Repo摄入**:存储库分析→ 代码索引→ 知识库
1. **电话游戏**:交互式用户输入工作流
1. **变更日志生成**:Git差异分析→ AI变更日志创建
1. **营销活动**:端到端的活动编排
1. **自动报告**:计划数据收集→ 报告生成
1. **数据分析**:多源数据摄取→ 转变→ 洞察
1. **财务分析**:深入的市场分析→ 风险评估→ 策略
1. **安全重构**:代码分析→ 重构→ 测试验证
1. **测试生成**:代码分析→ 单元/集成测试创建
1. **新贡献者**:入职培训→ 回购分析→ 首项任务指导

**AI元素组件** (8用于工作流):

- `WorkflowCanvas` -带平移/缩放功能的主画布
- `WorkflowNode` -单个工作流程步骤
- `WorkflowEdge` -步骤之间的连接
- `WorkflowPanel` -带细节的侧面板
- `WorkflowControls` -画布控件
- `WorkflowLegend` -节点类型图例
- `WorkflowOutput` -执行输出显示

## 🚀 **高级用法**

### 自定义代理

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


### MCP/A2A客户端

Start server

npm run mcp-server

Use in Cursor/Claude

coordinate_a2a_task({task: "AAPL analysis", agents: ["research", "stock"]})


## 🤝 **贡献**

AgentStack是一个开源项目,由开发人员、研究人员和人工智能爱好者组成的社区提供支持。我们欢迎各种贡献——从错误修复和文档改进到新工具、代理和创新功能。

### **为什么要贡献?**

- 🚀 **塑造未来**:帮助定义生产级多代理系统的标准
- 📚 **学习与成长**:使用尖端的人工智能技术(Mastra、RAG、A2A编排)
- 🌟 **构建您的投资组合**:为高影响力、企业就绪的框架做出贡献
- 🤝 **加入社区**:与全球充满激情的开发人员合作

### **贡献者快速入门**

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


### **贡献什么**

|贡献类型|示例|影响|
| ----------------- | -------------------------------------------------- | ------------------------------ |
| **新工具** |金融API、数据处理器、网络爬虫|扩展框架功能|
| **新代理商** |特定领域专家(法律、医疗等)|增强人工智能劳动力|
| **漏洞修补** |类型错误、边缘情况、性能问题|提高可靠性|
| **文档** |README更新、代码注释、教程|帮助其他开发人员|
| **测试** |提高覆盖率,增加集成测试|确保质量|
| **UI组件** |新的AI元素,仪表板功能|改善用户体验|
| **工作流** |多步自动化模式|演示最佳实践|

### **贡献工作流程**

%%{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


### **开发标准**

#### **代码质量检查表**

在提交PR之前,请确保:

- \[ \] **类型安全**:所有TypeScript都以严格模式编译(`npm run typecheck`)
- \[ \] **测试覆盖率**:新代码的覆盖率超过95%(`npm test`)
- \[ \] **掉毛**:ESLint无警告通过(`npm run lint`)
- \[ \] **Zod模式**:所有工具输入/输出都使用严格的验证
- \[ \] **文档**:新功能包括JSDoc注释
- \[ \] **错误处理**:输入错误返回的优雅失败
- \[ \] **可观测性**:重要操作的跟踪范围

#### **提交消息约定**

我们跟随 [约定式提交](https://www.conventionalcommits.org/):

():

[optional body]

[optional footer(s)]


**示例:**

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.


### **拉取请求模板**

在打开PR时,请包括:

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

### **获取帮助**

- 💬 **讨论**: 
- 🐛 **错误报告**: [打开问题](https://github.com/ssdeanx/AgentStack/issues)
- 📧 **电子邮件**: [ssdeanx@gmail.com](mailto:ssdeanx@gmail.com)
- 🐦 **推特**: [@ssdeanx](https://x.com/ssdeanx)

### **行为准则**

我们致力于为每个人提供热情和包容的体验:

- 在所有互动中保持尊重和建设性
- 欢迎新来者并帮助他们开始
- 专注于对社区最有利的事情
- 对他人表示同情

**报告违规行为** 到 [ssdeanx@gmail.com](mailto:ssdeanx@gmail.com)

______________________________________________________________________

**🎉 感谢您考虑为AgentStack做出贡献!每一份贡献,无论多么微小,都有助于使这个项目对每个人都更好。**

## 📚 **资源**

**前端路线:**

- **[聊天界面](app/chat/AGENTS.md)**:使用AI Elements和@AI sdk/react与48多名代理进行AI聊天
- **[网络](app/networks/AGENTS.md)**:带路由面板的高级代理网络编排
- **[工作流](app/workflows/AGENTS.md)**:使用AI Elements Canvas进行交互式工作流可视化
- **[仪表盘](app/dashboard/AGENTS.md)**:带有代理/工具/工作流/跟踪/内存/向量的管理仪表板
- **[文档](app/docs/)**:综合文档(AI SDK、组件、RAG、安全)
- **[API 参考](app/api-reference/)**:OpenAPI架构和API文档

**共享库:**

- **[lib/钩子](lib/hooks/)**:用于数据提取的TanStack查询挂钩(1590+行)
  - `use-mastra-query.ts` -适用于所有Mastra API的全面挂钩
- **[lib/types](lib/types/)**:Zod模式和TypeScript类型(自动生成)
- **[lib/](lib/)**:客户端SDK、实用程序、身份验证、A2A协调
- **[src/mastra/auth.ts](src/mastra/auth.ts)**:更好的Auth+LibSQL服务器身份验证配置
- **[src/mastra/workspaces.ts](src/mastra/workspaces.ts)**:工作区、沙箱、AgentFS和LibSQL支持的工作区存储
- **[src/mastra/agents/request-context.ts](src/mastra/agents/request-context.ts)**:服务器端请求上下文架构和帮助程序
- **[src/mastra/tools/request-context.utils.ts](src/mastra/tools/request-context.utils.ts)**:工具端请求上下文助手

**核心组件:**

- **[UI组件](ui/AGENTS.md)**:55个shadcn/ui基础组件
- **[AI元素](src/components/ai-elements/AGENTS.md)**:50个AI聊天/推理/画布组件
- **[代理商目录](src/mastra/agents/AGENTS.md)**:48多名代理人
- **[工具矩阵](src/mastra/tools/AGENTS.md)**:94+工具
- **[工作流](src/mastra/workflows/AGENTS.md)**:21个多步骤工作流
- **[网络](src/mastra/networks/AGENTS.md)**:12个代理网络
- **[配置指南](src/mastra/config/AGENTS.md)**:设置+环境变量
- **[MCP/A2A](src/mastra/mcp/AGENTS.md)**:多代理联盟
- **[得分手](src/mastra/scorers/AGENTS.md)**:10+评估指标

## 🏆 **路线图**

- \[x\] **金融套房**:Polygon/Finnhub/AlphaVantage(✅ 实时-30+个端点)
- \[x\] **RAG 流程**:libSQL+重新排序/图形(✅ 直播)
- \[x\] **A2A MCP**:并行编排(✅ 直播)
- \[x\] **15个工作流程**:顺序、并行、分支、循环、foreach、挂起/恢复(✅ 直播)
- \[x\] **12个代理网络**:路线和协调(✅ 直播)
- \[x\] **105个UI组件**:AI元素+shadcn/ui(✅ 直播)
- \[x\] **聊天界面**:带有AI元素的完整代理聊天UI(✅ 直播-48+代理)
- \[x\] **仪表盘**:带TanStack查询的管理仪表板(✅ 直播-8条路线)
- \[x\] **MastraClient SDK**:具有Zod模式的类型安全客户端(✅ 直播)
- \[x\] **营销套件**:社交媒体、搜索引擎优化、翻译、客户支持(✅ 直播)
- \[x\] **DevOps套件**:CI/CD、测试、部署、监控(✅ 直播)
- \[x\] **商业智能**:数据分析、可视化、报告(✅ 直播)
- \[x\] **安全套件**:代码审查、合规性、漏洞管理(✅ 直播)
- \[ \] **朗史密斯/凤凰城**:增强的eval仪表板
- \[ \] **Docker/Helm**:K8s部署模板
- \[ \] **多租户技术**:租户隔离和资源管理

______________________________________________________________________

⭐ **星 [ssdeanx/AgentStack](https://github.com/ssdeanx/AgentStack)**
🐦 **跟随 [@ssdeanx](https://x.com/ssdeanx)**
📘 **[文档](https://agentstack.ai)** (将于2026年第一季度推出)

_最后更新时间:2026-04-14 | v1.0.43_

## 🧠 **聊天**

%%{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 { > 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 { > info warning danger }

class InlineCitationToken { > 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

目录标签

目录标签

AI代理TypeScriptClaude本地部署企业工具金融智能RAG管道多代理协调

支持客户端

ClaudeCursorWindsurf

接入字段

传输方式(transport,传输协议)

stdio

鉴权方式(authType,认证方式)

token

运行时(runtime,运行环境)

Node.js

来源包(packageName,安装包名)

vitest

工具数量(toolCount,工具数)

0

资源数量(resourceCount,资源数)

0

提示词数量(promptCount,提示词数)

0

权限和风险

stdiotoken部署方式未说明

接入前请确认传输方式、认证方式和部署位置,并根据实际工具能力限制访问范围。

安装前确认

不要直接授予不必要的文件、网络或账号权限;先核对安装命令和配置内容。

来源信息

继续浏览同类 MCP