Ydy4HYW7ExA

Claude Habitat

Community Ydy4HYW7ExA
Updated

Claude Habitat — MCP server for project context, workflows, knowledge, and skills

Claude Habitat

An MCP (Model Context Protocol) server that provides persistent project context, workflow management, and knowledge capture for AI coding agents.

What It Does

Claude Habitat gives AI agents structured memory across sessions:

  • Project Context — track project profile, conventions, tech stack, and document chain architecture for flexible context management
  • Workflow Management — 8-phase workflows with gate checks, records, and phase transitions
  • Knowledge Base — persistent patterns, lessons, insights, and preferences across projects
  • Skill System — 23 executable skill protocols with shared knowledge modules and @import resolution
  • Technical Debt — automated scanning, scoring, trend analysis, and remediation tracking
  • Language Support — detect project languages and set communication preferences

Key Numbers

  • 34 MCP tools across 9 namespaces
  • 23 skills with 111 shared knowledge modules
  • 6 behavior rules (auto-injected)
  • 6 custom slash commands
  • 6 debt detectors with weighted scoring

Installation

Prerequisites

  • Node.js 18+
  • npm or pnpm
  • Claude Code CLI (for MCP integration)

Setup

# Clone the repository
git clone <repo-url> claude-habitat
cd claude-habitat

# Install and register (builds, installs assets, registers MCP server, installs hooks)
node scripts/install.mjs

Manual Setup

If you prefer manual setup:

npm install
npm run build
npx tsx packages/mcp/src/index.ts

Register as MCP Server

The installer registers automatically. For manual registration, add to ~/.claude.json:

{
  "mcpServers": {
    "habitat-mcp": {
      "command": "node",
      "args": ["/path/to/claude-habitat/packages/mcp/dist/index.js"]
    }
  }
}

Initialize a Project

Once the MCP server is running, initialize your project:

/habitat-init

This scans the current directory, detects the tech stack, and creates a project profile with a .claude-habitat/marker.json marker file.

Configuration

Data Directory

All persistent data is stored in ~/.claude-habitat/ by default. Override with the HABITAT_DATA_DIR environment variable:

export HABITAT_DATA_DIR=/path/to/custom/data

Directory Structure

~/.claude-habitat/
├── projects/{project_id}/
│   ├── profile.json          # Project profile (name, path, tech stack)
│   └── conventions.json      # Project conventions
├── workflows/{workflow_id}.json  # Workflow state and records
├── knowledge/{category}/{id}.json  # Knowledge entries
├── lang/{project_id}.json    # Language preferences
└── debt/{project_id}/reports/    # Debt scan reports

{project_dir}/docs/context/   # Document chain (project-local)
├── .chain-index.json         # Link metadata
└── {dimension}/{doc}.md      # Document nodes

Project Marker File

Each initialized project has a .claude-habitat/marker.json marker file in its project directory:

{
  "project_id": "e9939649-364b-464c-b1d9-0253fd8cc748",
  "created_at": "2026-02-07T..."
}

This file is the single source of truth for project identity. Never hardcode or cache project_id across sessions.

MCP Tools Reference

Claude Habitat exposes 34 tools across 9 namespaces via the Model Context Protocol.

Project Namespace (5 tools)

project_init

Initialize a project by scanning its directory.

Parameter Type Required Description
path string yes Absolute path to the project directory

Returns: Project profile with detected tech stack, directory structure, and generated project_id.

project_get_context

Get full project context including profile and conventions.

Parameter Type Required Description
project_id UUID yes Project identifier
project_set_convention

Set a convention for a project.

Parameter Type Required Description
project_id UUID yes Project identifier
category string yes Convention category (e.g. "naming", "testing")
rule string yes The convention rule text
examples string[] no Example usages
project_get_conventions

Get all conventions for a project.

Parameter Type Required Description
project_id UUID yes Project identifier
project_update_profile

Update a project profile.

Parameter Type Required Description
project_id UUID yes Project identifier
updates object yes Fields to update

updates object fields (at least one required):

  • name (string) — project name
  • description (string) — project description
  • tech_stack (string[]) — technology stack entries

Workflow Namespace (6 tools)

workflow_start

Start a new workflow for a project.

