agentleFS
antivantiv/mate/AGENTS.md

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.

  • In this repository2 other files it gives its agents.

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
  1. Distinctive:

    Use Python 3.8+ for all new files

    line 7
  2. Distinctive:

    Follow PEP 8 style guidelines with 4-space indentation

    line 8
  3. Distinctive:

    Use type hints for function parameters and return types

    line 9
  4. Distinctive:

    Prefer descriptive variable names over comments

    line 10
  5. Distinctive:

    Use f-strings for string formatting

    line 11
  6. Distinctive:

    Import statements should be grouped: stdlib, third-party, local imports

    line 12
  7. Distinctive:

    ALWAYS activate the virtual environment: before running any Python commands

    line 16
  8. Very specific:

    Use source .venv/bin/activate before running Python scripts, tests, or imports

    line 17
  9. Distinctive:

    All Python commands should be run within the activated virtual environment

    line 19
  10. Very specific:

    Use SQLAlchemy ORM for all database operations (models defined in shared/utils/models.py)

    line 50
  11. Very specific:

    Use DatabaseClient for connection management and pooling

    line 53
  12. Distinctive:

    Create migrations for every database schema change across all 3 dialects

    line 67
  13. Very specific:

    RBAC: All agents must implement role validation through allowed_for_roles

    line 84
  14. Very specific:

    All tools must be constructed through ToolFactory (shared/utils/tools/tool_factory.py)

    line 88
  15. Common:

    Use environment variables for all API keys, database settings, and system toggles.

    line 127
  16. Distinctive:

    Write unit tests for all new agent, tool, callback, or route functionality

    line 173
  17. Distinctive:

    Test both successful and failure scenarios

    line 174
  18. Distinctive:

    Use mocking for external API and LLM calls

    line 175
  19. Very specific:

    Always include try-except blocks for database and network operations

    line 179
  20. Distinctive:

    Use connection pooling for database operations

    line 187
  21. Distinctive:

    Ensure appropriate indexes on database tables

    line 190
  22. Very specific:

    Do not create a separate README.md for each feature.

    line 225
  23. Distinctive:

    Update AGENTS.md when adding new patterns or architectural requirements

    line 226
  24. Distinctive:

    Before implementing: state assumptions explicitly.

    line 232
  25. Distinctive:

    If a simpler approach exists, propose it.

    line 233
  26. Distinctive:

    Avoid unnecessary abstractions for single-use code.

    line 237
  27. Distinctive:

    No unrequested "flexibility" or premature configurability.

    line 238
  28. Distinctive:

    If 50 lines cleanly solve a problem, do not write 200 lines.

    line 239
  29. Distinctive:

    Do not refactor unrelated code or adjust untouched comments/formatting.

    line 243
  30. Distinctive:

    Every changed line should trace directly to the task.

    line 246
  31. Distinctive:

    Write or run unit tests to confirm bug fixes and new functionality.

    line 250

≈ “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.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
AGENTS.md

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/activate before 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 up

Architecture

  • 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)
  • 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 finally blocks
  • Use DatabaseClient for connection management and pooling
  • Key Tables:
    • agents_config: Agent configuration and metadata
    • projects: Project boundaries and isolation
    • users: User authentication and role management
    • token_usage_logs: LLM token consumption and cost tracking
    • guardrail_logs: Model and function call guardrail incidents
    • audit_logs: Append-only audit events (evidence toward EU AI Act Art. 12)
    • rate_limit_config: Per-user/agent/project rate limit and budget rules
    • memory_blocks: Persistent contextual memory blocks
    • widget_api_keys: Public embeddable chat widget keys and allowed origins
    • agent_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)

Agent Development

  • Database agents: Stored in agents_config with types: 'root', 'llm', 'custom'
  • Hardcoded agents: Python classes in agents/<agent_name>/ (__init__.py and agent.py)
  • External agents: Agents can point to an existing OpenAI-compatible endpoint via model_base_url and model_api_key on the agent row. RBAC, guardrails, audit, token tracking, and widget integration apply identically. See docs/user/external-agents.md
  • Agent Tree: shared/utils/agent_manager.py merges database and hardcoded agents, building the hierarchy at startup
  • Project Scoping: Agents are scoped by project via projects table; agents_config.project_id must be populated for every agent
  • Planners: Root agents or agents without parents can be configured with planners (PlanReActPlanner, BuiltInPlanner) via planner_config JSON 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_config field
  • MCP Tools:
    • Configured via mcp_servers_config JSON using mcpServers
    • Stdio transport: specify command, args, and optional env
    • HTTP / SSE transport: specify url for 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 MCPToolset to McpToolset for ADK 2.3+ compatibility
    • See docs/dev/mcp-servers.md for details
  • 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 to audit_logs. See docs/user/eu-ai-act.md
  • Article 50(2) (Marking of Generated Synthetic Content): Generated images carry an XMP packet declaring IPTC digital source type trainedAlgorithmicMedia prior to saving (shared/utils/content_marking.py)
  • Article 12 (Audit Logging): Append-only audit trail in audit_logs table managed by shared/utils/audit_service.py provides record-keeping evidence. Retention configurable via AUDIT_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_executor tool is blocked on widget-exposed agents by default (MATE_ALLOW_CODE_EXECUTOR_ON_WIDGET override required)
  • Production Guard: MATE_ENV=production refuses insecure default credentials and misconfigurations unless explicitly overridden via MATE_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.

