A production-ready proof of concept demonstrating multi-agent AI orchestration for financial services using the Mastra framework.
This project showcases 2025's "Year of the Agent" paradigm shift from generative AI to agentic AI - systems that don't just generate content but autonomously execute complex tasks. Built for a hypothetical financial services company, this POC demonstrates how multiple specialized AI agents can work together to provide comprehensive financial advisory services.
โจ Multi-Agent Orchestration - Specialized agents coordinated under an orchestrator model ๐ก๏ธ Compliance-First Architecture - Built-in regulatory compliance and safety checks ๐ง Production-Ready Framework - Uses Mastra, a TypeScript agent framework from the Gatsby team ๐ฏ Domain Expertise - Specialized agents for portfolio analysis, risk assessment, market research, and compliance ๐ Flexible Workflows - Both hierarchical and workflow-based agent coordination patterns ๐ Comprehensive Tools - 15+ specialized financial analysis tools ๐ Safety & Governance - Human-in-the-loop, audit trails, and explainable AI
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Financial Advisor Agent โ
โ (Orchestrator) โ
โโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโฌโโโโโโโโโโโโโฌโโโโโโโโโโโโโฌโโโโโโโโโโโโ
โ โ โ โ
โผ โผ โผ โผ
โโโโโโโโโโโโโโ โโโโโโโโโโโโโโ โโโโโโโโโโโโโโ โโโโโโโโโโโโโโ
โ Portfolio โ โ Risk โ โ Market โ โ Compliance โ
โ Analyst โ โ Assessment โ โ Research โ โ Agent โ
โโโโโโโโโโโโโโ โโโโโโโโโโโโโโ โโโโโโโโโโโโโโ โโโโโโโโโโโโโโ
-
Portfolio Analyst Agent ๐
- Portfolio composition analysis
- Asset allocation recommendations
- Performance metrics (Sharpe ratio, alpha, beta)
- Diversification scoring
- Rebalancing suggestions
-
Risk Assessment Agent
โ ๏ธ - Risk metric calculation (VaR, CVaR, volatility)
- Risk profile compatibility assessment
- Stress testing scenarios
- Risk mitigation strategies
-
Market Research Agent ๐
- Market trend analysis
- Sector performance evaluation
- Economic indicator monitoring
- Sentiment analysis
-
Compliance Agent โ
- Regulatory compliance checking (SEC, FINRA)
- Investment suitability assessment
- KYC/AML verification
- Compliance reporting
-
Financial Advisor Agent ๐
- Orchestrates all specialized agents
- Client request interpretation
- Response synthesis
- Human escalation
- Node.js 18+ and npm
- Anthropic API key (Claude)
- Optional: OpenAI API key for multi-provider support
# Clone the repository
git clone <repository-url>
cd mastra-agent-poc
# Install dependencies
npm install
# Set up environment variables
cp .env.example .env
# Edit .env and add your ANTHROPIC_API_KEYEdit .env file:
ANTHROPIC_API_KEY=your_anthropic_api_key_here
AGENT_TEMPERATURE=0.7
AGENT_MAX_ITERATIONS=10# Portfolio analysis example
npm run portfolio-analysis
# Risk assessment example
npm run risk-assessment
# Market research example
npm run market-research
# Full orchestrated workflow
npm run orchestratedimport { portfolioAnalystAgent } from './agents/portfolio-analyst';
const result = await portfolioAnalystAgent.generate(`
Analyze this portfolio and provide recommendations:
${JSON.stringify(portfolio)}
`);
console.log(result.text);import { executePortfolioReview } from './workflows/portfolio-review-workflow';
const result = await executePortfolioReview({
portfolio: clientPortfolio,
client: clientProfile,
});
console.log('Analysis:', result.portfolioAnalysis);
console.log('Risks:', result.riskAssessment);
console.log('Recommendations:', result.recommendations);import { executeInvestmentDecision } from './workflows/investment-decision-workflow';
const decision = await executeInvestmentDecision({
investmentType: 'ETF',
investmentAmount: 100000,
client: clientProfile,
currentPortfolio: portfolio,
});
console.log('Approved:', decision.approved);
console.log('Confidence:', decision.confidence);
console.log('Reasoning:', decision.reasoning);analyzePortfolio- Asset allocation and diversification analysiscalculatePerformanceMetrics- Returns, Sharpe ratio, alpha, betasuggestRebalancing- Portfolio rebalancing recommendations
calculateRiskMetrics- VaR, CVaR, volatility, max drawdownassessRiskProfile- Risk tolerance alignmentrunStressTest- Market stress scenario testing
getMarketData- Current market data fetchinganalyzeTrends- Technical and sentiment analysisresearchSector- Sector-specific researchanalyzeEconomicIndicators- Macro indicator analysis
checkCompliance- Regulatory compliance verificationassessSuitability- Investment suitability scoringgenerateComplianceReport- Audit trail generation
mastra-agent-poc/
โโโ src/
โ โโโ agents/ # AI agent definitions
โ โ โโโ portfolio-analyst.ts
โ โ โโโ risk-assessment.ts
โ โ โโโ market-research.ts
โ โ โโโ compliance.ts
โ โ โโโ financial-advisor.ts
โ โโโ tools/ # Agent tools
โ โ โโโ portfolio-tools.ts
โ โ โโโ risk-tools.ts
โ โ โโโ market-tools.ts
โ โ โโโ compliance-tools.ts
โ โโโ workflows/ # Multi-agent workflows
โ โ โโโ portfolio-review-workflow.ts
โ โ โโโ investment-decision-workflow.ts
โ โโโ examples/ # Usage examples
โ โ โโโ portfolio-analysis.ts
โ โ โโโ risk-assessment.ts
โ โ โโโ market-research.ts
โ โ โโโ orchestrated-workflow.ts
โ โโโ types/ # TypeScript type definitions
โ โโโ config/ # Configuration management
โ โโโ index.ts # Main entry point
โโโ ARCHITECTURE.md # Detailed architecture documentation
โโโ README.md # This file
โโโ package.json
โโโ tsconfig.json
- Human-in-the-Loop: Critical decisions flagged for human approval
- Compliance-First: All recommendations pass through compliance checks
- Explainable AI: Every agent decision includes reasoning
- Audit Trails: Complete logging of all agent interactions
- Graceful Degradation: Fallback mechanisms when agents fail
- Input validation and sanitization
- Output filtering for inappropriate recommendations
- Rate limiting to prevent abuse
- Secure API key management
- Data privacy protection
Multi-agent workflow analyzing portfolio from multiple perspectives:
- Asset allocation analysis
- Risk evaluation
- Market context
- Compliance verification
Compliance-first workflow for evaluating new investments:
- Regulatory pre-check
- Market research
- Risk assessment
- Portfolio fit analysis
Proactive risk monitoring and mitigation:
- Real-time risk metric tracking
- Stress testing
- Risk tolerance alignment
- Mitigation strategies
Automated compliance checking:
- Suitability assessments
- Regulatory requirement verification
- Audit trail generation
- Conflict of interest detection
- Memory Layer: Persistent client context and conversation history
- RAG Integration: Connect to financial databases and documents
- Multi-Modal Support: Document and chart analysis
- Real-Time Data: Live market data integration
- Advanced Orchestration: Dynamic agent selection based on complexity
- Learning Loop: Agent improvement from historical interactions
- Voice Interface: Voice-based agent interactions
- Computer Use: Agents that can interact with financial software
Mastra represents the DIY platform approach in the agentic framework spectrum:
Advantages:
- Full control over agent behavior and orchestration
- TypeScript-native for modern web development
- Built by proven team (Gatsby creators)
- Open-source and extensible
- Production-ready with observability
Alternative Approaches:
- Turnkey Solutions: LangChain, AutoGPT (higher abstraction, less control)
- Provider-Specific: OpenAI Assistants, Anthropic Claude (vendor lock-in)
- Custom Built: Full flexibility, higher development cost
Generative AI (2022-2024)
- Generate content (text, images, code)
- Require explicit instructions
- Single-turn interactions
- Human drives the process
Agentic AI (2025+)
- Execute complex tasks autonomously
- Reason about goals and strategies
- Multi-turn, iterative problem solving
- AI drives the process with human oversight
- Hierarchical: Orchestrator delegates to specialists (this POC)
- Collaborative: Agents work together as peers
- Sequential: Agents work in pipeline stages
- Competitive: Multiple agents propose solutions, best selected
This is a proof of concept for demonstration purposes. For production use:
- Implement real market data integrations
- Add persistent storage for client data
- Enhance security and authentication
- Add comprehensive testing
- Implement monitoring and alerting
- Add regulatory compliance modules specific to your jurisdiction
ISC License - see LICENSE file for details
- Mastra Framework - The TypeScript AI agent framework
- Anthropic Claude - The LLM powering our agents
- Financial services domain expertise from industry best practices
For questions or issues:
- Review the ARCHITECTURE.md for detailed design information
- Check the examples in
src/examples/ - Open an issue in the repository
Built with โค๏ธ demonstrating the future of AI agents in financial services
This is a proof of concept for educational and demonstration purposes. Not for production use in regulated financial advisory without proper compliance review and licensing.