Skip to main content
Glama
README.md
# Claude Session MCP

An MCP (Model Context Protocol) server that provides Claude Code with **programmatic session awareness** - the ability to query context usage, read todos, track session history, sync planning docs, and make intelligent reset recommendations.

## Why This Exists

Claude Code agents, slash commands, and hooks need to make smart decisions about session management:

- **Before spawning a sub-agent:** Check if there's enough context budget remaining
- **Before expensive operations:** Verify we're not at 90% context and about to trigger compaction
- **When resuming work:** Know what todos are already in progress to avoid duplication
- **During long sessions:** Programmatically update `.context/dev/{branch}/` planning docs
- **End of task:** Get intelligent recommendations on whether to reset context

This MCP server makes all of that possible by exposing session state through 5 core tools.

---

## Features

### 5 Session Awareness Tools

| Tool | Purpose | Use Cases |
|------|---------|-----------|
| **`check_context_budget`** | Query context window usage and remaining capacity | Gate operations when context is critical, warn before spawning agents |
| **`get_session_state`** | Unified snapshot of todos, git state, context files, session info | Check existing todos before creating new ones, verify branch state |
| **`get_session_history`** | What's been accomplished (files modified, todos completed, commits) | Auto-generate session summaries, resume after context reset |
| **`sync_planning_doc`** | Programmatically update `.context/dev/{branch}/` planning docs | Log decisions as you work, mark tasks complete in real-time |
| **`should_reset_context`** | Intelligent recommendations for when to reset context | End-of-task automation, proactive warnings |

---

## Installation

### Prerequisites

