# Codemap

> A universal suite of MCP-native and node.js API tools for agentic AI, researchers, and developers to map, knowledge-graph, and work with structured code and other artifacts.

- **Type:** MCP server
- **Install:** `agentstack add mcp-egentica-codemap`
- **Verified:** Pending review
- **Seller:** [egentica](https://agentstack.voostack.com/s/egentica)
- **Installs:** 0
- **Category:** [Integrations](https://agentstack.voostack.com/c/integrations)
- **Latest version:** 0.1.0
- **License:** Apache-2.0
- **Upstream author:** [egentica](https://github.com/egentica)
- **Source:** https://github.com/egentica/codemap
- **Website:** https://egentica.ai

## Install

```sh
agentstack add mcp-egentica-codemap
```

Requires the [AgentStack CLI](https://agentstack.voostack.com/docs/cli). Works with Claude Code, Cursor, and any MCP-compatible agent.

## About

# @egentica/codemap

> Universal code knowledge graph designed for Agentic AI systems

[](https://www.npmjs.com/package/@egentica/codemap)
[](https://opensource.org/licenses/Apache-2.0)
[](https://egentica.ai)
[](https://github.com/egentica/codemap)
[](https://github.com/egentica/codemap)

**CodeMap is hyperfocused on empowering AI agents like Claude to understand, navigate, and modify codebases with deep contextual awareness.** Built on AST-based parsing and a comprehensive knowledge graph, CodeMap gives AI agents the structural understanding they need to work effectively across sessions.

**CodeMap is free and open source software, licensed under the [Apache License 2.0](./LICENSE.md).** Published by **Zapshark Technologies LLC** under the [Egentica](https://egentica.ai) brand — a growing suite of open-source agentic research, assistant, and developer tools.

> 📚 **Full interactive documentation with live examples is available at [egentica.ai](https://egentica.ai)**

## Why CodeMap for AI Agents?

Traditional code tools assume a human developer with persistent memory and visual context. AI agents work differently:

- **🤖 Session-based workflow** - AI agents need explicit orientation at session start, not implicit IDE context
- **🧠 Context management** - Limited context windows require smart organization (labels, groups, annotations)
- **📋 Guided workflows** - Checklists ensure AI agents follow project-specific rules and policies
- **🔄 Session continuity** - Automatic tracking bridges the gap between conversations
- **🎯 Semantic organization** - Labels and groups create searchable, meaningful structure
- **🔍 Architecture enforcement** - Audit rules validate code structure and prevent violations
- **🔌 Extensible scripts** - Custom validation, build automation, and workflow scripts

**CodeMap treats AI agents as first-class citizens**, not as an afterthought to a human-focused tool.

## Features

- **🤖 AI-First Design** - Session workflow, checklists, and context management built for AI agents
- **🚀 Zero Configuration** - Works out of the box with Node.js, no setup required
- **🔍 Deep Code Understanding** - AST-based parsing with symbol extraction, dependency tracking, and symbol-level call graph
- **🕸️ Symbol Call Graph** - Track which symbols call which across files, with `calls`/`calledBy` on every symbol
- **🔌 Bundled Parsers** - TypeScript/JavaScript, Vue, and PHP support included
- **📊 Knowledge Graph** - Build relationships between files, symbols, and dependencies
- **🎯 Smart Search** - Keyword search, symbol search, hybrid search, AI-powered relevance ranking, and cross-store category search (groups, help, annotations, routines, symbols)
- **🤖 Agent-Optimized Output** - When running via MCP, responses include emoji signals (✅⚠️📭💡), plain-language insights, and `drillDown` hints. Use `summary: true` for a zero-bloat landscape scan before targeted follow-up.
- **🔄 Auto-Recovery** - MCP server silently recovers the last active project on startup after unexpected restarts (crashes, Claude Desktop timeouts). A clean `codemap_close` deletes the recovery state so switching projects always starts fresh.
- **📝 File Summaries** - Heuristic JSDoc extraction populates summaries automatically on every scan. Agent-written summaries persist in `.codemap/summaries.json`, override heuristics, and are searchable — files match queries on their documented purpose even if the keyword isn't in the filename.
- **🏷️ Labels & Groups** - AI agents organize code semantically for better context management
- **📋 Session Checklists** - Guide AI agents through project-specific workflows and policies
- **📝 Session Tracking** - Automatic change tracking and history across conversations
- **🛡️ Architecture Validation** - Audit system with 5 rule types and custom scripts
- **⚙️ Script System** - Extend with custom audit/build/orient/close/utility scripts
- **⚡ Macro System** - Create reusable shell command shortcuts with multi-shell support
- **🔄 Routine System** - Combine checklists, macros, scripts, templates, and help topics into automated workflows
- **📄 Template System** - Reusable code scaffolds for tools, utilities, and components
- **🔙 File History & Rollback** - Session-scoped automatic backups with instant rollback for quick recovery
- **💾 Backup System** - Hybrid daily + turn-based backups with restore capability for persistent storage
- **🔧 MCP Server** - Built-in Model Context Protocol server for Claude and other AI systems

## Installation

```bash
npm install @egentica/codemap
```

**Bundled language parsers** (no additional packages needed):
- ✅ TypeScript/JavaScript (`.ts`, `.tsx`, `.js`, `.jsx`)
- ✅ Vue (`.vue` single-file components)
- ✅ PHP (`.php` - supports PHP 5.2 through 8.x)

## Core Concepts

### Position Indexing: 1-Based for Users, 0-Based Internally

**CodeMap uses 1-based indexing for all user-facing positions** (line numbers, column numbers) to match editor conventions:

- **Line 1** = first line (like TypeScript errors, ESLint, VS Code, Git)
- **Column 1** = first character (like editor cursor positions)

This applies to:
- ✅ `codemap_read_file` offset parameter (line 1 = first line)
- ✅ `codemap_search` symbol positions (`startLine: 1, startCol: 1`)
- ✅ `codemap_search_in_files` match positions (`line: 1, column: 1`)
- ✅ `codemap_search_elements` DOM element positions
- ✅ `codemap_group_notate` line parameter
- ✅ Error positions in validation results
- ✅ All SymbolEntry and ElementEntry fields

**Internally**, CodeMap converts to 0-based array indices where needed (e.g., `lines[0]` = line 1). This conversion is transparent to API users.

**Why this matters for AI agents:**
- When you see `startLine: 42, startCol: 8` in a symbol, that's line 42, column 8 in the editor
- When calling `codemap_read_file(offset: 1)`, you're reading from line 1, not line 0
- When an error says "line 10, column 5", that's exactly where it is in the editor

This consistency eliminates confusion and makes CodeMap's API intuitive for both humans and AI agents.

## Command Line Interface (CLI)

CodeMap includes a fast, lightweight CLI for querying code from shell scripts, wrapper packages (PHP/Python/Ruby), and external tools.

### Quick Start

```bash
# Scan project and build knowledge graph
codemap scan

# Show project statistics
codemap stats --format table

# Search for files and symbols
codemap search "AuthService"

# Show dependencies for a file
codemap deps src/services/auth.ts

# List symbols in a file
codemap symbols src/utils/helpers.ts --format json

# Export full graph as JSON
codemap export > graph.json
```

### Performance Optimization

CodeMap automatically caches the knowledge graph for 10-50x faster CLI operations:

- **First scan**: 1-5 seconds (builds complete graph)
- **Subsequent commands**: 50-200ms (loads from cache)

The graph is automatically saved to `.codemap/graph.json` when you create a `.codemap/` directory in your project:

```bash
# Enable graph caching (creates .codemap/ directory)
mkdir .codemap

# First scan builds and caches the graph
codemap scan

# All future commands load instantly from cache
codemap stats        # ~50-200ms
codemap search "..."  # ~50-200ms
codemap deps file.ts  # ~50-200ms
```

**Note**: The cache is updated when you run `codemap scan`. For long-running sessions where files change frequently, you may want to re-scan periodically.

### CLI Commands

| Command | Description | Output Format |
|---------|-------------|---------------|
| `scan [dir]` | Scan directory and build/update graph | JSON |
| `stats` | Show project statistics (files, symbols, deps) | JSON, table, compact |
| `search ` | Search for files and symbols | JSON, table, compact |
| `deps ` | Show dependencies for a file | JSON, table, compact |
| `symbols ` | List all symbols in a file | JSON, table, compact |
| `export` | Export complete graph as JSON | JSON |

### Output Formats

Use `--format` to control output style:

```bash
# JSON (default) - machine-readable
codemap stats --format json

# Table - human-readable tabular output
codemap stats --format table

# Compact - minimal one-line output
codemap stats --format compact
```

### Use Cases

**Wrapper Packages**: Build language-specific libraries (PHP, Python, Ruby) that maintain a persistent CodeMap instance and expose a native API:

```php
// PHP wrapper example
$codemap = new CodeMap('/path/to/project');
$stats = $codemap->getStats();
$symbols = $codemap->getSymbols('src/User.php');
```

**Shell Scripts**: Integrate into build scripts, CI/CD pipelines, or automation:

```bash
#!/bin/bash
# Pre-commit hook: check for architecture violations
codemap scan
if codemap audit | grep -q "error"; then
  echo "Architecture violations detected!"
  exit 1
fi
```

**Editor Integration**: Query code structure from text editors or IDEs that don't support LSP.

## Example Prompts for AI Agents

Here are example prompts you can use when working with CodeMap:

### Getting Started
```
"Orient me to this codebase"
"Show me the project overview and any outstanding tasks"
"What are the current session checklists?"
```

### Navigation & Discovery
```
"Find all authentication-related files"
"Show me files that use the EventBus pattern"
"Find the LoginButton component and its dependencies"
"What files import the database module?"
"Show me all TypeScript interfaces in the project"
```

### Code Organization
```
"Label all files in src/auth/ as part of the authentication system"
"Create a group for the payment processing components"
"Show me all files labeled as 'work in progress'"
"Add a note to the auth-system group about the JWT expiry time"
```

### Architecture & Quality
```
"Run the audit to check for architecture violations"
"Are there any files with direct Node.js fs imports?"
"Check if all tool files have proper documentation"
"Find console.log statements outside of debug files"
```

### Code Analysis
```
"What would break if I change this function signature?"
"Show me all components that depend on UserContext"
"Find files related to user authentication"
"What's the blast radius of changing the API endpoint format?"
```

### File Operations
```
"Show me the LoginForm component implementation"
"Read the authentication middleware and show what it imports"
"Create a new utility function for date formatting"
"Replace all instances of 'getUserById' with 'findUserById'"
```

### Session Management
```
"Start a new session for refactoring the auth system"
"Write a handoff summary for the next session"
"What did I accomplish in the last session?"
"Close this session with a summary"
```

### Custom Scripts
```
"Create an audit script to validate API endpoint naming"
"Run my custom build validation script"
"Create a utility script to generate TypeScript types"
```

## Quick Start for AI Agents

### Session Workflow

AI agents should follow this workflow at the start of each conversation:

```typescript
// 1. Orient to the project
const orientation = await codemap.orient();
// Shows: stats, checklists, labels, groups, last session summary

// 2. Review the checklist
// Checklists remind AI agents of project-specific rules:
// - "Use clean-build.bat to build the package"
// - "Label files with architectural patterns as you encounter them"
// - "Review NEXT_SESSION.md for outstanding tasks"

// 3. Start a session (if creating files)
await codemap.sessions.start();

// 4. Work on the codebase
// ... search, read, edit, organize with labels/groups ...

// 5. Close the session with handoff
await codemap.sessions.close('Summary of work completed');
```

### Why This Matters

**Orient** gives AI agents the context they need to pick up where the last conversation left off. **Checklists** encode project-specific workflows that would otherwise get lost between sessions. **Session tracking** creates continuity across conversations.

## Architecture Validation

CodeMap includes a powerful audit system to enforce architectural rules and coding standards:

### Audit Rules

Create `.codemap/audit-rules.json` to define validation rules:

```json
{
  "version": "1.0",
  "rules": [
    {
      "id": "registries-in-core",
      "name": "Registry files must be in core",
      "type": "file-location",
      "enabled": true,
      "severity": "error",
      "config": {
        "filePattern": "*Registry.ts",
        "allowedPaths": ["src/core/"]
      }
    },
    {
      "id": "no-direct-fs-imports",
      "name": "Centralize fs operations",
      "type": "forbidden-import",
      "enabled": true,
      "severity": "error",
      "config": {
        "imports": ["node:fs", "fs", "node:path", "path"],
        "exemptFiles": ["src/core/FileSystemIO.ts"]
      }
    },
    {
      "id": "no-console-in-prod",
      "name": "No console.log in production",
      "type": "text-pattern",
      "enabled": true,
      "severity": "warning",
      "config": {
        "pattern": "console\\.log",
        "isRegex": true,
        "allowedFiles": ["src/debug/**"]
      }
    },
    {
      "id": "tools-need-docs",
      "name": "Tool files require annotations",
      "type": "required-annotation",
      "enabled": true,
      "severity": "info",
      "config": {
        "filePattern": "src/tools/**/*.tool.ts",
        "requiredAnnotations": ["@codemap.usage"],
        "requireAny": true
      }
    },
    {
      "id": "custom-validation",
      "name": "Run custom audit script",
      "type": "script",
      "enabled": true,
      "severity": "error",
      "config": {
        "script": "audit/api-versioning.js"
      }
    }
  ]
}
```

### 5 Rule Types

1. **file-location** - Enforce file placement (e.g., "all *Repository.ts files must be in src/data/")
2. **forbidden-import** - Restrict imports to specific files (e.g., centralize database access)
3. **text-pattern** - Search for code patterns with regex support
4. **required-annotation** - Ensure files have required @codemap annotations
5. **script** - Run custom JavaScript validation logic

### Run Audit

```typescript
// Check all rules
const result = await codemap.audit();

// Check specific rule
const result = await codemap.audit({ ruleId: 'no-direct-fs-imports' });

// Example result
{
  rulesRun: 3,
  filesChecked: 242,
  violationCount: 12,
  violations: [
    {
      ruleId: 'no-direct-fs-imports',
      file: 'src/utils/config.ts',
      severity: 'error',
      message: 'Forbidden import: "fs"'
    }
  ]
}
```

## Script System

Extend CodeMap with custom scripts in 5 categories:

### Script Categories

1. **audit** - Custom validation rules (called by audit system)
2. **build** - Build automation with lifecycle hooks
3. **orient** - Contribute custom sections to session orientation
4. **close** - Cleanup and validation on session close
5. **utility** - Ad-hoc helper scripts (ephemeral, purged on close)

### Create Scripts

```typescript
// Create an audit script
await codemap.scripts.create('audit', 'api-versioning', `
export default {
  name: 'api-versioning',
  async execute({ files, ruleId, severity }) {
    const violations = [];
    
    for (const file of files) {
      if (file.path.includes('/api/') && !file.path.includes('/v1/')) {
        violations.push({
          file: file.path,
          message: 'API endpoints must be versioned (e.g., /api/v1/)'
        });
      }
    }
    
    return { passed: violations.length === 0, violations };
  }
};
`);

// Create a build script
await codemap.scripts.create('build', 'lint-check', `
export default {
  name: 'lint-check',
  async execute({ host, iobus }) {
    // Run linter before build
    const result = await host.shell.exec('npm run lint');
    return { success: result.exitCode === 0 };
  }
};
`);

// Create an orient script
await codemap.scripts.create('orient', 'show-metrics', `
export default {
  name: 'show-metrics',
  async execute({ host, sessionId }) {
    const stats = host.graph.getStats();
    return {
      markdown: \`## Code Metrics\\n

…

## Source & license

This open-source MCP server is cataloged on AgentStack and links to its original source — we do not rehost the code.

- **Author:** [egentica](https://github.com/egentica)
- **Source:** [egentica/codemap](https://github.com/egentica/codemap)
- **License:** Apache-2.0
- **Homepage:** https://egentica.ai

Install and usage instructions live in the source repository linked above.

## Pricing

- **Free** — Free

## Security capabilities

Automated source analysis of v0.1.0 — what this tool can access:

- **Network access:** no
- **Filesystem access:** yes
- **Shell / process execution:** no
- **Environment & secrets:** no
- **Dynamic code execution:** yes

*"Yes" means the capability is present in the source — more access means more to trust, not that it is unsafe.*


## Versions

- **0.1.0** — security scan: flagged — Imported from the upstream source.

## Links

- Listing page: https://agentstack.voostack.com/l/mcp-egentica-codemap
- Seller: https://agentstack.voostack.com/s/egentica
- Browse the marketplace: https://agentstack.voostack.com/browse

---
Listed on AgentStack — the marketplace for AI agent skills and MCP servers. Every listing is security-reviewed. Creators keep 70%.