Parameter Type Required Description
project_id UUID yes Project identifier
type enum yes feature, bugfix, refactor, or chore
title string yes Workflow title
description string no Detailed description

Returns: New workflow with generated workflow_id, initial phase set by type.

workflow_get_status

Get the current status of a workflow.

Parameter Type Required Description
workflow_id UUID yes Workflow identifier
workflow_transition

Transition a workflow to a new phase.

Parameter Type Required Description
workflow_id UUID yes Workflow identifier
to_phase string yes Target phase name
gate_checklist array yes Gate check items (min 1)

Each gate checklist item: { item: string, passed: boolean, evidence?: string }

workflow_record

Add a record to a workflow.

Parameter Type Required Description
workflow_id UUID yes Workflow identifier
type enum yes decision, finding, blocker, progress, or artifact
content string yes Record content
metadata object no Arbitrary metadata
workflow_list

List workflows for a project.

Parameter Type Required Description
project_id UUID yes Project identifier
status enum no Filter by active or completed
workflow_complete

Complete a workflow.

Parameter Type Required Description
workflow_id UUID yes Workflow identifier
outcome enum no completed or abandoned (default: completed)
summary string yes Completion summary

Knowledge Namespace (5 tools)

knowledge_save

Save a knowledge entry.

Parameter Type Required Description
category enum yes pattern, preference, lesson, insight, or evaluation
title string no Entry title
content string yes Knowledge content
tags string[] yes Tags for retrieval
source object no { project_id?: UUID, workflow_id?: UUID }
knowledge_recall

Recall knowledge entries by ID or filter. At least one of knowledge_id, category, or tags is required.

Parameter Type Required Description
knowledge_id UUID no Specific entry ID
category enum no Filter by category
tags string[] no Filter by tags
knowledge_search

Search knowledge entries by text query.

Parameter Type Required Description
query string yes Search query
category enum no Filter by category
limit number no Max results (max 50)
knowledge_list

List knowledge entries.

Parameter Type Required Description
category enum no Filter by category
limit number no Max entries to return
knowledge_forget

Delete a knowledge entry.

Parameter Type Required Description
knowledge_id UUID yes Entry to delete

Lang Namespace (4 tools)

lang_detect

Detect programming languages in a project directory.

Parameter Type Required Description
project_id string yes Project identifier
lang_translate

Translate text to a target language.

Parameter Type Required Description
text string yes Text to translate
target_language string yes Target language code
source_language string no Source language code
lang_set_preference

Set language preference for a project.

Parameter Type Required Description
project_id string yes Project identifier
language string yes Preferred language
lang_get_preference

Get language preference for a project.

Parameter Type Required Description
project_id string yes Project identifier

Skill Namespace (1 tool)

skill_resolve

Resolve a skill file with all @import directives linked into a single document.

Parameter Type Required Description
skill_name string yes Skill name (matches directory under assets/.claude/skills/)
max_depth number no Max import resolution depth (1-10, default 5)

Returns: Fully resolved skill protocol with all imported shared modules inlined.

Context Namespace (2 tools)

context_bundle

Concatenate multiple files into a single response with separators.

Parameter Type Required Description
paths string[] yes File paths to concatenate (1-20)
max_total_lines number no Line limit (1-5000)
separator string no Custom separator between files
convention_check

Check if a file follows project conventions.

Parameter Type Required Description
project_id UUID yes Project identifier
file_path string yes Path to file to check
content string no File content (reads from disk if omitted)

Doc Namespace (7 tools)

doc_link

Create a bidirectional link between two documents in the document chain.

Parameter Type Required Description
project_id UUID yes Project identifier
from_doc string yes Source document path
to_doc string yes Target document path
label string no Link label/description
doc_unlink

Remove a link between two documents.

Parameter Type Required Description
project_id UUID yes Project identifier
from_doc string yes Source document path
to_doc string yes Target document path
doc_read

Read a document and its metadata from the document chain.

Parameter Type Required Description
project_id UUID yes Project identifier
doc_path string yes Document path

Returns: Document content, metadata, and outbound links.

doc_write

Write or update a document in the document chain.

Parameter Type Required Description
project_id UUID yes Project identifier
doc_path string yes Document path
content string yes Document content
metadata object no Document metadata
doc_traverse