- Python 3.11+ (tested on 3.13)
- [uv](https://github.com/astral-sh/uv) package manager
- Claude Code CLI

### Install Steps

```bash
# Clone the repository
git clone https://github.com/yourusername/ccsession
cd ccsession

# Install with uv
uv venv
uv pip install -e ".[dev]"
```

---

## Configuration

### Option 1: Global Configuration

Add to `~/.claude/mcp.json`:

```json
{
  "mcpServers": {
    "ccsession": {
      "command": "uv",
      "args": ["run", "python", "-m", "ccsession"],
      "cwd": "/home/your-username/path/to/ccsession"
    }
  }
}
```

### Option 2: Project-Level Configuration

Add to `<your-project>/.claude/mcp.json`:

```json
{
  "mcpServers": {
    "ccsession": {
      "command": "uv",
      "args": ["run", "python", "-m", "ccsession"],
      "cwd": "/home/your-username/path/to/ccsession"
    }
  }
}
```

### Verify Installation

After restarting Claude Code, the tools will be available to agents and slash commands. You can verify by asking:

> "Can you check the context budget using the MCP tools?"

---

## Tool Reference

### 1. `check_context_budget`

Query current context window usage and remaining capacity.

**Parameters:**
- `context_limit` (optional): Maximum context tokens. Default: 156,000 (200K × 0.78 threshold)

**Returns:**
```json
{
  "tokens_used": 45230,
  "tokens_remaining": 110770,
  "percentage_used": 29.0,
  "context_limit": 156000,
  "status": "sufficient"
}
```

**Status Values:**
- `sufficient`: < 60% used
- `low`: 60-80% used
- `critical`: > 80% used

**Example Usage in Slash Command:**

```markdown
<!-- .claude/commands/check-budget.md -->
Use the `check_context_budget` MCP tool to see how much context we have left.

If status is "critical", warn me and recommend resetting context.
```

---

### 2. `get_session_state`

Get a unified snapshot of current session state.

**Parameters:**
- `working_directory` (optional): Working directory for git operations. Defaults to current directory.

**Returns:**
```json
{
  "todos": {
    "pending": [
      {
        "content": "Deploy to production",
        "status": "pending",
        "activeForm": "Deploying to production"
      }
    ],
    "in_progress": [
      {
        "content": "Update documentation",
        "status": "in_progress",
        "activeForm": "Updating documentation"
      }
    ],
    "completed": [
      {
        "content": "Implement auth middleware",
        "status": "completed",
        "activeForm": "Implementing auth middleware"
      }
    ]
  },
  "git": {
    "branch": "feat/auth",
    "has_uncommitted_changes": true,
    "uncommitted_file_count": 3,
    "is_git_repo": true
  },
  "context_files": {
    "branch_dir": ".context/dev/feat/auth",
    "plan_path": ".context/dev/feat/auth/feat-auth-detailed-plan.md",
    "exists": true
  },
  "session": {
    "start_time": "2025-12-03T14:00:00+00:00",
    "duration_minutes": 45,
    "session_id": "73cc9f9a-1234-5678-9abc-def012345678"
  }
}
```

**Example Usage in Agent:**

```python
# Before creating new todos, check what's already in progress
state = await get_session_state()

if any(t["content"] == "Implement authentication" for t in state["todos"]["in_progress"]):
    print("Authentication implementation already in progress, skipping duplicate todo")
```

---

### 3. `get_session_history`

Get what has been accomplished this session.

**Parameters:**
- `working_directory` (optional): Working directory for git operations. Defaults to current directory.

**Returns:**
```json
{
  "completed_todos": [
    "Implement auth middleware",
    "Add tests",
    "Update documentation"
  ],
  "files_modified": {
    "created": ["src/auth/middleware.ts"],
    "edited": ["src/server.ts", "README.md"],
    "deleted": []
  },
  "tool_calls": {
    "bash_commands": ["npm test", "git commit -m 'feat: add auth'"],
    "agents_spawned": ["Explore", "Plan"],
    "files_read": 23,
    "files_written": 5
  },
  "git_commits": [
    {
      "sha": "a3f5d2c",
      "message": "feat(auth): add middleware"
    }
  ]
}
```

**Example Usage in `/reset-context` Command:**

```markdown
<!-- .claude/commands/reset-context.md -->
1. Use `get_session_history` to see what was accomplished
2. Generate a concise summary from completed_todos and git_commits
3. Save summary to `.context/session-summaries/{date}-{session-id}.md`
4. Reset context with summary as reload context
```

---

### 4. `sync_planning_doc`

Programmatically update `.context/dev/{branch}/` planning documents.

**Parameters:**
- `mode` (required): One of:
  - `append_progress_log`: Add timestamped entry to Progress Log
  - `update_active_work`: Replace Active Work section
  - `mark_tasks_complete`: Mark tasks as `[x]` in Implementation Plan

- `completed_tasks` (array): Tasks completed (for `append_progress_log` or `mark_tasks_complete`)
- `in_progress` (string): Current work description (for `update_active_work`)
- `decisions` (array): Key decisions made (for `append_progress_log`)
- `blockers` (array): Current blockers (for `update_active_work` or `append_progress_log`)
- `next_steps` (array): Next immediate steps (for `update_active_work`)
- `working_directory` (optional): Working directory. Defaults to current directory.

**Returns:**
```json
{
  "success": true,
  "plan_path": ".context/dev/feat-auth/feat-auth-detailed-plan.md",
  "sections_updated": ["Progress Log"]
}
```

**Example 1: Append Progress Log**

```json
{
  "mode": "append_progress_log",
  "completed_tasks": ["Phase 1.1: Database schema", "Phase 1.2: API endpoints"],
  "decisions": ["Using bcrypt for password hashing", "JWT tokens expire after 24h"],
  "blockers": []
}
```

**Example 2: Update Active Work**

```json
{
  "mode": "update_active_work",
  "in_progress": "Implementing user registration endpoint",
  "next_steps": [
    "Add input validation",
    "Write unit tests",
    "Test with Postman"
  ],
  "blockers": ["Waiting for design review on error messages"]
}
```

**Example 3: Mark Tasks Complete**

```json
{
  "mode": "mark_tasks_complete",
  "completed_tasks": [
    "Implement authentication",
    "Write tests"
  ]
}
```

This will change:
```markdown
- [ ] Implement authentication
- [ ] Write tests
```

To:
```markdown
- [x] Implement authentication
- [x] Write tests
```

---

### 5. `should_reset_context`

Get intelligent recommendation on whether to reset context.

**Parameters:**
- `working_directory` (optional): Working directory. Defaults to current directory.

**Returns:**
```json
{
  "should_reset": true,
  "confidence": "high",
  "reasoning": [
    "Context 82% full (critical threshold)",
    "All in_progress todos completed",
    "Clean git state (no uncommitted changes)",
    "Session duration: 2h 15m"
  ],
  "safe_to_reset": true,
  "blockers": [],
  "suggested_summary": "Completed: auth middleware, tests, documentation"
}
```

**Decision Logic:**

| Condition | Recommendation |
|-----------|----------------|
| Context >80% + clean git + todos done | `should_reset: true`, `confidence: high` |
| Context 60-80% + todos done + clean git | `should_reset: true`, `confidence: high` |
| Context 60-80% + clean git | `should_reset: true`, `confidence: medium` |
| Context >60% + uncommitted changes | `should_reset: false`, `safe_to_reset: false` |
| Session >60min + todos done + clean git | `should_reset: true`, `confidence: medium` |

**Example Usage in Hook:**

```json
// .claude/hooks/before-agent-spawn.json
{
  "command": "bash -c 'claude-code mcp call should_reset_context | jq -r .should_reset'",
  "on_success": "proceed",
  "on_failure": "warn"
}
```

---

## Use Cases

### Use Case 1: Smart Agent Spawning

**Problem:** Agent spawns a sub-agent, but context is at 85%, causing immediate compaction and lost context.

**Solution:**

```markdown
<!-- In your agent prompt -->
Before spawning any sub-agents, ALWAYS:

1. Call `check_context_budget`
2. If status is "critical" or "low", call `should_reset_context`
3. If reset recommended, warn user and ask permission before proceeding
```

### Use Case 2: Avoid Duplicate Todos

**Problem:** After context reset, agent creates duplicate todos for work already in progress.

**Solution:**

```markdown
<!-- In your slash command -->
Before creating todos:

1. Call `get_session_state`
2. Check if any `todos.in_progress` or `todos.pending` match your planned work
3. Only create new todos for work not already tracked
```

### Use Case 3: Real-Time Planning Doc Updates

**Problem:** Planning docs in `.context/dev/{branch}/` only get updated at end of session, losing valuable decision history.

**Solution:**

```markdown
<!-- In your agent prompt -->
After completing each major task:

1. Call `sync_planning_doc` with mode="append_progress_log"
2. Include completed_tasks and any key decisions made
3. This keeps planning docs as living documents
```

### Use Case 4: Automated Session Summaries

**Problem:** Manually writing session summaries before context reset is tedious and error-prone.

**Solution:**

```markdown
<!-- .claude/commands/auto-reset.md -->
1. Call `get_session_history` to get completed_todos and git_commits
2. Generate 2-3 sentence summary
3. Call `should_reset_context` to verify safe to reset
4. If safe, save summary and reset context with /reset command
```

---

## Architecture

### How It Works

1. **Transcript Discovery**: Scans `/tmp/claude-code-transcripts/` for the most recent `.jsonl` file
2. **Token Counting**: Parses transcript to sum `input_tokens + output_tokens + cache_creation_input_tokens + cache_read_input_tokens`
3. **Todo Parsing**: Reads `~/.claude/todos/{session_id}*.json` files (handles agent spawns)
4. **Git Operations**: Subprocess calls to `git` CLI for branch, status, commits
5. **Planning Doc Updates**: Markdown section parsing with regex, preserves formatting

### File Locations

```
~/.claude/
├── todos/{session_id}.json              # Main session todos
├── todos/{session_id}-agent-*.json      # Agent spawn todos
└── mcp.json                              # MCP server config

/tmp/claude-code-transcripts/
└── {session_id}.jsonl                    # Session transcript

<project>/.context/dev/{branch}/
└── {branch}-detailed-plan.md             # Planning document
```

### Context Limit Calculation

Claude Code triggers `/compact` at ~78% of the 200K context window:

```python
DEFAULT_CONTEXT_LIMIT = int(200_000 * 0.78)  # 156,000 tokens
```

Thresholds:
- **Sufficient**: < 60% of limit (< 93,600 tokens)
- **Low**: 60-80% of limit (93,600 - 124,800 tokens)
- **Critical**: > 80% of limit (> 124,800 tokens)

---

## Development

### Running Tests

```bash
# Run all tests
uv run pytest

# Run with verbose output
uv run pytest -v

# Run specific test file
uv run pytest tests/test_transcript.py

# Run with coverage
uv run pytest --cov=ccsession
```

### Test Coverage

- **47 passing tests** covering:
  - Transcript parsing (token counting, session start time, edge cases)
  - Git utilities (state detection, commits, planning doc paths)
  - Todo parsing (session todos, agent spawns, latest todos)
  - All 5 MCP tools (integration tests with mocked dependencies)

### Project Structure

```
ccsession/
├── src/ccsession/
│   ├── __init__.py
│   ├── __main__.py              # Entry point
│   ├── server.py                # MCP server + all 5 tools
│   └── parsers/
│       ├── transcript.py        # JSONL parsing, token counting
│       ├── git.py               # Git operations
│       └── todos.py             # Todo file parsing
├── tests/
│   ├── conftest.py              # Shared fixtures
│   ├── test_transcript.py       # Transcript parser tests
│   ├── test_git.py              # Git utilities tests
│   ├── test_todos.py            # Todo parser tests
│   ├── test_mcp_tools.py        # Integration tests
│   └── fixtures/                # Test data
├── pyproject.toml               # Package config
└── README.md
```

### Adding New Features

1. **New parser:** Add to `src/ccsession/parsers/`
2. **New tool:** Add handler in `server.py` under `handle_tool_call()`
3. **Add tests:** Create `tests/test_*.py` with fixtures
4. **Update docs:** Document in this README

---

## Troubleshooting

### MCP server not found

**Error:** `MCP server 'claude-session' not found`

**Solution:**
1. Check `~/.claude/mcp.json` or `<project>/.claude/mcp.json` exists
2. Verify `cwd` path points to correct directory
3. Restart Claude Code to reload MCP config

### No transcript found

**Error:** Tools return empty/zero values

**Solution:**
1. Verify `/tmp/claude-code-transcripts/` directory exists
2. Check that `.jsonl` files are being created during sessions
3. MCP uses most recent file by modification time

### Planning doc not found

**Error:** `sync_planning_doc` returns "Plan file not found"

**Solution:**
1. Verify `.context/dev/{branch}/{branch}-detailed-plan.md` exists
2. Check you're on the correct git branch
3. Planning doc path follows pattern: branch name with dashes, not slashes

### Tests failing

**Error:** Import errors or test failures

**Solution:**
```bash
# Reinstall in development mode
uv pip install -e ".[dev]"

# Clear pytest cache
rm -rf .pytest_cache

# Run with full traceback
uv run pytest -v --tb=long
```

---

## Acknowledgments

- **Transcript parsing logic** ported from [ccusage](https://github.com/ryoppippi/ccusage) by [@ryoppippi](https://github.com/ryoppippi)
- Built with the [MCP Python SDK](https://github.com/modelcontextprotocol/python-sdk)
- Designed for [Claude Code](https://www.anthropic.com/claude/code)

---

## License

MIT License - see LICENSE file for details

---

## Contributing

Contributions welcome! Please:

1. Fork the repository
2. Create a feature branch (`git checkout -b feat/amazing-feature`)
3. Add tests for new functionality
4. Ensure all tests pass (`uv run pytest`)
5. Submit a pull request

---

## Future Enhancements

Potential Wave 2+ features (see `PLAN.md` for full list):

- **Session comparison:** Diff two sessions to see what changed
- **Cost tracking:** Token usage → USD cost estimates
- **Time tracking:** How long was spent on each task
- **Planning doc templates:** Auto-generate planning docs from templates
- **Multi-session search:** Find when/where specific work was done
- **Session replay:** Reconstruct what happened in a previous session

See something missing? [Open an issue](https://github.com/yourusername/ccsession/issues)!

TDQS

A3.5/5.0

Scored across 5 tools

Disambiguation5/5

Each tool has a clearly distinct purpose with no overlap: checking context budget, retrieving session history, getting session state, recommending context resets, and syncing planning documents. The descriptions clearly differentiate their functions, making misselection unlikely.

Naming Consistency4/5

Most tools follow a consistent verb_noun pattern (check_context_budget, get_session_history, get_session_state, sync_planning_doc), but 'should_reset_context' deviates slightly by using 'should' instead of a direct action verb. Overall, the naming is readable and predictable with only minor inconsistency.

Tool Count5/5

With 5 tools, this server is well-scoped for session management and context tracking. Each tool serves a specific, necessary function in this domain, and the count is neither too thin nor excessive for the apparent purpose.

Completeness4/5

The tool set covers core session management needs: monitoring context usage, tracking history and state, providing reset recommendations, and updating planning documents. A minor gap exists in direct context reset or modification tools, but agents can work around this using existing tools like 'should_reset_context' for guidance.

Maintenance

ActivityInactive
ResponsivenessNo issues