Skip to content

noobwander/MCP

Repository files navigation

Codebase Context MCP Server

A Model Context Protocol (MCP) server that provides deep codebase analysis through AST (Abstract Syntax Tree) parsing and dependency graph generation for Python, JavaScript, PHP, and HTML projects.

Overview

This MCP server enables Claude Code and Codex CLI to understand your codebase structure by:

  • Extracting functions, classes, and imports from source files
  • Building dependency graphs showing import relationships
  • Analyzing module architecture and detecting circular dependencies
  • Searching for symbols across the entire codebase

✨ Features a custom lightweight graph implementation using only Python built-ins - no NetworkX or external graph libraries required!

Quick Start

The server is already configured and ready to use! When you start a Claude Code or Codex CLI session, the MCP tools will be automatically available.

Testing the Setup

Start Claude Code or Codex in any of your projects and you should see:

# Codebase Context Loaded

You now have access to MCP tools for deep codebase analysis...

Then ask your assistant to analyze your project:

User: "Give me a summary of this project"
Assistant: [Automatically uses `get_project_summary`]

Note: Throughout this document, any mention of "Claude" refers to whichever MCP-enabled client you're running (Claude Code or Codex CLI).

Codex CLI Support

Codex CLI now loads the exact same MCP tooling:

  • ~/.codex/settings.json mirrors the Claude hooks so SessionStart/PostToolUse run /home/tchang/MCP/rules/*.sh for Codex sessions.
  • ~/.codex/mcp.json registers the codebase-context server with the same command/args, using the Codex project directory environment variable when available.
  • ~/.config/mcp/servers.json provides a global registry entry so other MCP-aware tools can reuse the server without extra setup.
  • rules/session_start_hook.sh was updated to detect whether Claude or Codex launched the session and prints the correct client label.

To use it: restart the Codex CLI, open any project, and run list_mcp_resources (or just start coding). You should immediately see the codebase-context server in the tool list and receive the same automatic project summary workflow that Claude Code uses.

Directory Structure

/home/tchang/MCP/
├── codebase-context-server/
│   ├── server.py              # Main MCP server
│   ├── ast_tools.py           # AST parsing for Python/JS/PHP/HTML
│   ├── graph_tools.py         # Dependency graph generation
│   ├── requirements.txt       # Python dependencies
│   └── venv/                  # Python 3.13 virtual environment
├── rules/
│   ├── codebase_instructions.md     # Instructions for Claude/Codex
│   └── session_start_hook.sh        # SessionStart hook script
└── git-hooks/                 # Git hook templates (for future use)

Available MCP Tools

1. get_project_summary

Get high-level statistics about the codebase.

Usage:

Claude will call this automatically at session start

Returns:

  • Total files, functions, classes, lines
  • Language breakdown (Python, JS, PHP, HTML)

2. analyze_file_ast

Extract detailed AST information from a single file.

Parameters:

  • file_path: Path to file (relative to project root)
  • deep: Boolean, include full AST structure (default: false)

Returns:

  • Functions with signatures and locations
  • Classes with inheritance info
  • Import statements
  • File statistics

3. analyze_directory

Analyze all supported files in a directory.

Parameters:

  • directory: Path to directory
  • extensions: Optional filter (e.g., [".py", ".js"])
  • deep: Include full AST structure

Returns:

  • Complete AST data for all files
  • Summary statistics by language

4. get_dependency_graph

Build dependency graph showing import relationships.

Parameters:

  • directory: Project root (defaults to current)
  • output_format: "summary" (default) or "json"

Returns:

  • Total files and dependencies
  • Circular dependencies (if any)
  • Most imported files

5. get_module_structure

High-level view of module organization.

Returns:

  • Entry points (files not imported by others)
  • Leaf modules (files that don't import others)
  • Directory breakdown
  • Circular dependencies

6. get_file_dependencies

Show dependencies for a specific file.

Parameters:

  • file_path: File to analyze
  • directory: Project root

Returns:

  • What the file imports
  • What imports the file

7. search_symbols

Find functions or classes by name across the codebase.

Parameters:

  • pattern: Search string (substring match)
  • symbol_type: "function", "class", or "both"

Returns:

  • Matching symbols with file locations and line numbers

Language Support

Language Extensions Functions Classes Imports Full AST Graphs
Python .py
JavaScript/TypeScript .js, .jsx, .ts, .tsx
PHP .php
HTML .html, .htm

Note: Dependency graph generation uses a custom lightweight implementation with zero external dependencies!

How It Works

1. Startup

When you start a Claude Code or Codex session:

  1. SessionStart hook runs (~/.claude/settings.json)
  2. Hook displays available tools
  3. Claude automatically calls get_project_summary
  4. You get an overview of your codebase

2. During Development

Claude intelligently uses tools based on context:

  • Before editing: Analyzes file AST and dependencies
  • Architecture questions: Generates dependency graphs
  • Code search: Uses symbol search
  • Impact analysis: Checks file dependencies

3. Configuration

MCP Server Config (~/.claude/mcp.json):

{
  "mcpServers": {
    "codebase-context": {
      "command": "/usr/local/bin/python3.13",
      "args": ["/home/tchang/MCP/codebase-context-server/server.py"],
      "env": {
        "PROJECT_DIR": "${CLAUDE_PROJECT_DIR}"
      }
    }
  }
}

SessionStart Hook (~/.claude/settings.json):

{
  "hooks": {
    "SessionStart": [
      {
        "matcher": "startup",
        "hooks": [
          {
            "type": "command",
            "command": "/home/tchang/MCP/rules/session_start_hook.sh"
          }
        ]
      }
    ]
  }
}

Codex MCP Config (~/.codex/mcp.json):

{
  "mcpServers": {
    "codebase-context": {
      "command": "/home/tchang/MCP/codebase-context-server/venv/bin/python",
      "args": [
        "/home/tchang/MCP/codebase-context-server/server.py"
      ],
      "env": {
        "PROJECT_DIR": "${CODEX_PROJECT_DIR}",
        "PYTHONPATH": "/home/tchang/MCP/codebase-context-server"
      }
    }
  }
}

Codex Hooks + MCP Config (~/.codex/settings.json):

{
  "hooks": {
    "SessionStart": [
      {
        "matcher": "startup",
        "hooks": [
          {
            "type": "command",
            "command": "/home/tchang/MCP/rules/session_start_hook.sh"
          }
        ]
      }
    ],
    "PostToolUse": [
      {
        "matcher": "Write|Edit",
        "hooks": [
          {
            "type": "command",
            "command": "/home/tchang/MCP/rules/post_edit_hook.sh"
          }
        ]
      }
    ]
  },
  "mcpServers": {
    "codebase-context": {
      "command": "/home/tchang/MCP/codebase-context-server/venv/bin/python",
      "args": [
        "/home/tchang/MCP/codebase-context-server/server.py"
      ],
      "env": {
        "PROJECT_DIR": "${CODEX_PROJECT_DIR}",
        "PYTHONPATH": "/home/tchang/MCP/codebase-context-server"
      },
      "enabled": true
    }
  }
}

Testing

Test 1: Project Summary

cd /home/tchang/python/projects/your-project
claude
# Claude should automatically show project summary

Test 2: File Analysis

Ask Claude:

"Analyze the structure of main.py"

Claude will use analyze_file_ast to show functions, classes, and imports.

Test 3: Dependency Graph

Ask Claude:

"Show me the dependency structure of this project"

Claude will use get_module_structure and get_dependency_graph.

Test 4: Symbol Search

Ask Claude:

"Where is the login function defined?"

Claude will use search_symbols to find it.

Troubleshooting

MCP Server Not Loading

Check MCP configuration (Claude):

cat ~/.claude/mcp.json

Check MCP configuration (Codex):

cat ~/.codex/mcp.json

Test server manually:

cd /home/tchang/MCP/codebase-context-server
source venv/bin/activate
python server.py
# Should wait for input (MCP server running)
# Press Ctrl+C to exit

SessionStart Hook Not Running

Check settings (Claude):

cat ~/.claude/settings.json

Check settings (Codex):

cat ~/.codex/settings.json

Test hook manually:

/home/tchang/MCP/rules/session_start_hook.sh
# Should display instructions

Python Dependencies Issue

Reinstall dependencies:

cd /home/tchang/MCP/codebase-context-server
source venv/bin/activate
pip install -r requirements.txt

MCP Tools Not Appearing

Check Claude Code logs:

tail -f ~/.claude/debug/*.log

Restart Claude Code:

# Exit current session and start fresh

Performance Tips

Large Codebases

For projects with 100k+ lines:

  • Tools are optimized with caching
  • Use targeted queries instead of full analysis
  • deep=false (default) for faster analysis

Excluded Directories

The following directories are automatically skipped:

  • .git, __pycache__, node_modules
  • venv, .venv, vendor
  • dist, build

Phase 2 & 3 Roadmap

Phase 2: Codebase Discovery

Goal: Use Phase 1 tools to analyze your actual projects

Process:

  1. Claude analyzes your codebases using current tools
  2. Discovers patterns:
    • How routes/endpoints are defined
    • Where database queries are located
    • Configuration file formats
    • Documentation structure

Deliverable: Design document for specialized tools

Phase 3: Specialized Tools

Goal: Build tools tailored to your codebase

Planned Tools:

  1. API Route Discovery

    • Auto-detect framework (Flask, Slim, Express, etc.)
    • Extract all endpoints with methods and handlers
  2. Database Schema Extraction

    • Connect to MySQL database
    • Parse migration files
    • Extract from ORM models
  3. Configuration Parser

    • Parse .env files
    • Extract from config.php, settings.py
    • Redact sensitive data
  4. Documentation Indexer

    • Index docstrings and comments
    • Parse README and docs/
    • Searchable documentation context

Your Projects

The server works across all your projects:

  • /home/tchang/python/projects/ (16,524 files, ~365k lines)
  • /home/tchang/python/Working/ (651 files, ~464k lines)
  • /var/www/html/samplelogin/ (1,116 files, ~1.4M lines)

Advanced Usage

Custom File Extensions

Edit ast_tools.py to add more languages:

EXT_TO_LANG = {
    '.py': 'python',
    '.js': 'javascript',
    # Add your custom extensions here
}

Export Dependency Graphs

Graphs are automatically exported to .context/ in each project:

  • dependency-graph.json - Machine-readable format
  • dependency-graph.dot - Graphviz format for visualization

Visualize Graphs

# Install Graphviz
sudo apt-get install graphviz

# Generate PNG from DOT file
dot -Tpng .context/dependency-graph.dot -o dependency-graph.png

Contributing to Phase 2

When you start using these tools, keep notes on:

  • What patterns you discover in your code
  • What additional context would be helpful
  • Specific pain points or repetitive queries

This will inform the design of Phase 3 specialized tools.

Support

For issues or questions:

  1. Check the troubleshooting section above
  2. Review /home/tchang/MCP/rules/codebase_instructions.md
  3. Test components manually (server, hooks, tools)

File Locations

  • MCP Server: /home/tchang/MCP/codebase-context-server/
  • Instructions: /home/tchang/MCP/rules/codebase_instructions.md
  • MCP Config: ~/.claude/mcp.json
  • Settings: ~/.claude/settings.json
  • Logs: ~/.claude/debug/

Version

Phase 1 - Complete

  • AST analysis for Python, JS, PHP, HTML
  • Dependency graph generation
  • Module structure analysis
  • Symbol search
  • Automatic session initialization

Phase 2 - Planned

  • Codebase pattern discovery
  • Framework detection

Phase 3 - Planned

  • API route discovery
  • Database schema extraction
  • Configuration parsing
  • Documentation indexing

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors