Claude Session MCP

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.

Category
访问服务器

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% used
  • low: 60-80% used
  • critical: > 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 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:

{
  "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

  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:

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

  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:

# 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


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!

推荐服务器

Baidu Map

Baidu Map

百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。

官方
精选
JavaScript
Playwright MCP Server

Playwright MCP Server

一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。

官方
精选
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。

官方
精选
本地
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。

官方
精选
本地
TypeScript
VeyraX

VeyraX

一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。

官方
精选
本地
graphlit-mcp-server

graphlit-mcp-server

模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。

官方
精选
TypeScript
Kagi MCP Server

Kagi MCP Server

一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。

官方
精选
Python
e2b-mcp-server

e2b-mcp-server

使用 MCP 通过 e2b 运行代码。

官方
精选
Neon MCP Server

Neon MCP Server

用于与 Neon 管理 API 和数据库交互的 MCP 服务器

官方
精选
Exa MCP Server

Exa MCP Server

模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。

官方
精选