cortex-engine

cortex-engine

Persistent memory for AI agents with semantic memory, belief tracking, and dream consolidation, enabling cross-session knowledge retention.

Category
访问服务器

README

@fozikio/cortex-engine

npm version npm downloads GitHub stars License: MIT

Persistent memory for AI agents. Open source, LLM-agnostic, works with any MCP client.

<p align="center"> <img src="demo.gif" alt="cortex-engine demo — init, explore, serve" width="800" /> </p>

Star History

<a href="https://www.star-history.com/?repos=Fozikio%2Fcortex-engine&type=date&legend=top-left"> <picture> <source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/image?repos=Fozikio/cortex-engine&type=date&theme=dark&legend=top-left" /> <source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/image?repos=Fozikio/cortex-engine&type=date&legend=top-left" /> <img alt="Star History Chart" src="https://api.star-history.com/image?repos=Fozikio/cortex-engine&type=date&legend=top-left" /> </picture> </a>

What It Does

Most AI agents forget everything when the session ends. cortex-engine fixes that — it gives agents a persistent memory layer that survives across sessions, models, and runtimes.

  • Semantic memory — store and retrieve observations, beliefs, questions, and hypotheses as interconnected nodes
  • Belief tracking — agents hold positions that update when new evidence contradicts them
  • Two-phase dream consolidation — NREM compression (cluster, refine, create) + REM integration (connect, score, abstract) — modeled on biological sleep stages
  • Goal-directed cognitiongoal_set creates desired future states that generate forward prediction error, biasing consolidation and exploration toward what matters
  • Neuroscience-grounded retrieval — GNN neighborhood aggregation, query-conditioned spreading activation, multi-anchor Thousand Brains voting, epistemic foraging
  • Information geometry — locally-adaptive clustering thresholds that respect embedding space curvature, schema congruence scoring
  • Graph health metrics — Fiedler value (algebraic connectivity) measures knowledge integration; PE saturation detection prevents identity model ossification
  • Spaced repetition (FSRS) — interval-aware scheduling with consolidation-state-dependent decay profiles
  • Embeddings — pluggable providers (built-in, OpenAI, Vertex AI, Ollama) — no external service required by default
  • LLM-agnostic — pluggable LLM providers: Ollama (free/local), Gemini, Kimi (Moonshot AI), DeepSeek, Hugging Face, OpenRouter, OpenAI, or any OpenAI-compatible API
  • Three storage backends — local SQLite (default), cloud Firestore, and JSON file (backup/migration). All share one CortexStore interface — see docs/storage-backends.md
  • Atomic transactionswithTransaction(fn) primitive composes multi-step writes. SQLite uses BEGIN IMMEDIATE with a per-store mutex; Firestore uses runTransaction with a write-routing proxy. See docs/concurrency.md
  • Migration toolingfozikio migrate --from <url> --to <url> clones between any pair of backends. ID-preserving, checkpointed, resumable, fails-loud on schema mismatch
  • Typed tool catalogue — every cognitive tool carries category + whenToUse + doNotUse metadata so LLMs disambiguate cleanly. Browse with fozikio tools or GET /tools. Auto-generated reference at docs/tools-reference.md
  • Long-context dream consolidation — set strategy: long-context to run edge discovery and abstraction in a single large LLM pass instead of N² pairwise calls; surfaces transitive patterns and cross-domain connections that the sequential approach misses
  • Agent dispatchagent_invoke lets your agent spawn cheap, cortex-aware sub-tasks using any configured LLM. Knowledge compounds across sessions.
  • MCP server — 57 cognitive tools (query, observe, believe, wander, dream, goal_set, agent_invoke, thread_create, journal_write, evolve, etc.) over the Model Context Protocol

The result: personality and expertise emerge from accumulated experience, not system prompts. An agent with 200 observations about distributed systems doesn't need to be told "you care about distributed systems." It just knows.

Works with Claude Code, Cursor, Windsurf, or any MCP-compatible client. Runs locally (SQLite) or in the cloud (Firestore + Cloud Run).

Security

