Enterprise-grade AI Agent System - Constrained by SDD, Powered by MCP for Controlled Perception and Execution
中文文档 | Quick Start | Architecture | Design Doc
FrontAgent is an AI Agent system designed specifically for frontend engineering, addressing core challenges faced when deploying agents in real-world engineering scenarios:
- ✅ Two-Stage Architecture - Separate planning and execution to avoid JSON parsing errors and enable dynamic code generation
- ✅ Phase-Based Execution - Steps grouped by phases with error recovery within each phase
- ✅ Self-Healing - Tool Error Feedback Loop automatically analyzes errors and generates fix steps
- ✅ Facts Memory - Structured facts-based context system for precise project state tracking
- ✅ Module Dependency Tracking - Automatic import/export parsing to detect path hallucinations
- ✅ Hallucination Prevention - Multi-layer hallucination detection and interception
- ✅ SDD Constraints - Specification Driven Development as hard constraints for agent behavior
- ✅ MCP Protocol - Controlled tool invocation via Model Context Protocol
- ✅ Minimal Changes - Patch-based code modifications with rollback support
- ✅ Web Awareness - Understand page structure through browser MCP
- ✅ Shell Integration - Terminal command execution (requires user approval)
- ✅ Pre-Planning Scan - Scan project structure before planning to generate accurate file paths
- ✅ Auto Port Detection - Automatically detect dev server ports from config files
# 1. Install
git clone <repo>
cd frontagent
pnpm install
pnpm build
npm link
# 2. Configure LLM (supports OpenAI and Anthropic)
# OpenAI config
export PROVIDER="openai"
export BASE_URL="https://api.openai.com/v1"
export MODEL="gpt-4"
export API_KEY="sk-..."
# Or Anthropic config
export PROVIDER="anthropic"
export BASE_URL="https://api.anthropic.com"
export MODEL="claude-sonnet-4-20250514"
export API_KEY="sk-ant-..."
# 3. Navigate to your project directory and initialize SDD
cd your-project
frontagent init
# 4. Let AI help you complete tasks
frontagent run "Create a user login page"
frontagent run "Optimize homepage loading performance"
frontagent run "Add dark mode support"┌─────────────────────────────────────────────────────────────────────┐
│ FrontAgent System │
├─────────────────────────────────────────────────────────────────────┤
│ │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ User Input │────▶│ Agent Core │────▶│ Output │ │
│ └─────────────┘ └──────┬──────┘ └─────────────┘ │
│ │ │
│ ┌─────────────────┼─────────────────┐ │
│ ▼ ▼ ▼ │
│ ┌────────────────┐ ┌────────────┐ ┌────────────────┐ │
│ │ SDD Layer │ │ Planner │ │ Executor │ │
│ │ (Constraints) │ │ (Stage 1) │ │ (Stage 2) │ │
│ └───────┬────────┘ └─────┬──────┘ └───────┬────────┘ │
│ │ │ │ │
│ ▼ ▼ ▼ │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ MCP Layer (Trusted Interface) │ │
│ ├──────────────┬───────────────┬──────────────────────┤ │
│ │ MCP File │ MCP Web │ MCP Shell │ │
│ └──────┬───────┴───────┬───────┴──────────┬───────────┘ │
└─────────┼───────────────┼──────────────────┼────────────────────────┘
▼ ▼ ▼
┌──────────────┐ ┌──────────┐ ┌──────────┐
│ File System │ │ Browser │ │ Shell │
│ (Project) │ │(Playwright)│ │Commands │
└──────────────┘ └──────────┘ └──────────┘
User Task
│
▼
┌──────────────────┐
│ Pre-Planning │ ← Scan project structure (NEW!)
│ File Scan │ Detect dev server port (NEW!)
└────────┬─────────┘
│
▼
┌──────────────────┐
│ Planner (Stage1)│ ← SDD Constraints
└────────┬─────────┘ Project file list
│ Dev server port
│ Generates execution plan (with phase field)
▼
┌──────────────────────────────────────────┐
│ Executor (Stage 2) │
│ ┌────────────────────────────────┐ │
│ │ Phase 1: Analysis │ │
│ │ ├─ Step 1 ✓ │ │
│ │ ├─ Step 2 ✗ (error) │ │
│ │ └─ Error Recovery │ │
│ │ ├─ Analyze error │ │
│ │ ├─ Generate fix steps │ │
│ │ └─ Execute fix ✓ │ │
│ └────────────────────────────────┘ │
│ ┌────────────────────────────────┐ │
│ │ Phase 2: Creation │ │
│ │ ├─ Step 3 ✓ │ │
│ │ └─ Step 4 ✓ │ │
│ └────────────────────────────────┘ │
│ │
│ After each step: │
│ └─ Update Facts │
│ ├─ File system state │
│ ├─ Dependency state │
│ ├─ Module dependency graph │
│ └─ Project state │
│ │
│ Phase completion validation: │
│ └─ Check missing module references │
│ └─ Auto-generate fix steps ✓ │
└───────────────────────────────────────────┘
│
▼
Task Complete ✓
Before generating the execution plan, FrontAgent now automatically scans the project structure to provide accurate file context to the LLM:
// Automatically executed before planning
const projectStructure = await scanProjectFiles();
// Returns: "Project files (245 files): src/App.tsx, src/components/Button.tsx, ..."
// LLM receives this context and generates more accurate file pathsBenefits:
- ✅ Accurate File Paths - LLM knows existing files and generates correct relative paths
- ✅ Reduced Hallucination - Fewer "file not found" errors
- ✅ Better Context - Planner understands the project structure before planning
Implementation: packages/core/src/agent.ts:217-255
FrontAgent now automatically detects the development server port from your project configuration:
// Detection sources (in order):
// 1. vite.config.ts/js: server.port field
// 2. package.json scripts: --port or -p flags
// 3. Framework defaults: Vite (5173), Next.js (3000), CRA (3000), Angular (4200)
// 4. Fallback: 5173
const devServerPort = await detectDevServerPort();
// Used in browser navigation tasksBenefits:
- ✅ Automatic Port Discovery - No manual port configuration needed
- ✅ Framework Awareness - Recognizes different framework defaults
- ✅ Browser Testing - Correct port used for browser validation tasks
Implementation: packages/core/src/agent.ts:732-793
FrontAgent uses an innovative two-stage architecture that completely solves JSON parsing errors when generating large amounts of code:
- Input: User task + SDD constraints + project context + project file list (NEW!)
- Output: Structured execution plan (descriptions only, no code)
- Tech: Uses
generateObjectto produce Zod Schema-compliant JSON - Key: No code in JSON, avoiding escape and parsing issues
{
"summary": "Create login page",
"steps": [
{
"description": "Create Login.tsx component file",
"action": "create_file",
"params": {
"path": "src/pages/Login.tsx",
"codeDescription": "Create a React component with username, password inputs and login button"
},
"needsCodeGeneration": true
}
]
}- Input: Structured execution plan
- Process: Execute each step in the plan sequentially
- Code Generation: When encountering
needsCodeGeneration: true, dynamically generate code usinggenerateText - Tech: Use MCP tools for file operations, command execution, etc.
Advantages:
- ✅ Completely avoid JSON parsing errors (code not in JSON)
- ✅ Better controllability (each step validated individually)
- ✅ Support large projects (no JSON size limit)
- ✅ More precise code generation (based on real-time context)
FrontAgent implements advanced phase-based execution and automatic error recovery:
The execution plan is automatically divided into multiple phases, each focused on a specific goal:
{
"steps": [
{
"stepId": "step-1",
"phase": "Analysis Phase",
"description": "Read existing files, analyze project structure",
"action": "read_file"
},
{
"stepId": "step-2",
"phase": "Creation Phase",
"description": "Create new component files",
"action": "create_file"
},
{
"stepId": "step-3",
"phase": "Installation Phase",
"description": "Install necessary dependencies",
"action": "run_command"
},
{
"stepId": "step-4",
"phase": "Validation Phase",
"description": "Run tests to verify functionality",
"action": "run_command"
}
]
}Advantages:
- 🎯 Clear Execution Flow - Each phase has a clear objective
- 🔄 Intra-Phase Error Recovery - Errors automatically fixed within phases
- 📊 Better Progress Tracking - Users see which phase is currently executing
When tool execution fails, the system automatically analyzes errors and generates fix steps:
// 1. Error detected
Error: Cannot apply patch: file not found in context: src/App.tsx
// 2. LLM analyzes error
{
"canRecover": true,
"analysis": "File src/App.tsx not read into context, need to read it first",
"recoverySteps": [
{
"description": "Read src/App.tsx into context",
"action": "read_file",
"tool": "filesystem",
"params": { "path": "src/App.tsx" }
},
{
"description": "Reapply patch to src/App.tsx",
"action": "apply_patch",
"tool": "filesystem",
"params": { /* original params */ }
}
]
}
// 3. Auto-execute fix steps
// 4. Continue original flowFeatures:
- 🔍 Smart Error Analysis - LLM understands error causes and finds root issues
- 🛠️ Auto-Generate Fixes - No manual intervention needed
- 📝 Common Error Patterns - Built-in handling for common errors
- ♻️ Phase-Level Recovery - Errors fixed within phases without blocking overall flow
Traditional agents use logs as context, leading to information redundancy and inaccuracy. FrontAgent uses a structured "facts" system:
Traditional approach (log-based):
Executed operation log:
1. Attempted to read src/App.tsx - failed
2. Attempted to create src/components/Button.tsx - success
3. Attempted to read src/App.tsx - success
4. Installed react-router-dom - success
...(lots of redundant info)
FrontAgent approach (facts-based):
## File System State
### Confirmed Existing Files:
- src/App.tsx
- src/components/Button.tsx
- package.json
### Confirmed Non-Existent Paths:
- src/pages/Login.tsx
## Dependency State
### Installed Packages:
react-router-dom, axios
### Missing Packages:
@types/node
## Created Modules
### component (3 modules):
- src/components/ui/Button.tsx (default export: Button)
- src/components/ui/Card.tsx (default export: Card)
- src/components/layout/Header.tsx (exports: Header, Navigation)
### page (2 modules):
- src/pages/HomePage.tsx (default export: HomePage)
- src/pages/LoginPage.tsx (default export: LoginPage)
### ⚠️ Missing Module References:
- src/pages/HomePage.tsx references non-existent module: ../components/ui/Spinner
## Project State
- Dev server: Running (port: 5173) ← Auto-detected!
- Build status: Success
## Recent Errors
- [apply_patch] Cannot apply patch: file not found in contextAdvantages:
- 📊 Structured Information - Clear state categories (filesystem, dependencies, module graph, project state)
- 🎯 Deduplication - Automatic deduplication using Set/Map
- 💡 Context Awareness - LLM knows which files exist/don't exist
- 🔄 Real-time Updates - Auto-update facts after each tool execution
- 📉 Reduced Token Usage - Concise information reduces LLM input length
- 🔗 Module Tracking - Auto-parse import/export relationships for each created file
Specification Driven Development (SDD) as hard constraints for agent behavior:
# sdd.yaml
version: "1.0"
project:
name: "my-project"
type: "react-spa"
tech_stack:
framework: "react"
version: "^18.0.0"
language: "typescript"
forbidden_packages:
- "jquery"
- "lodash"
code_quality:
max_function_lines: 50
max_file_lines: 300
forbidden_patterns:
- "any"
- "// @ts-ignore"
modification_rules:
protected_files:
- "package.json"
require_approval:
- pattern: "src/api/*"
reason: "API layer changes require approval"Provides file operation MCP tools:
read_file- Read file contentlist_directory- List directory content (supports recursion)create_file- Create new file (two-stage: generate code from description)apply_patch- Apply code patches (two-stage: generate changes from description)search_code- Search codeget_ast- Get AST analysisrollback- Rollback changes
Provides terminal command execution (requires user approval):
run_command- Execute shell commands- Custom working directory support
- Timeout settings
- User approval required before execution
- Auto-distinguish warnings from errors
- Use cases:
npm install,git init,pnpm build, etc.
Provides browser interaction MCP tools:
navigate- Navigate to URLget_page_structure- Get page DOM structureget_accessibility_tree- Get accessibility treeget_interactive_elements- Get interactive elementsclick/type/scroll- Page interactionsscreenshot- Page screenshot
Multi-layer hallucination detection:
- File Existence Check - Verify referenced files exist
- Import Validity Check - Verify imports are resolvable
- Syntax Validity Check - Verify code syntax is correct
- SDD Compliance Check - Verify compliance with SDD constraints
- Language: TypeScript
- Runtime: Node.js 20+
- Package Manager: pnpm
- MCP SDK: @modelcontextprotocol/sdk
- Browser Automation: Playwright
- AST Analysis: ts-morph
- LLM Integration: Vercel AI SDK
frontagent/
├── packages/
│ ├── shared/ # Shared types and utilities
│ ├── sdd/ # SDD control layer
│ ├── mcp-file/ # File operations MCP client
│ ├── mcp-web/ # Web awareness MCP client
│ ├── mcp-shell/ # Shell commands MCP client
│ ├── hallucination-guard/ # Hallucination prevention
│ └── core/ # Agent core (two-stage architecture)
├── apps/
│ └── cli/ # CLI tool
├── examples/
│ ├── sdd-example.yaml # SDD config example
│ └── e-commerce-frontend/ # E-commerce frontend example
└── docs/
├── architecture.md # Architecture design
└── design.md # Original requirements
cd examples
frontagent run "Create an e-commerce frontend project using React + TypeScript + Vite + Tailwind CSS"Agent will automatically:
- Analyze project requirements
- Generate execution plan
- Create package.json and config files
- Request to execute
npm install(requires user approval) - Generate page components and style files
frontagent run "Modify vite.config.ts to add path alias configuration"Agent will:
- Read existing vite.config.ts
- Understand current configuration
- Generate new config code
- Apply minimal patches
frontagent run "Add user authentication feature, including login, registration, and token management"Agent will:
- Analyze existing project structure
- Plan files to create
- Generate auth-related components
- Create API integration code
- Update route configuration
frontagent run "Analyze and optimize homepage loading performance"Agent will:
- Read relevant component code
- Analyze performance issues
- Propose optimization solutions
- Implement code-level optimizations (lazy loading, code splitting, etc.)
frontagent run "Add route configuration in App.tsx"Execution process shows self-healing:
Phase 1: Analysis Phase
✓ Step 1: Read package.json
Phase 2: Creation Phase
✗ Step 2: Modify App.tsx
Error: Cannot apply patch: file not found in context
🔄 Error recovery in progress...
Analysis: App.tsx not read into context
✓ Recovery Step 1: Read src/App.tsx into context
✓ Recovery Step 2: Reapply patch to App.tsx
Phase 3: Validation Phase
✓ Step 3: Run type check
✅ Task complete! Auto-fixed 1 error
Key Features:
- 🎯 Phase-Based Execution - Clear execution phases (Analysis, Creation, Validation)
- 🔄 Auto-Fix - Detected file not read, auto-insert read step
- 📊 Facts Tracking - System knows which files are read/unread
- ⚡ No Retry Needed - One-shot completion, no manual re-runs needed
| Variable | Description | Example Value |
|---|---|---|
PROVIDER |
LLM provider | openai or anthropic |
API_KEY |
API key | sk-... |
MODEL |
Model name | gpt-4 or claude-sonnet-4-20250514 |
BASE_URL |
API endpoint | https://api.openai.com/v1 |
export PROVIDER="openai"
export BASE_URL="https://api.openai.com/v1"
export MODEL="gpt-4"
export API_KEY="sk-..."export PROVIDER="anthropic"
export BASE_URL="https://api.anthropic.com"
export MODEL="claude-sonnet-4-20250514"
export API_KEY="sk-ant-..."# Development mode
pnpm dev
# Type check
pnpm typecheck
# Build
pnpm build
# Clean
pnpm clean- Two-stage agent architecture (Planner + Executor)
- Phase-based execution
- Tool Error Feedback Loop (self-healing)
- Facts-based context system
- Module dependency graph
- Post-generation validation
- Path hallucination detection
- Multi-LLM provider support (OpenAI, Anthropic)
- Shell command execution (with user approval)
- Dynamic code generation (avoid JSON parsing errors)
- MCP tool integration (File, Web, Shell)
- Type auto-normalization (handle LLM output uncertainty)
- Unlimited steps (support complex tasks with many steps)
- LLM schema constraint optimization (multi-strategy auto-fix, smart retry)
- Pre-planning file scan (NEW!)
- Auto dev server port detection (NEW!)
- Enhanced SDD constraints (finer-grained rule control)
- RAG experience base integration (learn from historical tasks)
- GUI agent auto-testing (Playwright-based)
- VS Code plugin (use directly in IDE)
- Multi-agent collaboration (decompose large tasks)
- Custom MCP server support (user-defined tools)
- Code review mode (auto-check code quality)
- Incremental update mode (only modify necessary parts)
Contributions are welcome! Please feel free to submit issues, bug reports, or suggestions.
- Fork this repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
MIT