# MCP Tools API Deep Reference (All 31 FastMCP Tools)

This document provides complete parameter definitions, return types, and example responses for all 31 BrainDB FastMCP tools.

---

## 1. `upsert_slot_fact`
*   **Purpose:** Atomically upsert a single key-value memory fact into the Hot Layer with bi-temporal versioning (`t_invalid = NOW()`, `[:SUPERSEDED_BY]`).
*   **Signature:**
    ```python
    upsert_slot_fact(key: str, value: str, layer: str = "ACTIVE_TASK", project_name: str | None = None) -> str
    ```
*   **Parameters:**
    *   `key`: Canonical key string with prefix (e.g. `task:auth:jwt`, `pref:verbosity`, `env:os`).
    *   `value`: Current value string (e.g. `in_progress`, `DONE`, `concise`).
    *   `layer`: One of `ACTIVE_TASK`, `USER_PREF`, `ENV_MEMORY`, `ACTIVE_CONTEXT`.
    *   `project_name`: Name of project (required for `ACTIVE_TASK` / `ACTIVE_CONTEXT`).
*   **Latency:** 5–20ms.

---

## 2. `upsert_slot_facts_batch`
*   **Purpose:** Atomically register multiple facts in a single network round-trip.
*   **Signature:**
    ```python
    upsert_slot_facts_batch(facts: list[dict], project_name: str | None = None) -> str
    ```
*   **Payload Format:**
    ```json
    [
      {"key": "task:auth", "value": "status: active", "layer": "ACTIVE_TASK"},
      {"key": "task:auth:jwt", "value": "status: ready", "layer": "ACTIVE_TASK"}
    ]
    ```
*   **Latency:** 5–20ms.

---

## 3. `get_hot_layer`
*   **Purpose:** Fetch all active facts for a specified Hot semantic layer (<20ms direct B-tree lookup).
*   **Signature:**
    ```python
    get_hot_layer(layer: str = "ACTIVE_TASK", project_name: str | None = None) -> list[dict[str, Any]]
    ```
*   **Supported Layers:** `ACTIVE_TASK`, `USER_PREF`, `COMMUNITY_SUMMARY`, `WARM_TASK`, `WARM_ARCHIVE`.
*   **Output:** JSON list mapping active key-value facts with validity timestamps.

---

## 4. `add_graph_relationships`
*   **Purpose:** Insert explicit domain entities and directed edges into the graph. Accepts entities as names or dictionary objects.
*   **Signature:**
    ```python
    add_graph_relationships(entities: list[dict | str], relationships: list[dict], project_name: str | None = None) -> str
    ```
*   **Relationship Format:**
    ```json
    {
      "source": "Task_Auth",
      "target": "Task_Crypto",
      "type": "DEPENDS_ON",
      "properties": {"criticality": "high"}
    }
    ```

---

## 5. `log_episode`
*   **Purpose:** Fast enqueue of episodic conversation turns and agent events into graph, with optional entity and chunk linkages.
*   **Signature:**
    ```python
    log_episode(message: str, topics: list[str] | None = None, project_name: str | None = None, user_id: str | None = None, entity_names: list[str] | None = None, chunk_ids: list[str] | None = None) -> str
    ```

---

## 6. `ingest_context`
*   **Purpose:** Ingest hierarchical Markdown documents, code, or specs into Cold Layer. Generates L1/L2/L3 chunks, vector embeddings, AST entities, and HNSW links.
*   **Signature:**
    ```python
    ingest_context(text: str, layer: str = "KNOWLEDGE", project_name: str | None = None, file_path: str | None = None) -> str
    ```
*   **Bi-Temporal Detection:** Supplying `file_path` enables SHA-256 hash checks; skips unchanged files and invalidates stale chunks if changed.

---

## 7. `query_semantic_layer`
*   **Purpose:** Fast vector retrieval filtered strictly to specified semantic layers.
*   **Signature:**
    ```python
    query_semantic_layer(query: str = "", layers: list[str] | str = "KNOWLEDGE", project_name: str | None = None, top_k: int = 20, update_access_stats: bool = True) -> str
    ```
*   **Latency:** 100–250ms.
*   **Side-effect:** Increments `access_count` on returned chunks.

---

## 8. `query_graph`
*   **Purpose:** Relational Multi-Hop GraphRAG Traversal (Hybrid Dense Vector + 2-Hop Entity Subgraph + Hierarchical Document Traversal) + Cross-Encoder Reranker + Grounded Answer synthesis.
*   **Signature:**
    ```python
    query_graph(question: str, project_name: str | None = None, max_depth: int = 4, sota_mode: str = "ultimate", audit_mode: bool = False, user_id: str | None = None, scopes: list[str] | None = None) -> str
    ```
*   **Latency:** 800ms–1.8s.
*   **Side-effect:** Increments `access_count` on returned chunks.

---

## 9. `resolve_and_link_entities`
*   **Purpose:** Two-tier semantic entity resolution (prefix blocking + cosine similarity) and probabilistic `[:SAME_AS {confidence: float}]` graph linking.
*   **Signature:**
    ```python
    resolve_and_link_entities(entities: list[str], similarity_threshold: float = 0.88, project_name: str | None = None) -> str
    ```
*   **Latency:** <20ms.

---

## 10. `run_sleep_consolidation`
*   **Purpose:** Sleep-Consolidated Memory (SCM) idle daemon cycle. Prunes orphaned temporary entities older than grace period (default 24h) and resets memory decay.
*   **Signature:**
    ```python
    run_sleep_consolidation(project_name: str | None = None, min_age_seconds: int = 86400) -> str
    ```
*   **Latency:** Background / 5–25s.

---

## 11. `ingest_codebase_graph`
*   **Purpose:** Deterministic AST extraction of `CodeFile`, `CodeClass`, and `CodeFunction` symbols and relationships (`CONTAINS`, `HAS_METHOD`, `EXTENDS`, `CALLS`, `IMPORTS`), batched into Neo4j via `UNWIND`.
*   **Signature:**
    ```python
    ingest_codebase_graph(directory_path: str, project_name: str | None = None) -> str
    ```
*   **Latency:** 2–7s for whole repositories.

---

## 12. `query_code_graph`
*   **Purpose:** Query incoming callers, outgoing callees, line ranges, signatures, and linked documentation for any function or class symbol. Uses Jev `Choice` to disambiguate ambiguous symbol names.
*   **Signature:**
    ```python
    query_code_graph(symbol_name: str, depth: int = 2, project_name: str | None = None) -> str
    ```
*   **Latency:** 40–120ms.

---

## 13. `build_hierarchical_communities`
*   **Purpose:** Builds a 3-level hierarchical community DAG in Neo4j (L0 Component Clusters, L1 Subsystem Domains, L2 Root Architecture) synthesized via DeepSeek V4.1-flash, and caches the root overview in Hot Layer `COMMUNITY_SUMMARY`.
*   **Signature:**
    ```python
    build_hierarchical_communities(project_name: str | None = None) -> str
    ```
*   **Latency:** 10–30s.

---

## 14. `hierarchical_community_search`
*   **Purpose:** Coarse-to-fine top-down beam search: Root (L2) -> Subsystems (L1) -> Component Clusters (L0) -> Entities & Code Symbols. Uses Jev `Score` primitive to prune branches in milliseconds without LLM token waste.
*   **Signature:**
    ```python
    hierarchical_community_search(query: str, beam_width: int = 3, project_name: str | None = None) -> str
    ```
*   **Latency:** 120–250ms.

---

## 15. `reinforce_memory`
*   **Purpose:** Applies biological Hebbian learning ("cells that fire together, wire together") to memory items traversed during reasoning. Multiplies stability $S \leftarrow S \times 1.15$ and increments `access_count` to immunize active paths against Ebbinghaus exponential forgetting.
*   **Signature:**
    ```python
    reinforce_memory(chunk_ids: list[str] | None = None, entity_names: list[str] | None = None, project_name: str | None = None) -> str
    ```
*   **Latency:** 10–30ms.

---

## 16. `archive_completed_tasks`
*   **Purpose:** Consolidate and retire completed tasks (`value STARTS WITH 'DONE'`) from the Hot Layer (`ACTIVE_TASK`) into Warm episodic state by setting `t_invalid = NOW()`. Enforces the Hot-to-Warm Stop architectural law: tasks STOP at Warm and are NOT duplicated into Cold `TASK_HISTORY`, because Cold storage is populated exclusively via dedicated file ingestion (`specs/*.md`).
*   **Signature:**
    ```python
    archive_completed_tasks(project_name: str | None = None) -> str
    ```
*   **Latency:** 10–25ms.

---