The engine includes defense-in-depth protections for deployed environments:

  • Timing-safe auth — REST server authentication uses crypto.timingSafeEqual to prevent timing side-channel attacks
  • Plugin sandboxing — the plugin loader validates import paths against trusted directories, blocking loads from untrusted locations
  • REST tool blocklist — destructive tools (forget, dream, evolve, resolve, thread_resolve) are blocked from the generic REST endpoint; they remain available via MCP for direct agent access
  • SQLite injection prevention — namespace names are validated (alphanumeric only), LIMIT clauses are parameterized
  • Secret leak prevention — config loader warns when API keys appear in config files instead of environment variables

Architecture

Module Role
core Foundational types, config, and shared utilities
engines Cognitive processing: memory consolidation, FSRS, graph traversal
stores Persistence layer — SQLite (local), Firestore (cloud), JSON (backup/migration). All implement the shared CortexStore interface
tools All 57 cognitive tool implementations (one file per tool)
mcp MCP server, tool registry, and plugin loader
cognitive Higher-order cognitive operations (dream, wander, validate)
triggers Scheduled and event-driven triggers
bridges Adapters for external services and APIs
providers Embedding and LLM provider implementations
bin Entry points: serve.js (HTTP + MCP), cli.js (admin CLI)
public Built-in web dashboard (served automatically with --rest)

Quick Start

npm install @fozikio/cortex-engine
npx fozikio init my-agent
cd my-agent
npx fozikio serve   # starts MCP server

Your agent now has 57 cognitive tools. The generated .mcp.json is version-pinned and platform-aware (Windows cmd /c wrapper handled automatically).

See the Quick Start wiki page for the full 5-minute setup.

Multi-Agent

npx fozikio agent add researcher --description "Research agent"
npx fozikio agent add trader --description "Trading signals"
npx fozikio agent generate-mcp   # writes .mcp.json with scoped servers

Each agent gets isolated memory via namespaces. See the Architecture wiki page for details.

Agent-First Setup

The fastest path: open an AI agent in an empty directory and say "set up a cortex workspace." The agent runs npx fozikio init, reads the generated files, and is immediately productive. See the Installation wiki page for the full guide.

Dashboard

cortex-engine ships with a built-in web dashboard. Start the REST server and open the URL in your browser:

npx fozikio serve --rest --port 3000
# open http://localhost:3000

The dashboard shows your agent's stats, threads, ops log, memories, concepts, and observations — no separate install required. It auto-detects its API from the same origin it's served from.

If auth is enabled (CORTEX_API_TOKEN), the dashboard loads without auth but API calls require a token. Set it via localStorage:

localStorage.setItem("cortex-settings", JSON.stringify({ token: "your-token" }));

Source: fozikio-dashboard

CLI

npx fozikio serve                          # start MCP server
npx fozikio health                         # memory health report
npx fozikio vitals                         # behavioral vitals and prediction error
npx fozikio wander                         # walk through the memory graph
npx fozikio wander --from "auth"           # seeded walk from a topic
npx fozikio maintain fix                   # scan and repair data issues
npx fozikio report                         # weekly quality report
npx fozikio tools                          # browse the cognitive tool catalogue
npx fozikio tools --category memory        # filter to a category
npx fozikio migrate --from sqlite:./cortex.db --to json:./backup.json --verify

All read-only commands honour --namespace <ns> and --agent <name> flags. When called from a workspace with .fozikio/agent.yaml, the agent's default_namespace is picked up automatically — no flag needed.

Development

npm run dev       # tsc --watch
npm test          # vitest run
npm run test:watch

Environment Variables

Variable Required Description
CORTEX_API_TOKEN Optional Used by the cortex-telemetry hook to send retrieval feedback to the cortex API. Not required to run the MCP server.
MOONSHOT_API_KEY Optional Required when llm: kimi is set. Get one from platform.moonshot.cn.
OPENAI_API_KEY Optional Required when llm: openai is set, or when using any OpenAI-compatible provider without an explicit API key.

Additional variables are required depending on which providers you enable (Firestore, Vertex AI, etc.). See docs/ for provider-specific configuration.

