Skip to content

Repository files navigation

πŸ€– MCP Agent Stack

A fully autonomous local-first AI agent with 18 tools, 6 LangGraph workflows, a 3-tier LLM role system, and a self-improving memory β€” running on your hardware, with optional cloud LLM escalation.

Built on MCP (Model Context Protocol), LM Studio (local LLM inference), ChromaDB (vector memory), SearXNG (self-hosted search), and LangGraph (state-machine orchestration). The default stack runs entirely on your machine β€” no API keys required. Cloud LLMs (OpenAI, DeepSeek, Mistral, Qwen, Kimi, Claude, Gemini, Z.ai, MiMo) are supported as opt-in escalation paths via the consult tool and CONSULTOR_MODEL role.

Python 3.11+ Node.js 18+ MCP LM Studio LangGraph

Prerequisites: Python 3.11+, Node.js 18+, Git on PATH, LM Studio with 3 role models loaded (Planner, Executor, Router).

Windows note: PDF report generation requires the GTK3 Runtime.

Jump to Quick Start Β· Repo Structure Β· AI Contributor Guide


🌟 What Makes This Different

Differentiator What it means
3-tier role system with fallback chains Not just Planner / Executor / Router β€” each role has sub-roles (summarize, extract, research, critique, analyze, code, review, refactor, test, document, classify, route, vision) with per-role model overrides and automatic fallback to the parent role. Tune models per task, not per agent.
Self-improving memory Three ChromaDB collections (episodic / semantic / procedural) with a background Sleep & Learn daemon that distills rules from execution traces and injects them into future Planner prompts. The agent gets better at your workflows over time, autonomously.
Atomic-action meta-tools 18 tools expose ~130 atomic actions via @meta_tool + DISPATCH registry. Adding an action = creating one file with @register_action. Zero wiring in server.py or registry.py. See Β§ Tools below.
Real TDD autocode The autocode workflow runs real pytest subprocesses, scopes changes to git branches, blocks edits to protected files, and rolls back on failure. 29-node LangGraph state machine with a debug loop + optional swarm fallback.
Local-first, cloud-optional Default = LM Studio + SearXNG + ChromaDB, fully offline. Opt-in cloud escalation via consult tool and per-role provider routing (PLANNER_MODEL=openai works). 10 supported LLM providers.
Tz-aware scheduling + offline recovery The schedule tool handles cron/interval/one-shot jobs with standard cron semantics (0=Sunday), iCal calendar sync, and catch-up of missed fires while the server was offline (misfire policies: skip / fire_last / fire_all). All time operations are tz-aware via core/time_utils.py.
5-file documentation standard Every component has INDEX / ARCHITECTURE / API / CHANGELOG / INSTRUCTIONS docs. AI editors can read just INSTRUCTIONS.md to know what not to break. See docs/DOCUMENTATION_GUIDE.md.

πŸš€ Quick Start

# 1. Clone & venv
git clone https://github.com/brunogcar/agent agent
cd agent
python -m venv venv
.\venv\Scripts\Activate.ps1   # Windows | source venv/bin/activate on Linux/macOS

# 2. Install
python -m pip install --upgrade pip
pip install -r requirements.txt
playwright install             # required for browser tool

# 3. Configure
copy .env.example .env         # then edit model names + GATEWAY_SECRET
# Tip: check http://localhost:1234/v1/models for your exact LM Studio model IDs

# 4. Run
.\venv\Scripts\python.exe server.py

Required .env changes:

  1. PLANNER_MODEL, EXECUTOR_MODEL, ROUTER_MODEL β€” match exact IDs from http://localhost:1234/v1/models.
  2. GATEWAY_SECRET=changeme β€” must be changed or the REST API refuses to start in production.
  3. AGENT_ROOT, WORKSPACE_ROOT β€” point to your actual local directories.

Optional β€” Codebase Embeddings (semantic search): The understand workflow can index code for semantic search ("find the function that does X"). To enable it:

  1. Download All-MiniLM-L6-v2-Embedding-GGUF (q8, 25MB) in LM Studio
  2. Load it under Models β†’ Embeddings
  3. Set EMBEDDING_MODEL in .env to match the model name LM Studio shows

If the embedding model isn't loaded, the workflow skips vector indexing gracefully β€” graph edges still work, just no semantic search. See understand API docs for details.

