Claude Session MCP
Provides Claude Code with programmatic session awareness to track context usage, session history, and task progress. It enables intelligent context reset recommendations and automatic synchronization of project planning documentation.
README
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 package manager
- Claude Code CLI
Install Steps
# 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:
{
"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:
{
"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:
{
"tokens_used": 45230,
"tokens_remaining": 110770,
"percentage_used": 29.0,
"context_limit": 156000,
"status": "sufficient"
}
Status Values:
sufficient: < 60% usedlow: 60-80% usedcritical: > 80% used
Example Usage in Slash Command:
<!-- .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:
{
"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:
# 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:
{
"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:
<!-- .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 Logupdate_active_work: Replace Active Work sectionmark_tasks_complete: Mark tasks as[x]in Implementation Plan
-
completed_tasks(array): Tasks completed (forappend_progress_logormark_tasks_complete) -
in_progress(string): Current work description (forupdate_active_work) -
decisions(array): Key decisions made (forappend_progress_log) -
blockers(array): Current blockers (forupdate_active_workorappend_progress_log) -
next_steps(array): Next immediate steps (forupdate_active_work) -
working_directory(optional): Working directory. Defaults to current directory.
Returns:
{
"success": true,
"plan_path": ".context/dev/feat-auth/feat-auth-detailed-plan.md",
"sections_updated": ["Progress Log"]
}
Example 1: Append Progress Log
{
"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
{
"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
{
"mode": "mark_tasks_complete",
"completed_tasks": [
"Implement authentication",
"Write tests"
]
}
This will change:
- [ ] Implement authentication
- [ ] Write tests
To:
- [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:
{
"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:
// .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:
<!-- 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:
<!-- 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:
<!-- 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:
<!-- .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
- Transcript Discovery: Scans
/tmp/claude-code-transcripts/for the most recent.jsonlfile - Token Counting: Parses transcript to sum
input_tokens + output_tokens + cache_creation_input_tokens + cache_read_input_tokens - Todo Parsing: Reads
~/.claude/todos/{session_id}*.jsonfiles (handles agent spawns) - Git Operations: Subprocess calls to
gitCLI for branch, status, commits - 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:
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
# 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
- New parser: Add to
src/ccsession/parsers/ - New tool: Add handler in
server.pyunderhandle_tool_call() - Add tests: Create
tests/test_*.pywith fixtures - Update docs: Document in this README
Troubleshooting
MCP server not found
Error: MCP server 'claude-session' not found
Solution:
- Check
~/.claude/mcp.jsonor<project>/.claude/mcp.jsonexists - Verify
cwdpath points to correct directory - Restart Claude Code to reload MCP config
No transcript found
Error: Tools return empty/zero values
Solution:
- Verify
/tmp/claude-code-transcripts/directory exists - Check that
.jsonlfiles are being created during sessions - MCP uses most recent file by modification time
Planning doc not found
Error: sync_planning_doc returns "Plan file not found"
Solution:
- Verify
.context/dev/{branch}/{branch}-detailed-plan.mdexists - Check you're on the correct git branch
- Planning doc path follows pattern: branch name with dashes, not slashes
Tests failing
Error: Import errors or test failures
Solution:
# 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 by @ryoppippi
- Built with the MCP Python SDK
- Designed for Claude Code
License
MIT License - see LICENSE file for details
Contributing
Contributions welcome! Please:
- Fork the repository
- Create a feature branch (
git checkout -b feat/amazing-feature) - Add tests for new functionality
- Ensure all tests pass (
uv run pytest) - 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!
Recommended Servers
playwright-mcp
A Model Context Protocol server that enables LLMs to interact with web pages through structured accessibility snapshots without requiring vision models or screenshots.
Magic Component Platform (MCP)
An AI-powered tool that generates modern UI components from natural language descriptions, integrating with popular IDEs to streamline UI development workflow.
Audiense Insights MCP Server
Enables interaction with Audiense Insights accounts via the Model Context Protocol, facilitating the extraction and analysis of marketing insights and audience data including demographics, behavior, and influencer engagement.
VeyraX MCP
Single MCP tool to connect all your favorite tools: Gmail, Calendar and 40 more.
graphlit-mcp-server
The Model Context Protocol (MCP) Server enables integration between MCP clients and the Graphlit service. Ingest anything from Slack to Gmail to podcast feeds, in addition to web crawling, into a Graphlit project - and then retrieve relevant contents from the MCP client.
Kagi MCP Server
An MCP server that integrates Kagi search capabilities with Claude AI, enabling Claude to perform real-time web searches when answering questions that require up-to-date information.
E2B
Using MCP to run code via e2b.
Neon Database
MCP server for interacting with Neon Management API and databases
Exa Search
A Model Context Protocol (MCP) server lets AI assistants like Claude use the Exa AI Search API for web searches. This setup allows AI models to get real-time web information in a safe and controlled way.
Qdrant Server
This repository is an example of how to create a MCP server for Qdrant, a vector search engine.