Traverse the document chain from a starting document.

Parameter Type Required Description
project_id UUID yes Project identifier
start_doc string yes Starting document path
max_depth number no Maximum traversal depth (default: 3)
filter object no Filter criteria for traversal

Returns: Graph of connected documents with their links and metadata.

doc_init_dimension

Initialize a dimension in the document chain with root doc and scaffold.

Parameter Type Required Description
project_id UUID yes Project identifier
name string yes Dimension name
sources string[] no Source document paths
auto_refresh boolean no Enable auto-refresh (default: false)
refresh_strategy string no Refresh strategy description
doc_sync

Scan project facts and sync auto-generated docs (README sections, CLAUDE.md counts).

Parameter Type Required Description
project_id UUID yes Project identifier
mode enum no check or update (default: update)

Returns: Facts summary, list of updated/stale files, and update counts.

Prompt Namespace (1 tool)

prompt_assemble

Assemble a prompt from document chains with intelligent ordering and deduplication.

Parameter Type Required Description
project_id UUID yes Project identifier
entry_points string[] yes Starting document paths (1-10)
max_depth number no Maximum traversal depth (default: 2)
max_tokens number no Approximate token budget (default: 50000)

Returns: Assembled prompt text with documents ordered by dependency and relevance.

Debt Namespace (3 tools)

debt_scan

Scan project for technical debt and produce a quantified report.

Parameter Type Required Description
project_id UUID yes Project identifier
scope enum no full or changed (default: full)
categories enum[] no Filter: structure, pattern, evolution, consistency

Returns: Quantified report with score (0-100), item counts by severity, and individual debt items.

debt_report

Query historical debt scan reports with comparison.

Parameter Type Required Description
project_id UUID yes Project identifier
limit number no Max reports to return (1-50, default 5)
since string no ISO date string to filter from
debt_trend

Analyze debt score trends, detect convergence/divergence, identify stubborn items.

Parameter Type Required Description
project_id UUID yes Project identifier
window number no Number of reports to analyze (2-100, default 10)

Returns: Trend direction (converging/stable/diverging), score trajectory, and stubborn items that persist across scans.

Skill System

Claude Habitat includes 23 executable skill protocols and 111 shared knowledge modules. Skills define structured execution steps for specific task types.

How Skills Work

  1. Agent identifies the matching skill based on task type
  2. Calls skill_resolve(skill_name) to load the full protocol
  3. The resolver recursively inlines all @import directives (max depth 5)
  4. Agent follows the loaded protocol step by step

Each skill has a modular structure: SKILL.md (entry, <30 lines) + protocol.md + context.md + gates.md, linked via @import.

Skill Categories

Workflow Skills (7)
Skill Description
requirements-analysis Extract requirements, define acceptance criteria, and identify edge cases for a feature or change
design Create architectural specs, API contracts, and technical design decisions
implementation Write production code following design specs and project conventions
test-driven-development Write tests before implementation, define test strategy and coverage targets
code-review Analyze code quality, check conventions, identify bugs, security issues, and verify completion readiness
finishing-a-development-branch Guide branch completion: merge readiness, PR preparation, cleanup
release Version release, CHANGELOG update, branch merge, and deployment verification
Operational Skills (5)
Skill Description
adaptive-dispatch Recursive task decomposition: split or execute based on complexity
systematic-debugging Methodically diagnose bugs using hypothesis-driven investigation
quick-fix Fast path for small bug fixes: reproduce, fix, verify
refactor Restructure code without changing behavior: safety net first, then transform
mentor Explain concepts, answer questions, and capture reusable lessons
Debt Management Skills (3)
Skill Description
debt-audit Scan, analyze, and plan remediation for technical debt
debt-fix Drive technical debt remediation based on audit results
archive-rebuild Archive legacy code and rebuild from clean contracts
Infrastructure Skills (5)
Skill Description
project-init Initialize a new project profile by scanning directory and setting conventions
project-commander Display project overview, active workflows, knowledge inventory, and resume interrupted sessions
writing-skills Guide creation of new skill files following the modular skill format
using-git-worktrees Create and manage isolated git worktrees for parallel development
language-strategy Detect and apply user language preferences for communication
Knowledge & Docs Skills (2)
Skill Description
knowledge-harvest Capture reusable patterns, lessons, and insights at workflow completion
doc-update Update document chain, propagate changes, and maintain summaries
Hook-Driven Skills (1)
Skill Description
prompt-restructure Pure attention optimization for prompts — used by the prompt-restructure CLI tool via claude headless mode