## 17. `start_spec_task`
*   **Purpose:** Non-blocking task initiation (<15ms, 0 token cost). Reads and validates the Markdown specification file on disk (`specs/<feature>.md`), verifies heading discipline and checklist structure, and registers `in_progress` in the Hot Layer (`ACTIVE_TASK`). Opens the task execution gate immediately without blocking on slow Cold ingestion.
*   **Signature:**
    ```python
    start_spec_task(
        spec_path: str,
        task_key: str | None = None,
        project_name: str | None = None,
        initial_status: str = "in_progress"
    ) -> str
    ```
*   **Parameters:**
    *   `spec_path`: Relative or absolute path to the workspace Markdown spec file (e.g. `specs/auth.md`).
    *   `task_key`: Optional explicit key for Hot working memory (defaults to `task:<feature_name>`).
    *   `project_name`: Isolation boundary project name.
    *   `initial_status`: Status string recorded in Hot memory (default: `in_progress`).
*   **Latency:** 5–15ms.

---

## 18. `sync_and_complete_task`
*   **Purpose:** Single-Ingest Commit Gate. Enforces that 100% of checklist items in the Markdown spec on disk are marked completed (`- [x]`). Ingests the finished spec into Cold Layer `KNOWLEDGE` **once**, retires the Hot task fact (`DONE`, `t_invalid = NOW()`), and creates the atomic provenance relationship `[:COMMITTED_INTO]` connecting the retired task fact directly to the Cold spec root chunk. Zero duplication, zero drift.
*   **Signature:**
    ```python
    sync_and_complete_task(
        spec_path: str,
        task_key: str | None = None,
        project_name: str | None = None,
        require_all_checked: bool = True,
        summary: str | None = None,
        retire_now: bool = True
    ) -> str
    ```
*   **Parameters:**
    *   `spec_path`: Relative or absolute path to the completed workspace Markdown spec file.
    *   `task_key`: Optional explicit key of the Hot task to retire (auto-derived from spec if omitted).
    *   `project_name`: Isolation boundary project name.
    *   `require_all_checked`: If True, raises validation error if any `- [ ]` unchecked item remains.
    *   `summary`: Optional brief completion summary for the log/provenance edge.
    *   `retire_now`: If True (default), retires the task immediately to `WARM_TASK` with `t_invalid = NOW()`.
*   **Latency:** 15–30ms (Hot retirement & validation) + single Cold spec ingestion.

---

## 19. `health_check`
*   **Purpose:** Diagnostic tool that pings the Neo4j connection pool, measures query round-trip latency, and validates active LLM/embedding models.
*   **Signature:**
    ```python
    health_check() -> dict[str, Any]
    ```
*   **Latency:** 5–15ms.

---

## 20. `reconcile_spec_task`
*   **Purpose:** Bidirectional Spec Reconciliation. Compares the live disk spec against the stored SHA-256 fingerprint (`meta:<task_key>:spec_hash`), auto-ingests user-added checklist items as `TODO`, and refreshes the fingerprint without amnesia.
*   **Signature:**
    ```python
    reconcile_spec_task(spec_path: str, task_key: str | None = None, project_name: str | None = None) -> str
    ```
*   **Latency:** <15ms.

---

## 21. `initialize_project_layers`
*   **Purpose:** Pre-initializes the canonical 5-layer cognitive schema container nodes in Neo4j (`ACTIVE_TASK`, `USER_PREF`, `WARM_TASK`, `WARM_ARCHIVE`, `KNOWLEDGE`) for a project namespace.
*   **Signature:**
    ```python
    initialize_project_layers(project_name: str | None = None) -> str
    ```
*   **Latency:** 10–25ms.

---

## 22. `ingest_corpus`
*   **Purpose:** Universal whole-corpus ingestion for a single document file OR an entire directory. Runs whole-corpus Stage 1 local skeleton, Stage 2 global entity linking & supersession, Stage 3 Leiden community topology, and automated bottom/reverse pointer generation.
*   **Signature:**
    ```python
    ingest_corpus(file_path: str, project_id: str | None = None, corpus_type: str = "general") -> str
    ```
*   **Latency:** Staged (sub-second per file; 5-15s for batches).

---

