Connecting Tools

Wire your agents and apps to ENGRAM — the MCP server and tools, API keys, Hosts, Claude Desktop, and the Watcher.

9. Connecting External Tools to ENGRAM

Much of your research happens outside the ENGRAM app — in coding assistants like Claude Code, in Claude Desktop, in ChatGPT. ENGRAM connects to these tools so the knowledge you produce there flows into your knowledge base, instead of being stranded in another window. The bridge is an MCP server (Model Context Protocol) that ENGRAM exposes; any MCP-capable tool can use it to read from and write to your knowledge base on your behalf.

9.1 Overview

You authenticate external tools with a Personal Access Token (PAT) — a key beginning engram_pat_ that you generate in Settings → API Keys. The token identifies you, so anything a connected tool syncs lands in your knowledge base. Add the ENGRAM MCP server to your tool's configuration with your token, and the tool gains a set of ENGRAM actions:

Everything synced through a connected tool inherits your account's privacy: articles and documents are private by default, and only become public if you explicitly publish them. Your PAT is the key to your knowledge base — keep it secret, and revoke it in Settings if it's ever exposed. The sections below walk through the setup, the available tools, and per-client configuration.

9.2 The MCP server

ENGRAM exposes an MCP (Model Context Protocol) server so your local agents — Claude Code, Claude Desktop, or any other MCP-compatible client — can read, search, and write articles in your knowledge base. The same tools also drive coding-session ingest, external-conversation capture, and the Knowledge Gaps closure loop.

The ENGRAM MCP server lives at https://engram.pvelua.net/mcp/ (the trailing slash is required). It authenticates per-user via a Personal Access Token (PAT) you mint from your Settings panel.

9.2.1 Configuration

Step 1 · Mint a PAT

Sign in to ENGRAM, click your avatar (top-right), open Settings → API Keys, and click + Create Key. Give it a memorable name (e.g. "Claude Code on MacBook") and copy the engram_pat_… token immediately — the raw key is shown only once. If you lose it, just create a new one and revoke the old.

See §9.4 API Keys for the full panel walkthrough.

Step 2 · Claude Code

Claude Code speaks MCP over HTTP natively — no wrapper needed. Run this once from any terminal (the -s user flag scopes the registration globally so it works from any project):

claude mcp add -s user --transport http engram-kb \
  https://engram.pvelua.net/mcp/ \
  --header "Authorization: Bearer engram_pat_your_token_here"

Verify with claude mcp list — the engram-kb entry should report ✓ Connected. Restart any open Claude Code session for the new server to load.

Tip. If you'd rather keep the raw PAT out of ~/.claude.json, export it as a shell env var first (export ENGRAM_PAT=engram_pat_…), then reference it in the header. Note that claude mcp add resolves env vars at registration time and bakes the literal value into the config — for true "no plaintext at rest", scope the registration to a project (-s project) and gitignore the resulting .mcp.json.

Step 3 · Claude Desktop

Claude Desktop's built-in MCP runtime is stdio-only for non-public servers, so we use mcp-remote — a small npm package that runs as a local stdio process and relays JSON-RPC to a remote HTTP MCP endpoint. Edit your claude_desktop_config.json (see paths below) and add this entry:

{
  "mcpServers": {
    "engram-kb": {
      "command": "/usr/local/bin/npx",
      "args": [
        "mcp-remote",
        "https://engram.pvelua.net/mcp/",
        "--header",
        "Authorization: Bearer ${ENGRAM_PAT}"
      ],
      "env": {
        "ENGRAM_PAT": "engram_pat_your_token_here"
      }
    }
  }
}

Config file location:

Restart Claude Desktop after editing. The MCP indicator (Settings → Developer) should show engram-kb as connected.