Rules, Skills & Agents

fozikio init automatically installs safety rules, skills, and agent definitions from the fozikio.json manifest into the target workspace.

Safety Rules (Reflex)

cortex-engine ships with Reflex rules — portable YAML-based guardrails that work across any agent runtime, not just Claude Code.

Rule Event What It Does
cognitive-grounding prompt_submit Nudges the agent to call query() before evaluation, design, review, or creation work
observe-first file_write / file_edit Warns if writing to memory directories without calling observe() or query() first
note-about-doing prompt_submit Suggests capturing new threads of thought with thread_create()

Rules live in reflex-rules/ as standard Reflex YAML. They're portable — use them with Claude Code, Cursor, Codex, or any runtime with a Reflex adapter. See @fozikio/reflex for the full rule format and tier enforcement.

Claude Code users also get platform-specific hooks (in hooks/) for telemetry, session lifecycle, and project board gating. These are runtime adapters, not rules — they handle side effects that the declarative rule format doesn't cover.

To customize: Edit the YAML rule files directly, or set allow_disable: true and disable them via Reflex config.

Skills

Skills are invocable workflows that agents can use via /skill-name.

Skill When to Use What It Provides
cortex-memory Query, record, and review work Full memory workflow — query/observe patterns, belief tracking, memory-grounded code review, session patterns

Agents

Agent Description
cortex-researcher Deep research agent that queries cortex before external sources, observes novel findings back into memory

How Auto-Install Works

  1. fozikio init reads fozikio.json from the package root
  2. Copies hooks, skills, and Reflex rules into the target workspace
  3. Missing source files are skipped with a warning — init never fails due to missing assets

Built-in Capabilities (v1.0.0+)

As of v1.0.0, all 57 cognitive tools are built into cortex-engine core — no separate plugin installs needed. Previously these were separate @fozikio/tools-* packages; they've been absorbed into the engine.

Capability Tools
Memory observe, query, recall, wander, forget, retrieve
Beliefs & Reasoning believe, belief, contradict, speculate, validate, predict
Threads thread_create, thread_update, thread_resolve, threads_list
Journaling journal_write, journal_read
Identity evolve, evolution_list
Social social_read, social_update, social_draft, social_score
Graph neighbors, suggest_links, suggest_tags, link, graph_report
Maintenance dream, digest, reflect, find_duplicates, retrieval_audit, consolidation_status
Vitals vitals_get, vitals_set, sleep_pressure
Reasoning surface, ruminate, notice, intention, resolve
Content content_create, content_list, content_update
Ops ops_append, ops_query, ops_update
Goals goal_set
Agents agent_invoke
Stats stats

The plugin system is still available for custom extensions — see Plugin Docs.

Documentation

  • In-repo docs:
  • Wiki — Installation, architecture, plugin authoring, MCP integration, deployment, FAQ
  • Discussions — Ask questions, share what you've built
  • Contributing — How to contribute
  • Project Board — Roadmap and active work
  • Security — Report vulnerabilities

Community

Related Projects

  • @fozikio/reflex — Portable safety guardrails for agents. Rules as data, not code.
  • sigil — Agent control surface. Signals and gestures, not conversations.
  • fozikio.com — Documentation and guides

License

MIT — see LICENSE

推荐服务器

Baidu Map

Baidu Map

百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。

官方
精选
JavaScript
Playwright MCP Server

Playwright MCP Server

一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。

官方
精选
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。

官方
精选
本地
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。

官方
精选
本地
TypeScript
VeyraX

VeyraX

一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。

官方
精选
本地
graphlit-mcp-server

graphlit-mcp-server

模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。

官方
精选
TypeScript
Kagi MCP Server

Kagi MCP Server

一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。

官方
精选
Python
e2b-mcp-server

e2b-mcp-server

使用 MCP 通过 e2b 运行代码。

官方
精选
Neon MCP Server

Neon MCP Server

用于与 Neon 管理 API 和数据库交互的 MCP 服务器

官方
精选
Exa MCP Server

Exa MCP Server

模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。

官方
精选