## 23. `ingest_raw_text`
*   **Purpose:** Ingests raw markdown or plaintext strings directly into Brain DB with full 3-tier chunk hierarchy, AST concepts, and bottom pointer generation.
*   **Signature:**
    ```python
    ingest_raw_text(text: str, doc_id: str, title: str | None = None, project_id: str | None = None, corpus_type: str = "general", layer: str = "KNOWLEDGE") -> str
    ```
*   **Latency:** 1–3s.

---

## 24. `query_brain_db`
*   **Purpose:** Unified Relational GraphRAG Retrieval with dynamic token budget packing. Executes Hybrid Dense Vector + Knowledge Graph + BM25 search, Multiplex Expansion, Cross-Encoder Reranking, Contiguous Span Stitching, and Grounded Generation.
*   **Signature:**
    ```python
    query_brain_db(
        query: str,
        project_id: str | None = None,
        budget_ceiling: int | None = None,
        audit_mode: bool = False,
        max_depth: int | None = None,
        user_id: str | None = None,
        scopes: list[str] | None = None
    ) -> str
    ```
*   **Latency:** 800ms–1.8s.

---

## 25. `audit_epistemic_revisions`
*   **Purpose:** Audits active epistemic amendments, controlling chunks, and superseded provisions across the project knowledge graph. Bounded with `LIMIT 100`.
*   **Signature:**
    ```python
    audit_epistemic_revisions(project_id: str | None = None, doc_id: str | None = None, project_name: str | None = None) -> list[dict[str, Any]]
    ```
*   **Latency:** 20–60ms.

---

## 26. `compute_bottom_pointers`
*   **Purpose:** Computes and persists top-K forward semantic shortcuts (`[:SIMILAR_TO]`) for leaf chunks using block-wise cosine similarity, strictly excluding 2-hop sequential neighbors.
*   **Signature:**
    ```python
    compute_bottom_pointers(project_name: str | None = None, threshold: float = 0.65, top_k: int = 5) -> dict[str, Any]
    ```
*   **Latency:** 1–3s.

---

## 27. `compute_bottom_reverse_pointers`
*   **Purpose:** Computes and persists asymmetric reverse shortcuts (`[:SIMILAR_TO_REV]`) with HippoRAG / PathRAG cross-document diversity pruning.
*   **Signature:**
    ```python
    compute_bottom_reverse_pointers(project_name: str | None = None, cap: int = 10, cross_doc_diversity: bool = True) -> dict[str, Any]
    ```
*   **Latency:** 1–2s.

---

## 28. `get_bottom_pointers`
*   **Purpose:** Queries forward and reverse semantic bottom pointers for a specific chunk using independent subqueries (zero Cartesian product).
*   **Signature:**
    ```python
    get_bottom_pointers(chunk_id: str, project_name: str | None = None) -> dict[str, Any]
    ```
*   **Latency:** 10–25ms.

---

## 29. `manage_vault_credentials`
*   **Purpose:** Inspect, test, or update tenant BYOK / BYODB credentials and multi-model pipeline routing over MCP (guarded by `allow_agent_vault_management`).
*   **Signature:**
    ```python
    manage_vault_credentials(
        action: str = "get",
        llm_provider: str | None = None,
        llm_model: str | None = None,
        extractor_model: str | None = None,
        summary_model: str | None = None,
        reranker_model: str | None = None,
        llm_api_key: str | None = None,
        neo4j_uri: str | None = None,
        neo4j_user: str | None = None,
        neo4j_password: str | None = None,
        neo4j_database: str | None = None,
        tenant_id: str | None = None
    ) -> dict[str, Any]
    ```
*   **Actions:** `'get'`, `'test'`, `'update'`.

---

## 30. `manage_agent_keys`
*   **Purpose:** List, create, or revoke scoped FastMCP API keys (`bdb_live_...`) for connected AI agents (guarded by `allow_agent_vault_management` for mutations).
*   **Signature:**
    ```python
    manage_agent_keys(
        action: str = "list",
        name: str | None = None,
        key_id: str | None = None,
        tenant_id: str | None = None
    ) -> dict[str, Any]
    ```
*   **Actions:** `'list'`, `'create'`, `'revoke'`.

---

## 31. `get_account_telemetry`
*   **Purpose:** Retrieve tenant tier, Redis token-bucket burst/refill capacity, active key count, 30-day invocation counts, average latency, and recent audit logs.
*   **Signature:**
    ```python
    get_account_telemetry(tenant_id: str | None = None) -> dict[str, Any]
    ```
*   **Latency:** 10–30ms.