Connect to an MCP host (LM Studio, Claude Desktop, Cursor): copy mcp.json into your host's MCP settings and update the command to point at your venv/Scripts/python.exe. See Β§ Configure MCP Servers below for details.


πŸ›οΈ System Architecture

graph TD
    A["User (CLI / MCP Host / REST Gateway)"] -->|"MCP stdio or HTTP"| B["server.py"]
    B --> C["registry.py β€” @tool auto-discovery"]
    C --> D["18 Meta-tools"]
    C --> E["Skills Dispatcher<br/>(B3, CVM)"]
    C --> F["6 LangGraph Workflows"]
    D & E & F --> G["core/ β€” 13 subsystems"]

    G -->|"role-based dispatch"| H["core/llm.py"]
    H --> I["Planner tier<br/>long-context, vision"]
    H --> J["Executor tier<br/>code, JSON, synthesis"]
    H --> K["Router tier<br/>fast classification"]

    G --> L["core/memory_engine.py<br/>3-collection ChromaDB"]
    G --> M["core/sleep_learn/<br/>background rule distillation"]
    G --> N["core/tracer.py<br/>JSONL β†’ stderr"]
    G --> O["core/gateway.py<br/>FastAPI REST"]

    I & J & K -->|"OpenAI-compatible API"| P["LM Studio<br/>localhost:1234"]
    I & J & K -.->|"opt-in cloud"| Q["OpenAI / DeepSeek / Mistral /<br/>Qwen / Kimi / Claude / Gemini /<br/>Z.ai / MiMo"]
Loading

3-Tier Role System

The agent doesn't just use 3 models β€” it has a 3-tier role hierarchy with per-role model overrides and automatic fallback. Configure any role to use a local LM Studio model or a cloud provider name (e.g., RESEARCH_MODEL=openai).

Tier Role Purpose Default Context Timeout Sub-roles (fallback to parent)
Planner planner Orchestration, memory summaries, vision, long-context reasoning 160k 90s vision
Executor executor Code generation, strict JSON, data analysis, synthesis 16k 120s summarize, extract, research, critique, analyze, code, review, refactor, test, document
Router router Ultra-fast task classification and tool selection 4k 15s classify, route
Consultor (opt-in) consultor Cloud LLM advisory β€” escalation path when local models are insufficient β€” β€” β€”

Each sub-role can override its parent's model via *_MODEL env vars. Empty values fall back to the parent role. See docs/core/CONFIG.md and docs/core/LLM.md for the full routing matrix.


πŸ”„ Workflows

Long-running, multi-step orchestration pipelines built on LangGraph. Triggered via workflow(action="run", type="...", goal="...") or the REST API. All workflows are at v1.0+.

Workflow Functionality
Research Quick info gathering: single search β†’ parallel scrape β†’ synthesis. SSRF protection, citation tracking.
Deep Research Iterative multi-faceted research with ReAct loop, convergence detection, and budget tracking.
Data Pandas/numpy analysis, calculations, dataset generation. Sandboxed run_data mode.
Autocode Autonomous TDD code generation with git scoping, surgical patching, debug loop, and optional swarm fallback. 29 nodes.
Understand Build a deterministic codebase knowledge graph via AST parsing + doc indexing. Semantic search via embeddings.
Autoresearch Autonomous metric optimization (evolutionary loop) β€” proposes changes to a target file, keeps/discards based on a metric.

All workflows emit structured traces to logs/agent_*.jsonl and follow the memory bookend pattern (recall at start, store at end). See docs/WORKFLOWS.md for the full comparison and return schema.


πŸ› οΈ Tools

18 meta-tools expose ~130 atomic actions. Auto-discovered via @tool + @meta_tool + @register_action β€” zero manual wiring. Each tool follows the *_ops/ subpackage pattern.