Shared Knowledge Modules (111)

Skills reference shared modules via @import shared/path/to/module. The skill_resolve tool recursively inlines all imports.

  • 28 core modules (coding principles, patterns, delegation, design)
  • 83 language-specific modules across 14 languages
  • Languages: cpp, csharp, dart, go, java, kotlin, php, python, ruby, rust, scala, shell, swift, typescript

Architecture

Overview

Claude Habitat is an MCP (Model Context Protocol) server built with TypeScript. It runs as a stdio-based server process that AI coding agents connect to for persistent project context.

Entry Point

packages/mcp/src/index.ts — Registers all tools with the MCP server, wraps each handler with wrapHandler() for consistent error boundaries, and starts the stdio transport.

Source Layout

packages/
├── mcp/                    # MCP server (core)
│   ├── src/
│   │   ├── index.ts              # MCP server entry point
│   │   ├── constants.ts          # Shared constants (phases, categories, patterns)
│   │   ├── types/index.ts        # Core TypeScript interfaces
│   │   ├── storage/
│   │   │   ├── file-store.ts     # readJSON, writeJSON, exists, listFiles, removeFile
│   │   │   └── paths.ts          # Data directory path resolution
│   │   ├── validation/
│   │   │   └── schemas.ts        # Zod schemas for all tools
│   │   └── tools/
│   │       ├── project/          # init, get-context, set-convention, get-conventions, update-profile
│   │       ├── workflow/         # start, get-status, transition, record, list, complete
│   │       ├── knowledge/        # save, recall, search, list, forget
│   │       ├── lang/             # detect, translate, set-preference, get-preference
│   │       ├── skill/            # resolve
│   │       ├── context/          # bundle, convention-check
│   │       ├── doc/              # link, unlink, read, write, traverse, init-dimension, sync
│   │       ├── prompt/           # assemble
│   │       └── debt/             # scan, report, trend + scoring + detectors/
│   └── tests/
│       ├── unit/{namespace}/     # Unit tests per handler
│       └── integration/          # Cross-namespace integration tests
├── prompt-restructure/     # CLI tool for hook-driven prompt optimization
│   └── index.mjs
scripts/                    # install.mjs, uninstall.mjs
assets/.claude/             # skills/, commands/, rules/, hooks.json

Request Flow

  1. MCP client sends a tool call via stdio
  2. McpServer routes to the registered handler
  3. wrapHandler() catches errors and normalizes responses
  4. Handler validates input with Zod schema
  5. Handler reads/writes JSON files via file-store.ts
  6. Response returned as { content: [{ type: 'text', text }], isError? }

Storage Layer

All data persists as JSON files under ~/.claude-habitat/ (configurable via HABITAT_DATA_DIR).

  • Atomic writes: writeJSON writes to a .tmp file then renames for crash safety
  • Path safety: All project paths validated to be under $HOME or /tmp
  • No database: Pure filesystem storage, no external dependencies

Workflow Engine

8-phase lifecycle with gate checks between transitions:

Requirements → Design → Prototype → Test Construction → Production Implementation → Full Test Suite → Audit → Release
  • Workflows are typed: feature, bugfix, refactor, chore
  • Each type has a shortcut starting phase (e.g. chore starts at Production Implementation)
  • Phase transitions require a gate checklist with evidence
  • All decisions, findings, and blockers are recorded as workflow records

Document Chain Architecture

Flexible graph-based context management:

  • Documents are nodes in a directed graph with bidirectional links
  • @import (downward) and @referenced-by (upward) — both updated atomically
  • Any document is an entry point — traverse up or down from anywhere
  • Dynamic dimensions configured via doc_init_dimension
  • 8 MCP tools: doc_link, doc_unlink, doc_read, doc_write, doc_traverse, doc_init_dimension, doc_sync, prompt_assemble

MCP Server · Populars

MCP Server · New