VariablePurposeDefault / Options
AGENT_FRAMEWORKAgent runtime engineadk (default) or langgraph
DB_TYPEDatabase dialectsqlite (default), postgresql, mysql
DB_PATHPath to SQLite DB filee.g. shared/sql/mate.db
DB_HOST, DB_PORT, DB_NAME, DB_USER, DB_PASSWORDPostgreSQL / MySQL credentialsRequired if DB_TYPE != sqlite
GOOGLE_API_KEYGoogle Gemini API key (primary LLM)Required for Gemini models
OPENROUTER_API_KEYOpenRouter API keyRequired if routing through OpenRouter
OPENAI_API_KEY, ANTHROPIC_API_KEYAdditional provider keys via LiteLLMOptional
MODEL_TYPEPrimary model provider formatgemini or litellm
AUTH_USERNAME / AUTH_PASSWORDDashboard HTTP Basic Auth credentialsDefault: admin / mate
MATE_ENVOperational environmentdevelopment (default) or production
MATE_ALLOW_INSECURE_DEFAULTSOverride production startup security checksfalse
ALLOWED_ORIGINSComma-separated CORS allowliste.g. http://localhost:3000
TRUSTED_PROXY_HOSTSProxy hosts trusted for X-Forwarded-* headersOptional
OAUTH_ALLOWED_DOMAINS / OAUTH_ALLOWED_EMAILSRestrict SSO login domains/emailsUnset allows any provider user
TOKEN_TTL_HOURSPersonal Access Token / Bearer token lifetime24
WIDGET_ORIGIN_STRICTEnforce widget key origin allowlist strictlyfalse
MATE_ALLOW_CODE_EXECUTOR_ON_WIDGETAllow code executor on widget-linked agentsfalse
WIDGET_LEGACY_ADMIN_KEYTransitional support for widget key on admin APIfalse
ADK_HOST / ADK_PORTADK server address127.0.0.1:8001
ARTIFACT_SERVICEArtifact storage providerlocal_folder, supabase, s3
EMBEDDING_MODELModel for memory block semantic searchgemini/gemini-embedding-001
RATE_LIMIT_ENABLEDEnable rate limiting and budgetsfalse
ALERTS_ENABLED / ALERTS_INTERVAL_SECONDSAlert rules on agent errors/burstsfalse / 60
OTEL_TRACING_ENABLEDOpenTelemetry distributed tracing (ADK)false
LANGSMITH_TRACING / LANGSMITH_API_KEYLangSmith run tracing (LangGraph)false
AUDIT_RETENTION_DAYSRetention period for audit logse.g. 365
MATE_AI_DISCLOSURECustom default text for Art. 50 disclosureOptional

Testing

  • Tests live in shared/test/ with test_ 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-except blocks for database and network operations
  • Log errors using the configured logger
  • Provide fallback agents or safe defaults when agent initialization fails
  • Return None for 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 in static/
  • 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 start
  • docs/ — Guides and reference, also served in the dashboard at /dashboard/docs (see docs/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 setup
    • docs/dev/mcp-servers.md — MCP server and client integration (stdio, HTTP/SSE, ${VAR})
    • docs/dev/langgraph-runtime.md — LangGraph alternative runtime setup and wire contract
    • docs/dev/openai-compatibility.md — OpenAI-compatible API (/v1/chat/completions)
    • docs/user/slack.md — Slack bot integration and Block Kit card translation
    • docs/user/widget.md — Embeddable widget integration and origin security
    • docs/user/rate-limits.md — Rate limiting, token budgets, and cost controls
    • docs/dev/alerts.md — Notification rules on agent errors and budget thresholds
    • docs/dev/tracing.md — OpenTelemetry and LangSmith tracing setup
    • docs/dev/agent-wizard.md — Public self-service agent builder wizard
    • docs/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/ or docs/dev/ with a covers: list, and update the guides that cover the code you change
    • Update AGENTS.md when adding new patterns or architectural requirements

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.

Download now (ZIP)

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
What did you use it for? e.g. Reviewing pull requests in a Rails app

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.