Tool Functionality
web SearXNG search, BeautifulSoup scraping, SSRF protection, parallel search_and_read
tavily AI-ranked search, bulk URL extraction, keyless mode, API budget tracking
browser Playwright automation (20 atomic actions), session isolation, screenshot-on-failure
python Dual-mode execution: strict AST sandbox (run) or data-science subprocess (run_data)
file 25+ atomic FS actions: CRUD, directory traversal, document parsing, SQLite FTS
git 20+ atomic VCS actions: commit, diff, rollback, snapshot, branch/tag management
github 16 actions: PR + issue + release workflow + push/pull (httpx direct, not PyGithub)
cli 4-layer NL→shell dispatch: patterns → shell whitelist → router LLM → executor LLM
report 12 atomic actions: charts, maps, dashboards, diagrams, tables, export to PDF/PNG/xlsx + skill adapters
vision Multimodal image analysis via cfg.vision_model, 3 input sources, JSON mode
memory LLM-facing memory I/O: store, recall, delete, prune, summarize, janitor
agent 15 specialist sub-roles: classify, route, research, code, review, critique, plan, etc.
consult Cloud LLM advisory (opt-in, kill-switch, rate-limit guard) β€” 3 actions
swarm Multi-model consensus across cloud providers β€” 5 actions (consensus/race/vote/compare/list_providers)
parallel Concurrent tool execution with PARALLEL_SAFE allowlist β€” 3 actions (run/race/pipeline)
notify Cross-platform desktop alerts + APScheduler reminders (tz-aware), graceful console fallback
schedule Cron/interval/one-shot jobs + iCal sync, delivered via notify; offline missed-fire recovery
workflow LangGraph workflow launcher with auto-routing and resume support

See docs/TOOLS.md for the full catalog, return schema, security rules, and testing commands.


🧠 Core Subsystems

The core/ module is the foundation layer β€” 13 subsystems that do the thinking, remembering, and orchestration.

Subsystem Purpose
Config Singleton .env loader, 9 builders, tiered model roles, path hierarchy, fail-fast validation
LLM Role-based dispatch, circuit breakers, 10 providers (LM Studio + 9 cloud), JSON parsing
Memory 3-collection ChromaDB, 4-layer dedup, decay scoring, two learning subsystems
Router 15s timeout classification, model + heuristic + swarm fallback, confidence guard
Gateway FastAPI REST API, Bearer auth, rate limiting, SQLite task store
Runtime Activity tracking, watchdog, health checks, cancellation guards, task runner
Sleep & Learn Background daemon: trace observation β†’ rule distillation β†’ prompt injection
Knowledge Graph AST-based codebase analysis, dependency graphs, test targeting, project isolation
Tracer Structured JSONL logging, trace ID propagation, MCP stdio safety, bounded memory
Observability Tracer engine + reader + Prometheus metrics (graceful degradation)
NET HTTP error classification, SSRF protection, retry/backoff, API budget tracking
Context Pruner Cognitive context budgeting for LLM calls
Standalone Shared utilities: contracts.py, path_guard.py, time_utils.py, utils.py, citations.py, br_validator.py, json_extract.py

See docs/CORE.md for the full architecture layers and module map. See docs/STRUCTURE.md for the complete file/folder layout.


πŸ“Š Data Sources

Data sources are the raw data ingestion + query layer. Each sub-domain syncs data from an external API (CVM, B3) into a local SQLite database, then provides query modes for reading it. Single entry point: data_source(domain, sub_domain, mode, params).

CVM (Brazilian SEC)

Sub-domain What Storage
DFP Annual financial statements (DemonstraΓ§Γ΅es Financeiras Padronizadas) memory_db/cvm/dfp.db
ITR Quarterly financial statements (cumulative YTD) memory_db/cvm/itr.db
FRE FormulΓ‘rio de ReferΓͺncia β€” governance, shareholders, compensation memory_db/cvm/fre.db
IPE Material events index (earnings, dividends, M&A filings) memory_db/cvm/ipe.db
CAD Company register (CNPJ β†’ CD_CVM + names) memory_db/cvm/cad.db
VLMO Insider trading disclosures (Valores MobiliΓ‘rios) memory_db/cvm/vlmo.db
CGVN Governance practices (CΓ³digo de GovernanΓ§a e Melhores PrΓ‘ticas) memory_db/cvm/cgvn.db
FCA Registration form (ticker β†’ CNPJ + listing segment + ADR) β€” primary bridge resolver memory_db/cvm/fca.db
Bridge B3-CVM identity bridge (FCA first β†’ bridge.db β†’ B3 API β†’ ISIN fallback) memory_db/cvm/bridge.db

B3 (Brazilian Stock Exchange)

Sub-domain What Storage
API Market data: instruments, trades, derivatives (paginated JSON API) memory_db/b3/{table}.db
DIVIDENDS Corporate actions: cash/stock dividends, subscriptions (per-ticker) memory_db/b3/dividends.db

See docs/DATA_SOURCES.md for the full architecture, sync commands, and the zero-maintenance auto-discovery design.


🧩 Skills