Two gotchas. The trailing slash on /mcp/ is load-bearing (no slash → 307 redirect that the JSON-RPC client doesn't follow). And command needs an absolute path to npx — Claude Desktop launches with a stripped PATH so a bare npx won't resolve. which npx in your terminal tells you the right path (Homebrew installs put it at /usr/local/bin/npx on Intel Macs or /opt/homebrew/bin/npx on Apple Silicon).

9.3 The MCP tools

ENGRAM exposes 37 MCP tools across eleven capability groups. Each tool is callable by the agent as soon as the server is registered — you don't import or list them explicitly. Just describe the task in natural language ("save this draft to my KB", "find articles related to X", "remember this decision in ENGRAM") and the agent picks the right tool.

KB writes
sync_article
Create-or-update an article keyed on (repository, file_path). Idempotent — re-runs produce a superseding version, not a duplicate.
Use when: the article corresponds to a real on-disk file (the most common case is "mirror this file into the KB"). Re-running on the same path automatically versions the content.
Key params: title, content_markdown, repository, file_path.
Example: "Sync docs/architecture.md to my ENGRAM KB."
create_article
Create a new article unconditionally — no identity dedup. Use when the content has no clear file backing (chat-drafted output, web research summaries).
Use when: you don't plan to iterate on the article locally — one-off captures, comparison reports, web summaries.
Key params: title, content_markdown, optional source_agent, tags, reason.
Example: "Draft a comparison of vector databases and save it as a new ENGRAM article."
update_article
Revise an existing article in place by its id — creates a new version linked to the old one, carrying its provenance, visibility, and tags forward. The right way to update a chat-drafted article.
Use when: you want to change an article you made with create_article (which has no file key, so sync_article can't supersede it) — a correction, an expansion, a re-draft.
Key params: article_id, content_markdown, optional title, tags, reason (recorded on the version edge).
set_article_visibility
Publish an article — change its visibility from private to public in place. One-way (public can't be made private again).
Use when: a private draft is ready to share more widely on your instance.
Key params: article_id, visibility (public).
ingest_url_as_document
Fetch a web page (or a PDF) by URL, extract its main content to clean Markdown, and file it as a document in your KB — the agent's equivalent of the Library's "Add from URL".
Use when: you want to capture a specific page so it can be referenced later — e.g. add it, then ask for a comparison or summary report grounded on the full page text.
Key params: url (must be https://).
Example: "Add https://example.com/paper to my ENGRAM KB."
KB reads
search_articles
Title-keyword search. Multi-word queries are AND'd against titles (case-insensitive). Ranked exact > starts-with > all-tokens-present.
Use when: you know roughly what the article is called. Results include a short excerpt for disambiguation.
Key params: query, limit (default 10).
Example: "Search my KB for articles about authentication."
find_related_articles
PPR-based topic and entity discovery. Returns articles ranked by graph proximity to the query's entities, not title overlap.
Use when: title search would be too narrow — you want a comparison set, or everything that mentions a concept.
Key params: query, limit (default 10).
Example: "Find ENGRAM articles related to vector database comparisons."
get_article
Fetch full markdown content and version-chain metadata for a single article by ID.
Use when: you've narrowed down via search/find/list and want the full body. The response includes version and is_latest so the agent knows whether it's reading current content.
Key params: article_id.
list_articles
Recent articles inventory (latest-of-chain only). Supports creation_trigger, since, and tag filters.
Use when: browsing — "what did I article last week?", "all my MCP-created articles", "everything tagged with foo".
Key params: limit, optional creation_trigger, since, tag.
Code sessions
ingest_code_session
Persist a Claude Code session (the JSONL transcript) into the graph as :CodeSession + :CodeRecap + :CodeAction nodes.
Use when: you want a past coding session retrievable later by topic ("what did I do about Neo4j ownership last week?"). Re-runs are MERGE-safe — idempotent.
Key params: session_id (the JSONL filename UUID; the server finds it under ~/.claude/projects/).
Note: requires the operator to enable code-session ingest globally.
find_related_code_sessions
PPR-based code-session discovery — sibling to find_related_articles but over your coding history.
Use when: recalling what you did before (file edits, decisions, prior context) — distinct from "what I researched", which is find_related_articles.
Key params: query, limit (default 10).
Example: "What did I do about Neo4j connection pooling in past sessions?"
External conversations
record_external_conversation
Capture a chat you had on another LLM host (ChatGPT, Gemini, Claude AI Chat, …) so its entities flow into ENGRAM's memory-biased retrieval.
Use when: you've been researching something on a non-ENGRAM chat surface and want that work to inform future ENGRAM retrievals — and especially before turning the research into an article.
Key params: summary, source_agent, external_project, conversation_ref, optional related_repo, tags.
Pattern: call this first to register the external conversation, then pass the same (source_agent, external_project, conversation_ref) tuple as source_conversation_ref on a subsequent create_article/sync_article call for end-to-end provenance.
Memory recall
recall
Read your memories back on demand — the counterpart to remember. Returns the memories relevant to a query: your own, plus any explicitly shared with you, each tagged with why it surfaced.
Use when: an assistant working outside ENGRAM chat needs what you've remembered, rather than waiting for it to surface. Fail-closed — only your own and granted-in memories; cross-user shares resolve only when your operator has enabled sharing.
Key params: query (free text) and/or entities, horizon (long_term | working | both), optional limit.
Example: "Recall from ENGRAM what we decided about the database."
Memory authoring
remember
Deliberately commit a memory — a decision, fact, or preference worth keeping. Recallable right away, joining the same associative retrieval as your articles and conversation memories.
Use when: you land on something worth keeping and want it remembered on purpose rather than waiting for ENGRAM to observe it. Naming ENGRAM ("…in ENGRAM") routes it here, not to the assistant's own memory.
Key params: content, scope (long_term across sessions, or working for the current task), optional salience; to scope a finding to a project (agent teams), owner_scope="project" + active_repo (or active_project_id) — see Agent projects below.
Example: "Remember in ENGRAM that we chose PostgreSQL over MySQL for its JSONB support."
commit_task_memories
At a task or session close, gather the work into a recap and propose the memories worth keeping from it. The recap is suggested — held for review, invisible to retrieval until accepted.
Use when: wrapping up a unit of work and there's more worth keeping than any single fact. Returns a recap_id for the accept step.
Key params: context_ref (the session/task to reflect over), context_kind, optional task_ref.
Example: "Commit the memories from this session."
suggest_memories
Propose an explicit list of memories to keep, rather than letting ENGRAM gather them. Also written as a suggested recap awaiting your accept.
Use when: you know exactly what you want kept and want to hand it over directly.
Key params: items (the list of notes), context_ref, context_kind.
Example: "Suggest for my memory: the rate limit is 100 req/s; caching is deferred to v2."
accept_memories
Accept a suggested recap — flip its memories from suggested to recallable. The other half of the suggest→accept handshake.
Use when: you've reviewed a recap from commit_task_memories or suggest_memories and want to make those memories recallable. (You can also Accept/Reject from the Suggestions inbox in the Memory Explorer.)
Key params: recap_id (returned by the commit/suggest call).
list_inbox
List the recaps awaiting your review — your suggestion inbox, across all your work. Includes recaps handed off to you by a collaborator.
Use when: finding what's waiting for your accept — your own committed recaps, inferred suggestions, and hand-offs addressed to you — then accepting with accept_memories. (The same inbox is the Suggestions section of the Memory Explorer.)
Key params: none required.
Memory correction
revise
Correct a fact you remembered. ENGRAM derives a new memory from your correction that supersedes the old one — recall returns the current truth, and the previous belief is kept (never overwritten) for history.
Use when: something you told ENGRAM has changed — a decision reversed, a version bumped, a preference updated. You revise by id; the old memory is retired with a validity date, not deleted, so nothing is lost. ENGRAM decides how confidently to apply it, and routes anything uncertain to a human review inbox.
Key params: memory_id, new_content.
Example: "Revise that memory — we moved off MySQL to PostgreSQL for its JSONB support."
forget
Retire a memory without losing it. A non-lossy retraction — the memory stops being recalled and gets a validity end-date, but it is preserved for audit and can be brought back.
Use when: a fact is no longer true and there's no replacement — you just want ENGRAM to stop surfacing it. Unlike revise, there's no successor and no model call; it only touches your own memories.
Key params: memory_id.
revert
Restore a memory you superseded or forgot — undo the retirement. It becomes recallable again and, if it had been superseded, the newer version's link back to it is dropped.
Use when: a correction was wrong, or you retired something you still want. Because ENGRAM keeps the past instead of deleting it, reverting is always possible. Owner-only, like the others.
Key params: memory_id.
Memory sharing
share_memory
Grant another ENGRAM user read-access to one of your memories — or a whole conversation/session or project. The cross-user sharing primitive: it passes recall, not authorship, so the memory stays yours.
Use when: you want a teammate to be able to recall something of yours. Use recall-then-share: identify the id first (a memory you just committed, a conversation/session, or a project), then grant exactly that. Grants are inert until your operator enables sharing, and are revocable.
Key params: selector_kind (memory | context | project), selector_id, grantee (email or user_id), optional bound_scope, expires_at.
Example: "Share that PostgreSQL-vs-MySQL decision memory with alice@example.com."
list_shares
List the cross-user grants involving you — those you've made to others, or those others have made to you.
Use when: reviewing what you've shared, or what you can currently recall from others.
Key params: directionby (grants you made, incl. revoked — your audit trail) or with (active grants made to you).
revoke_share
Revoke a grant you made — the recipient can no longer recall it. A soft-revoke: the grant is kept (marked revoked) for your audit history, but stops resolving immediately.
Use when: ending a share. You can only revoke your own grants; your original memory is never touched.
Key params: share_id (from share_memory or list_shares).
share_working_memory
Hand off a slice of your live working memory to a teammate for the length of a task — the orchestrator→specialist fan-out primitive. Snapshot (not live), TTL-bounded, and revocable.
Use when: coordinating multi-agent work where a specialist needs your current working notes for a task — distinct from share_memory, which grants durable long-term recall. The named records are copied at share time, so your later edits never leak unless you push an amendment.
Key params: session_id, record_ids, recipients, optional shape (bilateral | pool), task_ref, ttl_seconds.
list_grantees
Discover the people and agents you can share memories with — the directory of eligible recipients, so an assistant can resolve "the reviewer" to a real recipient before sharing.
Use when: you want to share or hand off but don't already have the recipient's id. Returns only recipients eligible to receive — agents are opt-in (set by an administrator; default off).
Key params: optional role (filter by agent role), query (name / email match).
Sub-agent delegation
create_sub_agent
Provision a sub-agent under you — grow a team of specialist agents from inside your own session, without leaving it for the Admin UI. You become the new agent's owner; the human at the top of your tree stays accountable.
Use when: an orchestrator agent needs to fan work out to specialists that each carry their own ENGRAM identity. Requires the Agent Manager capability, enabled by your operator; the subtree quota and depth cap are enforced for you.
Key params: name, agent_role (e.g. researcher, coder, reviewer).
issue_sub_agent_pat
Mint a Personal Access Token for a sub-agent you created, so a worker process can act as that sub-agent. The raw key is returned once — treat it as a one-time secret.
Use when: you've created a sub-agent and want to hand its credential to the process that will run it (its own headless session), so that worker's memory writes land under the sub-agent's identity.
Key params: user_id (the sub-agent's id, from create_sub_agent), optional pat_name.
list_sub_agents
Re-enumerate the team you own — recover your sub-agents' identifiers at any time, so managing them never depends on state you happen to still hold in the current session.
Use when: you need your sub-agents' ids back — a new session, after a context reset, or just to review the roster before issuing or rotating a credential. An agent sees its direct sub-agents; a human sees its whole delegation subtree.
Key params: optional cursor (page from the last row), limit.
list_sub_agent_pats
List a sub-agent's access tokens — the non-secret metadata (prefix, status, last-used), never the raw keys — so you can identify a specific credential to revoke or rotate.
Use when: you want to see which tokens a sub-agent you own currently holds, and pick the key_id of the one to retire or rotate.
Key params: user_id (the sub-agent's id).
revoke_sub_agent_pat
Retire a sub-agent's access token — a kill-switch that reveals no secret. Only the owning parent can do it, and it works even when sub-agent provisioning is switched off, so a leaked key is always revocable.
Use when: a sub-agent's credential has leaked, or you're decommissioning the worker that ran under it, and you want that key to stop working immediately.
Key params: user_id, key_id (from list_sub_agent_pats).
rotate_sub_agent_pat
Rotate a sub-agent's access token — revoke the old key and mint a fresh one in a single step, so the worker keeps its identity but gets a new secret. The new raw key is returned once.
Use when: a key leaked or is due for rotation but the sub-agent should keep running — push the new key to its worker, and the old one stops working the moment you rotate.
Key params: user_id, key_id, optional pat_name.
Agent projects
create_project
Provision a project — the unit of per-project memory scoping. An orchestrator sets one up per unit of work (a repo, or a repo+branch) so its sub-agents can keep memories that stay bound to that project.
Use when: an orchestrator agent has a plan and wants each worker's findings kept per project. Provision once per repo (set repo_url so a worker's active_repo resolves to it); workers then resolve it, they don't re-create it. ENGRAM only tracks the project as a scoping anchor — it doesn't create the git repo or hold credentials.
Key params: name, optional repo_url (the key workers declare as active_repo). Returns the project_id.
The flow: create_project → each worker remember(owner_scope="project", active_repo=…) to anchor a finding, then share_memory(bound_scope="project") to the orchestrator → the orchestrator recall(active_repo=…) fans them in per project (one project's findings at a time). A project-scoped remember with no resolvable project fails loudly rather than storing an unrecallable memory.
list_projects
List the projects you own — to reuse one you already provisioned rather than minting a duplicate, or to recover a project's project_id / repo_url after a session boundary.
Use when: checking whether you've already set up a project for a repo before calling create_project, or re-enumerating your projects in a new session. Own-scoped — you see only your own projects, never another user's. (To reuse a project you don't own, you don't need to see it: a worker just declares active_repo and ENGRAM resolves it.)
Key params: none. Returns each project's project_id, name, repo_url, and per-surface counts.
Knowledge Gaps
list_kb_gaps
Browse the inventory of detected knowledge gaps (:GapItem nodes) — topics where the KB has thin coverage or known retrieval failures.
Use when: you want to see what the gap-analysis detectors have flagged for follow-up.
Key params: optional type, severity, status, limit.
propose_gap_closure
Draft a closure proposal against a specific gap — the primary submission surface for autonomous closure loops (Cowork, etc.).
Use when: you (or an autonomous agent) have a candidate fix for a gap and want it queued for review before execution.
Key params: item_id, action_type, plus context fields like proposed_title, draft_excerpt, draft_markdown.
execute_gap_closure
Execute an already-approved gap proposal — write the article, MERGE the alias, or whatever the proposal's action_type specifies.
Use when: a previously-proposed closure has been approved (manually or via policy) and you want to materialise it.
Key params: proposal_id.

9.4 API Keys (Personal Access Tokens)

API Keys tab showing four active Personal Access Tokens with names like 'Claude Desktop', 'Claude Code', creation dates, last-used dates, and Revoke/Delete buttons
Settings → API Keys · per-tool PATs with revoke and delete controls.

Personal Access Tokens (PATs) let external agents — Claude Code, Claude Desktop, and the engram-watcher CLI — call ENGRAM on your behalf. Each token authenticates as you: anything it does shows up in your audit history.

Create a PAT

Click + Create Key, give it a name that identifies where you'll use it (e.g. "Claude Code — MacBook", "Claude Desktop — Work"), and confirm. ENGRAM shows the full engram_pat_… token once.

Copy it immediately. The raw token is hashed and stored — ENGRAM cannot recover it later. If you misplace one, create a new key and delete the lost one. The displayed list shows only the first few + last few characters (e.g. engram_pat_rjkcy…2wCM) for identification.

Revoke vs Delete

Each row shows Created and Last used dates — useful for spotting tokens that haven't been touched in a while (candidates for cleanup) or, conversely, tokens that are seeing unexpected traffic.

9.5 Hosts

Hosts tab showing two machines: an unlabeled host with auto-detected hostname 'Mac.attlocal.net', and 'Work MacBook Pro 14' labeled host with hostname 'MacBook-Pro14.local', each showing session counts and first/last-seen dates
Settings → Hosts · machines that have ingested code sessions, with optional friendly labels.

The Hosts tab lists every machine that has uploaded a Claude Code session to your KB via the engram-watcher CLI. Each row is auto-created the first time a host posts a session — the hostname comes from socket.gethostname() on the sending machine.

Label — click on a host's name to give it a friendlier display name (e.g. "Work MacBook Pro 14" for MacBook-Pro14.local). The label is used everywhere the host appears in the UI: the Coding Sessions panel, the Project insights, and host-grouped filters. The raw hostname stays as the system-level identifier.

Sessions / First seen / Last seen — counters and timestamps maintained by the ingest pipeline. Useful for spotting hosts that have gone quiet (laptop in storage, watcher daemon stopped) or for confirming a freshly installed watcher is talking to ENGRAM.

Don't see a host you expect? Only machines running the engram-watcher CLI produce Hosts rows. If you've registered a PAT but haven't installed the watcher yet, this tab stays empty — that's expected.

9.6 Claude Code slash commands

ENGRAM ships with five Claude Code slash commands that wrap the most common KB workflows. Each one is just a markdown prompt that Claude Code runs when you type /<name> in any session — they don't add new MCP tools, they compose the tools you already have. Install once, use everywhere.

9.6.1 Installing a command

Slash commands live in one of two folders, depending on whether you want them global or per-project:

To install any of the five commands below, copy the markdown into a file with the corresponding name. For example, to add /find-in-engram-kb globally:

mkdir -p ~/.claude/commands
# paste the markdown for /find-in-engram-kb (shown below) into this file:
$EDITOR ~/.claude/commands/find-in-engram-kb.md

Claude Code picks up new commands without a restart — open a fresh session and type / to confirm /find-in-engram-kb appears in the autocomplete list.

Prerequisite. Every command below assumes the engram-kb MCP server is registered — see §9.2.1 Configuration. The commands have a curl fallback for the rare case where MCP isn't reachable, but the MCP path is the primary one.

9.6.2 /add-to-engram-kb

One-shot import of a local file into the KB as a brand-new article. Use this when the file is a one-off — a paper you just wrote, a meeting transcript, a research note that won't get re-iterated. For files that will get edited and re-synced over time, prefer /sync-to-engram-kb — it produces superseding versions instead of duplicates.

Read the file at $ARGUMENTS and add it to the ENGRAM Knowledge Base.

**Provenance:** this is a coding-agent file capture. The article's context is the
repository + file it was added from — recorded as a `:Context` (agent-capture),
NOT a conversation. Do **not** call `record_external_conversation`: there is no
single chat that owns a repo file (it evolves across many sessions). The
`source_agent` + `repository` + `file_path` you pass below ARE the provenance.

Steps:
1. Read the file content at the path specified
2. Extract the title from the first `# ` heading in the file. If no heading exists, use the filename without extension as the title
3. Determine the current git repository name using `git remote get-url origin` (strip the `.git` suffix and any `git@host:owner/` or `https://host/owner/` prefix to get the bare repo name) or fall back to the directory name
4. Use the ENGRAM KB MCP tool `create_article` with:
   - title: the extracted title
   - content_markdown: the full file content
   - source_agent: "claude_code"
   - repository: the git repository name (from step 3)
   - file_path: $ARGUMENTS
   - reason: "Added via /add-to-engram-kb command"
5. Report success: confirm the article was created with its title and article_id

If the MCP tool is not available, fall back to a direct API call:
```bash
curl -s -X POST https://engram.pvelua.net/api/articles \
  -H "Authorization: Bearer $ENGRAM_PAT" \
  -H "Content-Type: application/json" \
  -d '{"title":"<title>","content_markdown":"<content>","creation_trigger":"external","source_context":{"agent":"claude_code","repository":"<repo>","file_path":"$ARGUMENTS","reason":"Added via /add-to-engram-kb command"}}'
```

9.6.3 /sync-to-engram-kb

Idempotent mirror of a file into the KB. Re-running on the same (repository, file_path) tuple produces a new superseding version instead of a duplicate — the previous version stays reachable through the article's version chain. Use this for design docs, ongoing notes, or any markdown you keep editing locally.

Read the file at $ARGUMENTS and sync it to the ENGRAM Knowledge Base.

Unlike `/add-to-engram-kb`, this command is idempotent: re-running it on the same file produces a new superseding version of the existing article instead of a duplicate. The KB looks up the latest article for this user matching the (repository, file_path) tuple — on hit it creates a superseding version, on miss it creates a fresh article.

**Provenance:** this is a coding-agent file capture. The article's context is the
repository + file it was synced from — recorded as a `:Context` (agent-capture),
NOT a conversation. Do **not** call `record_external_conversation`: there is no
single chat that owns a repo file (it evolves across many sessions). The
`source_agent` + `repository` + `file_path` you pass below ARE the provenance.

Steps:
1. Read the file content at the path specified
2. Extract the title from the first `# ` heading in the file. If no heading exists, use the filename without extension as the title
3. Determine the current git repository name using `git remote get-url origin` (strip the `.git` suffix and any `git@host:owner/` or `https://host/owner/` prefix to get the bare repo name) or fall back to the directory name
4. Determine the current git branch using `git rev-parse --abbrev-ref HEAD`
5. Use the ENGRAM KB MCP tool `sync_article` with:
   - title: the extracted title
   - content_markdown: the full file content
   - source_agent: "claude_code"
   - repository: the git repository name (from step 3)
   - file_path: $ARGUMENTS
   - branch: the current git branch
   - reason: "Synced via /sync-to-engram-kb command"
6. Report the result: state whether the action was `"created"` or `"updated"`, the article title and `article_id`, and (if updated) the `supersedes_article_id`

If the MCP tool is not available, fall back to a direct API call:
```bash
curl -s -X POST https://engram.pvelua.net/api/articles/sync \
  -H "Authorization: Bearer $ENGRAM_PAT" \
  -H "Content-Type: application/json" \
  -d '{"title":"<title>","content_markdown":"<content>","creation_trigger":"external","source_context":{"agent":"claude_code","repository":"<repo>","file_path":"$ARGUMENTS","branch":"<branch>","reason":"Synced via /sync-to-engram-kb command"}}'
```

9.6.4 /find-in-engram-kb

Topic discovery across your KB articles. This calls find_related_articles — entity-graph PPR ranking, not title search — so it works even when the article titles don't mention your query verbatim. For exact-title lookups, ask Claude Code to use search_articles instead.

Find articles in the ENGRAM Knowledge Base related to the topic described in $ARGUMENTS.

This is a discovery command — it ranks KB articles by entity-graph PPR (Personalized PageRank), so it works even when the article titles don't mention your topic verbatim. Use it when you don't know an article's exact title, when you want a comparison set across several related articles, or when you're surveying what the KB has on a concept. For exact-title lookups, the `search_articles` MCP tool is a better fit.

Steps:
1. Use the ENGRAM KB MCP tool `find_related_articles` with:
   - query: $ARGUMENTS
   - limit: 10 (default; raise if the user asks for "more results")
2. Inspect the response. It carries:
   - `extracted_entities`: what entities were parsed from the query (Claude Haiku)
   - `resolved_entities`: which of those actually match NounPhrases in the user's KB
   - `articles`: ranked list with `article_id`, `title`, `score`, `matched_entities`, `excerpt`, `version`, `is_latest`
3. Report results in this shape:
   - One-line header summarizing the query and how many articles came back
   - For each article (top to bottom by score): the rank, title, score, the matched entities that drove the rank, and the excerpt
   - If `articles` is empty, explain *why* using the trail in the response:
     - No `extracted_entities` → the query was too generic or had no recognisable named entities; suggest rephrasing with concrete nouns
     - `extracted_entities` non-empty but `resolved_entities` empty → those entities don't exist in this user's KB; suggest a related broader term or `list_articles` to browse
     - Both populated but `articles` empty → the entities are in the graph but no articles connect strongly enough; suggest broadening the query or using `search_articles` for a title scan
4. **Do not** automatically call `get_article` for full content — that's a follow-up the user can request explicitly ("show me article #1" / "get full content for the top hit"). Surfacing only the ranked summaries first keeps the response scannable.

If the MCP tool is not available, fall back to a direct API call:
```bash
curl -s -X POST https://engram.pvelua.net/api/articles/find_related \
  -H "Authorization: Bearer $ENGRAM_PAT" \
  -H "Content-Type: application/json" \
  -d '{"query":"$ARGUMENTS","limit":10}'
```
Coding-session commands moved. /ingest-code-session and /find-in-engram-code now live on Coding & Build Timeline.

9.7 Claude Desktop instructions

Claude Desktop has no on-disk files, so content you add to ENGRAM from a Desktop chat should be filed under the chat that produced it (a :Conversation) as the provenance, not as a coding-agent file capture. The instructions below tell Claude Desktop to register the chat first, then link the article to it. Set them once at the account level and override per-project. Every ENGRAM write tool also takes a project argument so your content lands under a named project — the instructions set it for you.

These instructions cover Claude Desktop. For the other clients (Claude Code / Codex, Claude AI Chat, ChatGPT, Gemini, Cowork) and the full project-resolution model, see the operator guide docs/CLIENT_PROJECT_INSTRUCTIONS.md.

9.7.1 Global / Account Level Instructions

Open the Claude Desktop → Settings → General → Profile section and paste the text below into the Instructions for Claude box (“Claude will keep this in mind across chats and Cowork...”).

When using engram-kb MCP tools to save chat-originated content (something I drafted, pasted, or researched in THIS chat — not a real file you've read from disk):
  - Pass project: "<the current Project's name if I'm in one, otherwise 'desktop-chat'>" on every engram-kb tool call.
  - FIRST call `record_external_conversation` with:
    - source_agent: "claude_desktop"
    - external_project: the project name (same value as `project`)
    - conversation_ref: a stable identifier for this chat (e.g. "<project>/<chat title>" or a short slug). REUSE the same value across calls in the same chat so they append, not duplicate.
    - summary: 1–2 sentences on what this chat worked on.
    - project: the project name.
  - THEN use `create_article` (never `sync_article` — there is no on-disk file) with:
    - source_agent: "claude_desktop"
    - project: the project name.
    - source_conversation_agent / source_conversation_external_project / source_conversation_ref: the EXACT (source_agent, external_project, conversation_ref) tuple from the record_external_conversation call above. This links the article to the chat as a :Conversation (without it, the article would wrongly become an agent-capture :Context).
  - If I haven't given you a clear title, ask me to confirm one before calling the tool.
  - Always tell me the article_id and a one-line summary of what you saved after a successful create.

9.7.2 Project Level Instructions

Open the Claude Desktop → Chat → Projects. Click into the relevant project, scroll to the bottom, find the Instructions box, and paste the text below. This overrides the Global/Account level instructions for chats in this project — use it when a Chat project corresponds to a specific project that you are working on. As a result, all project chats land on the same :Project in ENGRAM after you recorded them to ENGRAM KB. If you do not have Projects concept, the account-level default is used.

For ENGRAM KB additions in this project, use project: "<project name>" (and external_project: "<project name>") on every engram-kb call. Other defaults from my account-level instructions apply unchanged.

9.8 Cowork integration

Claude Cowork is Anthropic's autonomous-loop runtime. ENGRAM's Knowledge Gap analysis surface is designed to plug into Cowork (or any other agent that can speak MCP): you give Cowork a schedule, it polls ENGRAM for fresh knowledge gaps, drafts closure proposals, and queues them in your Inbox for review. Cowork never approves or executes — you remain the gatekeeper.

The integration is a single MCP server + one PAT + one scheduled task. No webhooks, no separate service to host.

9.8.1 Daily ENGRAM KB gap-closure task

The task does three things on each run:

  1. Calls list_kb_gaps(severity="high", limit=10) to fetch what the gap detectors have flagged on the ENGRAM side since the last sweep.
  2. Iterates the items (cap at 5 per run, oldest first so the Inbox drains FIFO). For each one it picks the appropriate action_type from the gap-class map, grounds any drafts in your existing KB via find_related_articles, and submits one propose_gap_closure call in pending state.
  3. Stops. The Inbox is the next surface — you approve or dismiss from there; execution happens only on your explicit click.

That design keeps autonomous work safe: Cowork can run unattended for days without mutating your graph beyond the proposal queue. Quality rules (no hallucinated entities, cite existing ENGRAM articles, match the user's tone) are baked into the task body below.

9.8.2 Task markdown

Paste this verbatim into Cowork as the task body. The created_by stamp tags every proposal so you can filter "what did Cowork submit this quarter" in the Inbox.

Daily ENGRAM KB gap-closure draft pass.

Goal: triage today's high-severity Knowledge & Memory gaps, draft up to 5
PENDING closure proposals for the user to review in the ENGRAM Inbox panel,
and stop. The user is always the approver — never execute on their behalf.

────────────────────────────────────────────────────────────────────────
ANTI-FABRICATION GUARDRAILS — READ FIRST, THESE OVERRIDE EVERYTHING BELOW
────────────────────────────────────────────────────────────────────────
Your drafts document TOPICS for the user's personal KB. They are NOT
documentation of how ENGRAM itself is built. Do NOT assert how ENGRAM
works — its ranking algorithm, schema, services, retrieval/ingestion
mechanism, or storage — unless the exact claim is in grounding material
you actually read this run. When unsure, describe the concept generically
("a common Neo4j/LangChain pattern"), never "ENGRAM does X".

  G1. Don't state ENGRAM internals you can't ground this run.
  G2. Bridges name REAL shared entities, never invented mechanisms.
  G3. The KB is not ground truth — articles may be drafts, superseded,
      or from a different project.
  G4. Thin grounding (fewer than ~2 solid sources) → SKIP, don't synthesize.
  G5. Hedge unverified claims; calibrate confidence; below ~0.4, SKIP.

ENFORCED: a server-side fact-check judge verifies every drafted article's
ENGRAM-internal claims before your proposal reaches the inbox. Drafts that
misstate how ENGRAM works are auto-rejected — ground each claim or SKIP.

────────────────────────────────────────────────────────────────────────
ACTION-TYPE MAP (gap_type → action_type)
────────────────────────────────────────────────────────────────────────
  coverage_high_freq_np                  → draft_article
  coverage_rich_conversation             → draft_article
  structural_orphan_entity               → draft_article
  structural_community_isolation         → draft_bridge_article
  structural_semantic_proximity          → draft_bridge_article
                                           (community_a + community_b are
                                           semantically close but
                                           graph-disconnected; use the
                                           evidence's `community_a_label`
                                           and `community_b_label` as the
                                           two ends of the bridge)
  structural_memory_article_disconnect   → propose_alias (preferred when
                                           evidence carries a confident
                                           synonym pair) OR
                                           draft_bridge_article (fallback)
                                           — see step 3b
  structural_extraction_failure          → re_extract       (no draft)
  memory_sparse_consolidation            → re_consolidate   (no draft)
  memory_vocab_mismatch                  → propose_alias
  memory_recall_desert                   → propose_alias
  structural_ppr_failure                 → SKIP — maps to "investigate", not
                                           an executable closure. Report it as
                                           a KNOWN non-actionable type, NOT an
                                           "unknown gap_type".
  memory_importance_orphan               → SKIP — maps to "surface", not an
                                           executable closure. Report as above.

Picking between draft_article and draft_bridge_article:
  - draft_article         — when filling a single missing topic.
  - draft_bridge_article  — when LINKING an isolated cluster/memory to
                            the wider KB via 2-3 shared bridge entities.

────────────────────────────────────────────────────────────────────────
REQUIRED ARGS BY ACTION_TYPE
────────────────────────────────────────────────────────────────────────
  draft_article / draft_bridge_article
    item_id, action_type, proposed_title, draft_excerpt (≤400 chars,
    the Inbox pitch), draft_markdown (full draft), confidence (0.0-1.0),
    created_by

  propose_alias
    item_id, action_type, alias_primary_id, alias_alias_id, confidence,
    created_by

  re_extract / re_consolidate
    item_id, action_type, draft_excerpt (1-2 sentences explaining what
    will be re-run and why), created_by

────────────────────────────────────────────────────────────────────────
DRAFT STYLE (draft_article + draft_bridge_article)
────────────────────────────────────────────────────────────────────────
  - 400-800 words of markdown.
  - H1 title (matches proposed_title).
  - Short opening paragraph orienting the reader.
  - Body: 3-6 sections, technical, terse, decision-focused. Match the
    register of the user's existing articles surfaced via
    find_related_articles.
  - For draft_bridge_article: explicitly name 2-3 bridge entities in the
    body that link the gap's subject to the rest of the KB.
  - Final "## Related ENGRAM articles" section listing the articles you
    actually referenced (title + one-line note on the relationship).
  - Do NOT invent entities, articles, or facts you can't ground in
    find_related_articles output.

────────────────────────────────────────────────────────────────────────
WORKFLOW
────────────────────────────────────────────────────────────────────────
1. Call list_kb_gaps(severity="high", limit=10).
   - If empty, STOP and report "no high-severity gaps today."
   - Skip any item where dismissed=true or dismissed_reason starts with
     "Closed by proposal".

2. Cap at 5 proposals per run. Pick the 5 OLDEST open items (ascending
   by created_at) so the Inbox drains FIFO; if fewer than 5 open items
   exist, do all of them.

3. For each selected item:
   a. Look up action_type for item.gap_type in the map above. If the
      gap_type is not in the map, SKIP and note it.

   b. SPECIAL CASE — structural_memory_article_disconnect:
      The evidence carries these fields directly:
        - evidence.disconnected_entities — list of ≤10 {identifier, name}
          pairs (memory-side NounPhrases NOT mentioned in the article)
        - evidence.article_entities      — list of ≤10 {identifier, name}
          pairs (article-side NounPhrases)
      Scan the two lists for ONE obvious synonym pair — exact name
      match, acronym ↔ spelled-out (DPF ↔ "Diesel Particulate Filter"),
      singular ↔ plural, hyphen variation, etc. Prefer a SAME-entity_type
      pair: cross-entity_type aliases are rejected (400) at execute time,
      so treat a cross-type "synonym" as no confident pair and fall through
      to the bridge draft.
        - If a confident (≥0.85) pair exists:
            action_type      = "propose_alias"
            alias_primary_id = article-side identifier (the canonical)
            alias_alias_id   = memory-side identifier (the alias)
            confidence       = 0.85-0.95
        - Otherwise:
            action_type = "draft_bridge_article"
            Follow the draft-style rules above. Name 2-3 shared concepts
            that link the memory's topic to the article's content.
      Do NOT call find_related_articles for the alias scan — the
      evidence has what you need.

   c. For draft_article / draft_bridge_article items in any OTHER class
      (coverage_*, structural_orphan_entity, structural_community_isolation,
      structural_semantic_proximity, and the 3b draft-fallback case):
        - GROUNDING TERM depends on the gap class:
            • coverage_* / structural_orphan_entity → the missing topic
              (evidence entity_name / title).
            • structural_community_isolation → evidence.label (the isolated
              community's label).
            • structural_semantic_proximity → call find_related_articles
              TWICE: once with evidence.community_a_label and once with
              evidence.community_b_label. The bridge links these two
              communities.
        - Call find_related_articles with that term to ground the draft.
        - If results are thin, try ONE more query derived from a related
          concept in the evidence.
        - If both come back empty, SKIP the item and note "no ground
          material" — do not fabricate.
        - For draft_bridge_article, name 2-3 shared bridge entities drawn
          from the grounding results that connect the two ends.
        - Draft per the style rules above.

   d. For re_extract / re_consolidate: no draft — submit with a short
      draft_excerpt explaining why
      (e.g. "Article has N passages, 0 NounPhrase edges — re-extract
      should restore entity coverage").

   e. For propose_alias on memory_vocab_mismatch / memory_recall_desert:
      pick the pair from evidence; confidence ≥0.85 if obviously
      synonymous, 0.6-0.85 for a judgment call.

   f. Submit ONE propose_gap_closure per item with:
        - created_by = "cowork_daily_<YYYY_MM_DD>" (today's date, UTC,
                       underscores, e.g. cowork_daily_2026_05_19)
        - confidence  = 0.5 for draft variants unless a rule above
                        prescribes otherwise
        - All required args per the table above.

4. Report at the end:
   - Total proposals drafted, broken down by action_type.
   - For each proposal: proposal_id + item_id + gap_type +
     proposed_title (or alias pair for propose_alias).
   - Items skipped + reason (no ground material / unknown gap_type /
     no confident alias pair / dismissed).
   - Any tool calls that returned empty or surprising results.

────────────────────────────────────────────────────────────────────────
RULES
────────────────────────────────────────────────────────────────────────
- One proposal per gap item. If propose_gap_closure returns 4xx, report
  the error and move on — do not retry on the same item.
- Do NOT call execute_gap_closure under any circumstances.
- Do NOT call list_kb_gaps a second time mid-run.
- If propose_gap_closure returns 422 on `created_by`, your date string
  is malformed — fix once and retry.
- One pass. No exploration beyond find_related_articles for grounding.

9.8.3 Scheduling it in Cowork

Cowork's task surface has two configuration steps for an ENGRAM gap-closure schedule:

  1. Register the MCP server — under Cowork's MCP Servers tab, add an HTTP MCP server pointing at https://engram.pvelua.net/mcp/ with the Authorization: Bearer engram_pat_… header you minted in §9.4 API Keys. The trailing slash on /mcp/ is required.
  2. Create the task — give it a short description (e.g. "Daily ENGRAM KB gap closure"), paste the task markdown from §9.8.2 as the body, and set the schedule. Once per 24 hours is the sweet spot — that matches how often the server-side gap scheduler refreshes detectors and avoids spamming the Inbox with duplicate proposals.
Cowork posts to your Inbox, not your KB. The proposals land in Knowledge Base → Knowledge Health → Proposals in pending state. Review them at your own cadence; approving an article-draft proposal triggers article creation through the normal pipeline, with the same passage-extraction + entity-linking steps any other article goes through.

For the full operator guide (MCP transport choice, troubleshooting 4xx responses, recovering from the rare "no ground material" sweep), see docs/ENGRAM_KB_GAP_COWORK_INTEGRATION.md in the project repository.

9.9 Installing the ENGRAM Watcher (code-session ingest)

The ENGRAM Watcher is a small standalone CLI that ships your local Claude Code session logs (~/.claude/projects/**/*.jsonl) into your ENGRAM KB, so past coding sessions become retrievable from chat and via the coding-session tools (§9.6.5). It only decides "is this session file new or changed?" and streams the bytes upstream — all parsing, redaction, and graph writes happen server-side. Machines running the watcher show up under §9.5 Hosts.

Requires code-session ingest to be enabled. That's an operator setting. If the watcher reports 403 service disabled, ask whoever runs your ENGRAM deployment to turn code-session ingest on — until then the watcher runs but uploads are rejected.

Step 1 · Prerequisites

Step 2 · Install

One command — no repository access required. uv downloads the wheel and drops a single engram-watcher executable on your $PATH:

uv tool install "engram-watcher @ https://pvelua.net/downloads/engram_watcher-0.1.0-py3-none-any.whl"

Verify with engram-watcher --help. (Prefer pip? pip install "https://pvelua.net/downloads/engram_watcher-0.1.0-py3-none-any.whl" works too.) To update to a newer build later, re-run the install with an added --reinstall flag.

Step 3 · Configure

Only one value is required — your PAT. The server URL is built into the wheel (https://engram.pvelua.net), so you don't need to set it. Add to your shell profile (~/.zshrc or equivalent):

export ENGRAM_API_KEY="engram_pat_your_token_here"

# optional — a friendly machine name shown in Settings → Hosts
# export ENGRAM_WATCHER_HOSTNAME="My MacBook"
# optional — only if you point at a non-default deployment
# export ENGRAM_ORCHESTRATOR_URL="https://engram.pvelua.net"

Run source ~/.zshrc (or open a new terminal) so the token reaches the next invocation.

Step 4 · Run

Three modes:

engram-watcher --backfill            # one-shot: ship existing session history
engram-watcher --watch --verbose     # live: ship sessions as you code (leave running)
engram-watcher --dry-run             # local parse + report only, no upload

A typical first setup is one --backfill to capture history, then --watch left running in the background for ongoing sessions. The watcher keeps a small local cursor (~/.engram/code-session-watcher.db) so it never re-uploads an unchanged file.

Step 5 · Verify

After your next non-trivial Claude Code session settles, open Settings → Hosts (§9.5) — your machine appears as a new host row — and the session itself shows up under the Coding Sessions tab. Set a friendly host label if you like; it propagates everywhere that session is shown.