mate
AGENTS.md111 starsChanged 26 days agoApache-2.0View on GitHub
- Reads credentials
- Installs packages
Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about code style.
Of the AGENTS.md files we read, the 32,671 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.
The file
Show its rules and text
We split this AGENTS.md into the rules it gives an agent
31 rules. About 1 is common, 23 are distinctive, and 7 are very specific to this project.
≈1
Common · estimate
Many files like this have a rule of this kind.
≈23
Distinctive · estimate
This author's own choices. Worth a look.
7
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 7
Use Python 3.8+ for all new files
- Distinctive: line 8
Follow PEP 8 style guidelines with 4-space indentation
- Distinctive: line 9
Use type hints for function parameters and return types
- Distinctive: line 10
Prefer descriptive variable names over comments
- Distinctive: line 11
Use f-strings for string formatting
- Distinctive: line 12
Import statements should be grouped: stdlib, third-party, local imports
- Distinctive: line 16
ALWAYS activate the virtual environment: before running any Python commands
- Very specific: line 17
Use source .venv/bin/activate before running Python scripts, tests, or imports
- Distinctive: line 19
All Python commands should be run within the activated virtual environment
- Very specific: line 50
Use SQLAlchemy ORM for all database operations (models defined in shared/utils/models.py)
- Very specific: line 53
Use DatabaseClient for connection management and pooling
- Distinctive: line 67
Create migrations for every database schema change across all 3 dialects
- Very specific: line 84
RBAC: All agents must implement role validation through allowed_for_roles
- Very specific: line 88
All tools must be constructed through ToolFactory (shared/utils/tools/tool_factory.py)
- Common: line 127
Use environment variables for all API keys, database settings, and system toggles.
- Distinctive: line 173
Write unit tests for all new agent, tool, callback, or route functionality
- Distinctive: line 174
Test both successful and failure scenarios
- Distinctive: line 175
Use mocking for external API and LLM calls
- Very specific: line 179
Always include try-except blocks for database and network operations
- Distinctive: line 187
Use connection pooling for database operations
- Distinctive: line 190
Ensure appropriate indexes on database tables
- Very specific: line 225
Do not create a separate README.md for each feature.
- Distinctive: line 226
Update AGENTS.md when adding new patterns or architectural requirements
- Distinctive: line 232
Before implementing: state assumptions explicitly.
- Distinctive: line 233
If a simpler approach exists, propose it.
- Distinctive: line 237
Avoid unnecessary abstractions for single-use code.
- Distinctive: line 238
No unrequested "flexibility" or premature configurability.
- Distinctive: line 239
If 50 lines cleanly solve a problem, do not write 200 lines.
- Distinctive: line 243
Do not refactor unrelated code or adjust untouched comments/formatting.
- Distinctive: line 246
Every changed line should trace directly to the task.
- Distinctive: line 250
Write or run unit tests to confirm bug fixes and new functionality.
≈ “Common” is an estimate: at least 1 in 5 of the 41,581 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
MATE (Multi-Agent Tree Engine) System Instructions
Project Overview
MATE (Multi-Agent Tree Engine) is a production-ready web platform built on top of Google ADK (with optional LangGraph runtime support) that adds database-driven agent management, multi-LLM support, external OpenAI-compatible agent endpoints, RBAC, MCP integration, token tracking, guardrails, EU AI Act compliance features, and a dashboard UI with Work Room code canvas.
Code Style
- Use Python 3.8+ for all new files
- Follow PEP 8 style guidelines with 4-space indentation
- Use type hints for function parameters and return types
- Prefer descriptive variable names over comments
- Use f-strings for string formatting
- Import statements should be grouped: stdlib, third-party, local imports
- Match existing style when editing existing code
Development Environment
- ALWAYS activate the virtual environment before running any Python commands
- Use
source .venv/bin/activatebefore running Python scripts, tests, or imports - This ensures correct package versions and dependencies are used
- All Python commands should be run within the activated virtual environment
Quick Start
# Setup
python -m venv .venv && source .venv/bin/activate
pip install -r requirements.lock
cp .env.example .env
# Run (auto-applies DB migrations, default SQLite)
python auth_server.py
# Dashboard: http://localhost:8000 (default login: admin/mate)
# Docker alternative
docker-compose upArchitecture
- Agent-Manager-Tool Factory pattern: Centralized initialization and management
- Dual-Server Design:
- Auth Server: Runs on port 8000 (
auth_server.py, FastAPI with HTTP Basic Auth, proxies authenticated requests to the agent server) - Agent Server: Runs on port 8001 (internal, not directly exposed). Runtime framework selectable via
AGENT_FRAMEWORK:adk(default): Google ADK web server (adk_main.py)langgraph: LangGraph runtime (langgraph_main.py+shared/utils/langgraph/, emulates ADK wire contract)
- Auth Server: Runs on port 8000 (
- All requests go through auth server — no direct external access to agent runtime server
- A2A (Agent-to-Agent) and MCP protocol requests are proxied through auth server
- Business logic is strictly separated from database operations
shared/callbacks/hooks into agent lifecycle for RBAC (rbac_callback.py), token tracking (token_usage_callback.py), and guardrails (model_guardrail.py,function_call_guardrail.py)- Rate limiting and request throttling via
server/rate_limit_middleware.py
Database & Migrations
- Use SQLAlchemy ORM for all database operations (models defined in
shared/utils/models.py) - Support PostgreSQL (production), MySQL, and SQLite (development) via
DB_TYPE - Database sessions must be properly closed in
finallyblocks - Use
DatabaseClientfor connection management and pooling - Key Tables:
agents_config: Agent configuration and metadataprojects: Project boundaries and isolationusers: User authentication and role managementtoken_usage_logs: LLM token consumption and cost trackingguardrail_logs: Model and function call guardrail incidentsaudit_logs: Append-only audit events (evidence toward EU AI Act Art. 12)rate_limit_config: Per-user/agent/project rate limit and budget rulesmemory_blocks: Persistent contextual memory blockswidget_api_keys: Public embeddable chat widget keys and allowed originsagent_config_versions: Historical versioning of agent configurations
- Migrations:
- Migrations are stored in
shared/sql/migrations/{postgresql,mysql,sqlite}/ - Create migrations for every database schema change across all 3 dialects
- Database updates should go through the migration system, not through ad-hoc scripts
- Migrations auto-apply on server startup
- Migration CLI commands:
python shared/migrate.py run # Apply pending migrations python shared/migrate.py status # Check migration status python shared/migrate.py create # Create new migration files (all three dialects)
- Migrations are stored in
Agent Development
- Database agents: Stored in
agents_configwith types:'root','llm','custom' - Hardcoded agents: Python classes in
agents/<agent_name>/(__init__.pyandagent.py) - External agents: Agents can point to an existing OpenAI-compatible endpoint via
model_base_urlandmodel_api_keyon the agent row. RBAC, guardrails, audit, token tracking, and widget integration apply identically. Seedocs/user/external-agents.md - Agent Tree:
shared/utils/agent_manager.pymerges database and hardcoded agents, building the hierarchy at startup - Project Scoping: Agents are scoped by project via
projectstable;agents_config.project_idmust be populated for every agent - Planners: Root agents or agents without parents can be configured with planners (
PlanReActPlanner,BuiltInPlanner) viaplanner_configJSON field - RBAC: All agents must implement role validation through
allowed_for_roles - Agent Tree Cloning: Copy root agent hierarchies between projects, maintaining unique naming
Tool Integration
- All tools must be constructed through
ToolFactory(shared/utils/tools/tool_factory.py) - Tool configuration is stored as JSON in
tool_configfield - MCP Tools:
- Configured via
mcp_servers_configJSON usingmcpServers - Stdio transport: specify
command,args, and optionalenv - HTTP / SSE transport: specify
urlfor direct streaming connection without subprocess overhead ${VAR}secret interpolation: references to${ENV_VAR}in MCP configs or endpoint keys resolve dynamically from the server environment, keeping credentials out of the database- Renamed
MCPToolsettoMcpToolsetfor ADK 2.3+ compatibility - See
docs/dev/mcp-servers.mdfor details
- Configured via
- Specialized Tools:
create_agent_tool: Allows agents to inspect, create, or modify other agents at runtime- Memory blocks with semantic search embeddings (
EMBEDDING_MODEL) - Image generation with automated digital source marking
- Browser automation tools (async Playwright with session management)
- Google Drive & Google Search tools (require service account credentials)
- Custom tools defined in
shared/utils/tools/custom_tools.py - Human-in-the-loop (HITL) tool confirmation support
EU AI Act & Compliance
- Article 50 (AI Disclosure): Public chat surfaces (embed widget, standalone chat) inform users they are interacting with an AI (
shared/utils/ai_disclosure.py). Wording is configurable per agent. Waivers require an explicit justification string and write an entry toaudit_logs. Seedocs/user/eu-ai-act.md - Article 50(2) (Marking of Generated Synthetic Content): Generated images carry an XMP packet declaring IPTC digital source type
trainedAlgorithmicMediaprior to saving (shared/utils/content_marking.py) - Article 12 (Audit Logging): Append-only audit trail in
audit_logstable managed byshared/utils/audit_service.pyprovides record-keeping evidence. Retention configurable viaAUDIT_RETENTION_DAYS
Security & Guardrails
- RBAC: Mandatory user role validation before agent access
- Input Sanitization: Sanitize user inputs and tool parameters
- Guardrails: Implement pre-call and post-call model guardrails (
model_guardrail.py) and tool call constraints (function_call_guardrail.py) - Endpoint Security:
- Stored endpoint keys never reach the browser (sentinel values used in API responses)
- Unresolvable
${VAR}secrets abort agent construction rather than falling back to provider defaults - Agent provider keys are isolated from third-party hosts
- Widget Security:
- Origin allowlist enforcement via
WIDGET_ORIGIN_STRICT code_executortool is blocked on widget-exposed agents by default (MATE_ALLOW_CODE_EXECUTOR_ON_WIDGEToverride required)
- Origin allowlist enforcement via
- Production Guard:
MATE_ENV=productionrefuses insecure default credentials and misconfigurations unless explicitly overridden viaMATE_ALLOW_INSECURE_DEFAULTS - Never log sensitive data (API keys, credentials, tokens)
Environment Configuration
Use environment variables for all API keys, database settings, and system toggles.
| Variable | Purpose | Default / Options |
AGENT_FRAMEWORK | Agent runtime engine | adk (default) or langgraph |
DB_TYPE | Database dialect | sqlite (default), postgresql, mysql |
DB_PATH | Path to SQLite DB file | e.g. shared/sql/mate.db |
DB_HOST, DB_PORT, DB_NAME, DB_USER, DB_PASSWORD | PostgreSQL / MySQL credentials | Required if DB_TYPE != sqlite |
GOOGLE_API_KEY | Google Gemini API key (primary LLM) | Required for Gemini models |
OPENROUTER_API_KEY | OpenRouter API key | Required if routing through OpenRouter |
OPENAI_API_KEY, ANTHROPIC_API_KEY | Additional provider keys via LiteLLM | Optional |
MODEL_TYPE | Primary model provider format | gemini or litellm |
AUTH_USERNAME / AUTH_PASSWORD | Dashboard HTTP Basic Auth credentials | Default: admin / mate |
MATE_ENV | Operational environment | development (default) or production |
MATE_ALLOW_INSECURE_DEFAULTS | Override production startup security checks | false |
ALLOWED_ORIGINS | Comma-separated CORS allowlist | e.g. http://localhost:3000 |
TRUSTED_PROXY_HOSTS | Proxy hosts trusted for X-Forwarded-* headers | Optional |
OAUTH_ALLOWED_DOMAINS / OAUTH_ALLOWED_EMAILS | Restrict SSO login domains/emails | Unset allows any provider user |
TOKEN_TTL_HOURS | Personal Access Token / Bearer token lifetime | 24 |
WIDGET_ORIGIN_STRICT | Enforce widget key origin allowlist strictly | false |
MATE_ALLOW_CODE_EXECUTOR_ON_WIDGET | Allow code executor on widget-linked agents | false |
WIDGET_LEGACY_ADMIN_KEY | Transitional support for widget key on admin API | false |
ADK_HOST / ADK_PORT | ADK server address | 127.0.0.1:8001 |
ARTIFACT_SERVICE | Artifact storage provider | local_folder, supabase, s3 |
EMBEDDING_MODEL | Model for memory block semantic search | gemini/gemini-embedding-001 |
RATE_LIMIT_ENABLED | Enable rate limiting and budgets | false |
ALERTS_ENABLED / ALERTS_INTERVAL_SECONDS | Alert rules on agent errors/bursts | false / 60 |
OTEL_TRACING_ENABLED | OpenTelemetry distributed tracing (ADK) | false |
LANGSMITH_TRACING / LANGSMITH_API_KEY | LangSmith run tracing (LangGraph) | false |
AUDIT_RETENTION_DAYS | Retention period for audit logs | e.g. 365 |
MATE_AI_DISCLOSURE | Custom default text for Art. 50 disclosure | Optional |
Testing
- Tests live in
shared/test/withtest_prefix - ALWAYS run tests as module within activated virtual environment:
# Run all tests python -m unittest discover -s shared/test -t . -p "test_*.py" -v # Run single test module python -m unittest shared.test.test_agent_manager_simple -v # Run with test coverage coverage run -m unittest discover -s shared/test -t . -p "test_*.py" coverage report - Write unit tests for all new agent, tool, callback, or route functionality
- Test both successful and failure scenarios
- Use mocking for external API and LLM calls
- Include integration tests for agent hierarchies and external endpoints
Error Handling
- Always include
try-exceptblocks for database and network operations - Log errors using the configured logger
- Provide fallback agents or safe defaults when agent initialization fails
- Return
Nonefor failed agent initialization rather than crashing the server - Include descriptive error messages in logs
Performance & Monitoring
- Cache initialized agents in
AgentManager - Use connection pooling for database operations
- Implement token usage monitoring for cost tracking (
token_usage_logs) - Optimize tool creation to avoid redundant initialization
- Ensure appropriate indexes on database tables
- Distributed tracing with OpenTelemetry (ADK runtime) or LangSmith (LangGraph runtime)
- Rule-based alerts for agent failure rates, guardrail bursts, and budget overruns
MCP Integration
- Integrated MCP (Model Context Protocol) server at
/mcp - Full protocol support with Server-Sent Events (SSE) and HTTP streaming
- Agents can act both as MCP servers and consume external MCP servers
- Secure authentication headers and environment variable secret interpolation (
${VAR})
Dashboard & Web Interface
- Web-based dashboard under
/dashboard/with API endpoints under/dashboard/api/ - Jinja2 templates in
templates/and static assets instatic/ - Vue-style JavaScript with no build step required; PWA-ready (
static/manifest.json) - Work Room & Code Canvas: Side-by-side chat with live code canvas supporting Ace editor, sandboxed HTML/JS/CSS iframe execution, Pyodide Python, and DartPad
- Public embeddable chat widget (
/widget/) and standalone chat (/standalone/) - Agent management UI requires selecting a project before listing or editing agents
Important Documentation
README.md— Project overview, architecture, and quick startdocs/— Guides and reference, also served in the dashboard at/dashboard/docs(seedocs/README.md). In-depth feature guides include:docs/user/eu-ai-act.md— EU AI Act compliance guide (Art. 50, Art. 50(2), Art. 12)docs/user/external-agents.md— External OpenAI-compatible agent endpoint setupdocs/dev/mcp-servers.md— MCP server and client integration (stdio, HTTP/SSE,${VAR})docs/dev/langgraph-runtime.md— LangGraph alternative runtime setup and wire contractdocs/dev/openai-compatibility.md— OpenAI-compatible API (/v1/chat/completions)docs/user/slack.md— Slack bot integration and Block Kit card translationdocs/user/widget.md— Embeddable widget integration and origin securitydocs/user/rate-limits.md— Rate limiting, token budgets, and cost controlsdocs/dev/alerts.md— Notification rules on agent errors and budget thresholdsdocs/dev/tracing.md— OpenTelemetry and LangSmith tracing setupdocs/dev/agent-wizard.md— Public self-service agent builder wizarddocs/dev/template-format.md— Agent templates and presets
shared/sql/README.md— Database schema reference- Rules:
- Do not create a separate README.md for each feature; add a guide under
docs/user/ordocs/dev/with acovers:list, and update the guides that cover the code you change - Update
AGENTS.mdwhen adding new patterns or architectural requirements
- Do not create a separate README.md for each feature; add a guide under
Engineering & Coding Guidelines
1. Think Before Coding
- Don't assume. Don't hide confusion. Surface tradeoffs.
- Before implementing: state assumptions explicitly; if uncertain or multiple interpretations exist, ask or present options.
- If a simpler approach exists, propose it.
2. Simplicity First
- Minimum code that solves the problem. Nothing speculative.
- Avoid unnecessary abstractions for single-use code.
- No unrequested "flexibility" or premature configurability.
- If 50 lines cleanly solve a problem, do not write 200 lines.
3. Surgical Changes
- Touch only what you must. Clean up only your own mess.
- Do not refactor unrelated code or adjust untouched comments/formatting.
- Match existing style and idioms in the file.
- Clean up unused imports/variables created by your changes, but do not delete pre-existing dead code unless requested.
- Every changed line should trace directly to the task.
4. Goal-Driven Execution
- Define success criteria. Verify thoroughly.
- Write or run unit tests to confirm bug fixes and new functionality.
- For multi-step tasks, define a concise verification plan and execute step by step.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