Skills are analytical views that combine multiple data sources with domain reasoning. They are read-only (no sync) and sit on top of data_sources/. Single entry point: skill(domain, sub_domain, mode, params).

Skill Modes Combines
financials quarterly (default), annual, complete, summary DFP (annual) + ITR (quarterly cumulative) + DVA (proventos) β€” rapina-style
shareholders shareholders, free_float, equity_structure, summary FRE (named shareholders, free float) + DFP (equity structure in BRL)
dividends history, annual, payable, announcements, summary B3 (individual events) + DFP DVA (annual totals) + DFP BPP (payable) + IPE (filings)
valuation ratios, summary b3 price + DFP/ITR TTM financials + FRE shares β€” P/L, P/VPA, EV, ROIC, Graham Number
comparison side_by_side, summary, growth Orchestrates financials + valuation + dividends per ticker β€” multi-ticker compare
screener sector, compare CAD + bridge + valuation + financials + FCA (listing segment) β€” sector peers + medians
insider history, by_role, summary VLMO (insider trading disclosures) β€” insider buy/sell + sentiment
governance practices, score, by_chapter CGVN (governance practices) β€” % adopted, chapter breakdown
investsite indicators, statements, events, summary, listing investsite.com.br (live web scraping β€” valuation ratios, full statements, CVM event links)

Skills call data_source query engines directly (no JSON round-trip). The bridge auto-syncs on first ticker query (resolve_company(auto_sync=True)).

See docs/SKILLS.md for the full skills architecture and how to add new skills.


πŸ“Š Benchmark

The benchmark/ package measures which local model is best for each role. Useful when swapping models in LM Studio β€” find the right fit per role instead of guessing.

# Run all easy router tasks, 3 runs each, vs a pinned baseline
.\venv\Scripts\python -m benchmark --role router --depth easy --runs 3 --baseline baseline.json

# Compare two models on executor tasks
.\venv\Scripts\python -m benchmark --role executor --depth easy --compare lfm2-1.2b-tool,gemma-2-2b-it

# Compare raw vs agent-mode scores side-by-side
.\venv\Scripts\python -m benchmark --role code --depth easy --dual-mode

# List all available roles + task counts
.\venv\Scripts\python -m benchmark --list

Features: 81 tasks (40 executor + 31 router + 10 planner), dual-mode (raw + agent-mode) testing, side-by-side comparison tables with green-highlighted winners, 6 failure categories (timeout, llm_error, exception, empty_output, format_error, wrong_answer), variance tracking with wobble flag (Οƒ > 20), baseline pinning with regression thresholds, and automatic best-model-per-role recommendation. See docs/BENCHMARK.md for the full task catalog and v1.5 changelog.


πŸ“ˆ Project Status

The agent is actively developed. All tools, workflows, and core subsystems are at v1.0+ β€” the pre-v1 refactoring is complete. Individual components are versioned independently (see each component's CHANGELOG.md).

v1.0+ (stable):

  • 18 tools β€” all refactored to the @meta_tool + *_ops/ subpackage pattern (latest: schedule v1.0, notify v1.1)
  • 6 workflows β€” all LangGraph-based with *_impl/ subpackages (latest: autocode v3.1, autoresearch v1.2.2)
  • 13 core subsystems β€” all with thin-facade + *_backend/ pattern (latest: config v1.0, router v1.0, observability reorg)
  • core/time_utils.py β€” shared tz-aware time module (replaces the external @mcpcentral/mcp-time MCP dependency)

Recent highlights:

  • schedule tool (v1.0) β€” cron/interval/one-shot + iCal sync + offline missed-fire recovery
  • notify v1.1 β€” swapped to core/time_utils (tz-aware), DOW fix (0=Sunday), store moved to agent_root/
  • swarm tool (v1.0) β€” multi-model consensus across 9 cloud providers
  • github tool (v1.0) β€” 16 PR/issue/release actions

πŸ“š Documentation

Every component follows the 5-file documentation standard: INDEX (overview) Β· ARCHITECTURE (file map + design decisions) Β· API (contract) Β· CHANGELOG (history + roadmap) Β· INSTRUCTIONS (AI editing rules). See docs/DOCUMENTATION_GUIDE.md for the full standard.

Top-Level Indexes

Doc Covers
docs/STRUCTURE.md Repo layout reference β€” where everything lives, naming conventions, patterns
docs/TOOLS.md All 18 tools β€” status, safety rules, comparison
docs/WORKFLOWS.md All 6 workflows β€” status, comparison, return schema
docs/CORE.md All 13 core subsystems β€” architecture layers, module map
docs/DATA_SOURCES.md CVM + B3 data sources β€” sync, query, bridge
docs/SKILLS.md Skills layer β€” analytical views combining data sources
docs/BENCHMARK.md Role benchmarking tool, task catalog
docs/SESSION_WORKFLOW.md AI-assisted dev session workflow (how to work on this repo)
docs/DOCUMENTATION_GUIDE.md The 5-file standard itself

Per-Component Deep Dives

Each tool, core subsystem, and workflow has its own folder under docs/<area>/<component>/ containing ARCHITECTURE.md, API.md, CHANGELOG.md, and INSTRUCTIONS.md. Start from the indexes above to navigate.

System Prompts

docs/system_prompts/ defines the exact output schemas and guardrails each role expects. Read these before modifying workflow logic β€” they are the contract between the LLM and the agent's tooling.


πŸ€– AI Contributor Guide

ATTENTION AI ASSISTANTS: Read this section before writing code in this repo.

Where to look first

  1. docs/STRUCTURE.md β€” where things live (the repo map)
  2. docs/SESSION_WORKFLOW.md β€” the 5-step change workflow (investigate β†’ propose β†’ build zip β†’ commands β†’ git)
  3. The relevant component's INSTRUCTIONS.md (e.g., docs/tools/cli/INSTRUCTIONS.md) β€” tells you what NOT to break
  4. The component's ARCHITECTURE.md β€” tells you where things live
  5. docs/DOCUMENTATION_GUIDE.md β€” tells you how docs are structured

The 5-step session workflow

Every change follows this workflow (see docs/SESSION_WORKFLOW.md for the full guide):

  1. Investigate first β€” read the actual code + docs before proposing anything. Verify claims against source (docs drift).
  2. Propose a plan β€” list files to change, describe changes + design decisions, identify findings by priority (P0/P1/P2/P3). Wait for greenlight.
  3. Build a zip β€” repo-relative paths, no wrapper folder. Deliver to /home/z/my-project/zips/<feature>-v<ver>.zip.
  4. Give PowerShell commands β€” extract + copy + compile-check (emoji βœ…/❌ format) + component tests + full suite.
  5. Give git commands β€” git add + commit message (via commit -F commitmsg.txt) + git push, in a single block.

Hard rules:

  • Never change code without greenlight β€” propose first, wait for approval
  • Never write .bak files β€” forbidden by project rules
  • Never rewrite entire files when editing β€” surgical edits only
  • Never use bare pytest β€” always python.exe -m pytest
  • Never omit -W error from pytest commands
  • Never put git commands in the extract/copy block β€” keep them separate
  • Always investigate before proposing β€” read the actual code, don't guess
  • Always provide compile-check + test commands
  • Always update CHANGELOG.md for any version change

Agent self-preservation (hard rules for autonomous operation)

These prevent the local agent from breaking its own runtime. AI assistants helping the developer may suggest changes to protected files when explicitly asked.

  • MCP stdio safety: NEVER write to stdout in server.py, tools/, or workflows/. All logging goes to stderr via core/tracer.py. A single print() corrupts the JSON-RPC protocol channel.
  • Protected files: The autocode workflow is forbidden from editing server.py, registry.py, core/config.py, core/tracer.py, core/llm.py, core/memory_engine.py, and core/gateway.py.
  • Role abstraction: Never hardcode model names (e.g., "qwen", "hermes") in prompts or logic. Always use the planner, executor, router abstractions from cfg.
  • No .bak files: Use atomic writes (tempfile.NamedTemporaryFile + os.replace). Creating .bak files is forbidden by project rules.

Best practices for AI assistants

  • Preserve style & comments: Do not "clean up", reformat, or rewrite existing docstrings, comments, or spacing unless asked. Match the existing style (from __future__ import annotations everywhere).
  • Surgical edits only: Provide exact findβ†’replace blocks. Do not output entire files unless requested.
  • Respect LangGraph immutability: Workflow nodes return partial state updates (return {"key": value}). NEVER mutate the shared state dict in-place.
  • No hallucinated APIs: If you need to know how an internal module works, read the file. Do not guess function signatures of core/ modules.
  • Tool creation pattern: Create a file in tools/, import from registry import tool, use the @tool decorator (and @meta_tool + DISPATCH for atomic-action tools). The docstring becomes the LLM prompt. Always return {"status": "success/error", ...}. See docs/TOOLS.md Β§ New Tool Checklist.
  • Memory safety: Respect Tag Validation (MED-05) and the Write-Only Lock pattern (MED-01) in core/memory_backend/. Never write directly to the procedural_meta ChromaDB collection β€” the Sleep & Learn daemon owns it.
  • Testing: .\venv\Scripts\python tests/<area>/<component>/ -W error --tb=short -v

πŸ’€ Sleep & Learn (Meta-Learning Daemon)

A unique differentiator: an autonomous background daemon (core/sleep_learn/) observes execution traces, distills procedural rules from successes and failures, and injects the highest-utility rules into the Planner's context for future tasks. The agent genuinely learns from its own experience β€” no manual tuning required.

Rules for AI assistants interacting with this system:

  1. Respect the injection: If you see --- RELEVANT LEARNED RULES --- in a system prompt, apply those rules. They were autonomously learned from past outcomes.
  2. Never manually mutate learned rules: Don't write to the procedural_meta collection. The daemon's feedback loop boosts/penalizes rules based on trace outcomes.
  3. Use the janitor for bloat: If memory retrieval feels slow, run memory(action="janitor") to archive old episodes and purge stale rules.
  4. No LLM bypassing: Background learning tasks MUST use the public llm.complete() API. Never import provider clients directly β€” you'll bypass the daemon's token budgets and rate limiters.

See docs/core/SLEEP_LEARN.md for the full architecture.


πŸ“‚ Repo Hierarchy

The full file/folder layout is documented in docs/STRUCTURE.md. Below is a condensed view β€” see STRUCTURE.md for the complete map, naming conventions, and pattern details.

agent/
β”œβ”€β”€ server.py              # MCP stdio entry point (DO NOT BREAK STDOUT)
β”œβ”€β”€ registry.py            # @tool auto-discovery engine
β”œβ”€β”€ mcp.json               # MCP server configuration
β”œβ”€β”€ requirements.txt Β· pytest.ini
β”‚
β”œβ”€β”€ core/                  # 13 subsystems (facade + *_backend/ pattern)
β”‚   β”œβ”€β”€ config.py β†’ config_backend/     # 9-builder config system
β”‚   β”œβ”€β”€ llm.py β†’ llm_backend/           # 10 providers, role dispatch
β”‚   β”œβ”€β”€ memory_engine.py β†’ memory_backend/  # 3-collection ChromaDB
β”‚   β”œβ”€β”€ router.py β†’ router_backend/     # 15s classification + fallbacks
β”‚   β”œβ”€β”€ gateway.py β†’ gateway_backend/   # FastAPI REST API
β”‚   β”œβ”€β”€ runtime/ Β· sleep_learn/ Β· kgraph/  # Direct subpackages
β”‚   β”œβ”€β”€ observability/                  # tracer_engine + reader + metrics
β”‚   β”œβ”€β”€ net/                            # SSRF, retry, budget
β”‚   β”œβ”€β”€ context_pruner.py Β· tracer.py
β”‚   └── contracts.py Β· path_guard.py Β· time_utils.py Β· utils.py Β· ...  # Standalone
β”‚
β”œβ”€β”€ tools/                 # 18 meta-tools (facade + *_ops/ pattern)
β”‚   β”œβ”€β”€ _meta_tool.py      # @meta_tool decorator
β”‚   β”œβ”€β”€ agent.py + agent_ops/     Β· browser.py + browser_ops/
β”‚   β”œβ”€β”€ cli.py + cli_ops/         Β· consult.py + consult_ops/
β”‚   β”œβ”€β”€ file.py + file_ops/       Β· git.py + git_ops/
β”‚   β”œβ”€β”€ github.py + github_ops/   Β· memory.py + memory_ops/
β”‚   β”œβ”€β”€ notify.py + notify_ops/   Β· parallel.py + parallel_ops/
β”‚   β”œβ”€β”€ python.py + python_ops/   Β· report.py + report_ops/
β”‚   β”œβ”€β”€ schedule.py + schedule_ops/  Β· swarm.py + swarm_ops/
β”‚   β”œβ”€β”€ tavily.py + tavily_ops/   Β· vision.py + vision_ops/
β”‚   β”œβ”€β”€ web.py + web_ops/         Β· workflow.py + workflow_ops/
β”‚
β”œβ”€β”€ workflows/             # 6 LangGraph state machines (facade + *_impl/ pattern)
β”‚   β”œβ”€β”€ base.py Β· helpers/
β”‚   β”œβ”€β”€ research.py β†’ research_impl/         (8 nodes)
β”‚   β”œβ”€β”€ deep_research.py β†’ deep_research_impl/  (13 nodes)
β”‚   β”œβ”€β”€ data.py β†’ data_impl/                 (5 nodes)
β”‚   β”œβ”€β”€ autocode.py β†’ autocode_impl/         (29 nodes)
β”‚   β”œβ”€β”€ understand.py β†’ understand_impl/     (4 nodes)
β”‚   └── autoresearch.py β†’ autoresearch_impl/ (8 nodes)
β”‚
β”œβ”€β”€ data_sources/          # Raw data ingestion + query (CVM, B3)
β”‚   β”œβ”€β”€ dispatcher.py      # @tool data_source(domain, sub_domain, mode, params)
β”‚   β”œβ”€β”€ cvm/               # Brazilian SEC: DFP, ITR, FRE, IPE, CAD, Bridge
β”‚   └── b3/                # Brazilian stock exchange: API, Dividends
β”‚
β”œβ”€β”€ skills/                # Analytical views (read-only, combine data sources)
β”‚   β”œβ”€β”€ dispatcher.py      # @tool skill(domain, sub_domain, mode, params)
β”‚   └── cvm/               # CVM skills: shareholders, dividends
β”‚
β”œβ”€β”€ benchmark/             # Role benchmarking tool
β”œβ”€β”€ docs/                  # 5-file documentation standard per component
└── tests/                 # Pytest suites mirror source structure

See docs/STRUCTURE.md for: the v1.0 *_ops/ pattern, the *_impl/ workflow pattern, the *_backend/ core pattern, standalone modules, naming conventions, and configuration files.


πŸ”§ Troubleshooting

Issue Solution
LM Studio unreachable Check http://localhost:1234/v1/models. Ensure CORS is enabled in LM Studio.
ChromaDB binary hang Run pip install chromadb --no-binary chromadb.
Kaleido PNG crash Ensure kaleido==0.2.1 is installed.
Tool not discovered Check for @tool decorator, ensure file is in tools/ or skills/, restart server.
Autocode syntax errors Set AUTOCODE_DEBUG=1 in .env and check logs/agent_*.jsonl.
"No module named 'X'" Activate venv, run pip install -r requirements.txt, verify with where python.
MCP stdio corruption Check for print() statements in tools/workflows. All logging must go to stderr.
Git operations failing Ensure git is on PATH. We use subprocess directly, not GitPython.
PDF export failing Install GTK3 Runtime on Windows. HTML reports work without it.
Memory slow Run memory(action="janitor") to archive old episodes and purge stale rules.
Router timeout Check ROUTER_MODEL is loaded in LM Studio. Fallback heuristics will still work.
Gateway 403 errors Change GATEWAY_SECRET from default changeme in .env.
Cron fires wrong day Use schedule or notify(recurring) β€” both use _build_cron_trigger (0=Sunday). Don't use CronTrigger.from_crontab directly (0=Monday trap).

πŸ”— Configure MCP Servers

To connect the agent to an MCP host (LM Studio, Claude Desktop, Cursor), add the server configuration to your host's MCP settings file (e.g., mcp.json or claude_desktop_config.json). See mcp.json in the repository root for the exact JSON structure.

Key setup rules:

  • agent server: The command must point to the python.exe inside your venv folder (e.g., D:/mcp/agent/venv/Scripts/python.exe). Global Python won't find your installed dependencies.
  • Paths: Update all directory paths in the JSON to match where you cloned this repository.

Note: The agent no longer depends on the external @mcpcentral/mcp-time MCP server for time/timezone functionality. Time operations are handled natively by core/time_utils.py (tz-aware, reads AGENT_TZ env var). You can remove the time entry from your mcp.json if you had it.


Architecture: 3-tier role system β†’ 18 tools β†’ 6 workflows β†’ 3-collection memory β†’ structured tracing β†’ background learning β†’ tz-aware scheduling. Local-first, cloud-optional, fully open-source.


Last updated: 2026-07-16. All tools/workflows/subsystems at v1.0+. See STRUCTURE.md for the repo layout, SESSION_WORKFLOW.md for the dev workflow, and each component's CHANGELOG.md for version history.

Contributors

Languages