会话管理协议服务

提供程序化会话感知能力的MCP服务器,用于查询上下文使用情况、读取待办事项、跟踪会话历史、同步规划文档并提供智能重置建议。

  • by TimEvans
  • Python
  • 本地部署
  • 更新于
在 GitHub 查看 TimEvans/ccsession

使用说明

克劳德会话MCP

一个MCP(模型上下文协议)服务器,为Claude Code提供 程序化会议意识 -查询上下文使用情况、读取待办事项、跟踪会话历史、同步计划文档以及提出智能重置建议的能力。

为什么存在

Claude Code代理、斜线命令和钩子需要对会话管理做出明智的决定:

  • 在生成子代理之前: 检查是否有足够的上下文预算剩余
  • 在昂贵的操作之前: 确认我们没有处于90%的上下文状态,即将触发压缩
  • 恢复工作时: 了解正在进行的待办事项,以避免重复
  • 在长时间会议期间: 程序化更新 .context/dev/{branch}/ 规划文件
  • 任务结束: 获取有关是否重置上下文的智能建议

此MCP服务器通过5个核心工具公开会话状态,使所有这些成为可能。


特性

5个会话意识工具

工具 目的 用例
check_context_budget 查询上下文窗口使用情况和剩余容量 在上下文关键时关闭操作,在生成代理之前发出警告
get_session_state 待办事项、git状态、上下文文件、会话信息的统一快照 在创建新待办事项之前检查现有待办事项,验证分支状态
get_session_history 已完成的工作(文件已修改、待办事项已完成、提交) 自动生成会话摘要,在上下文重置后恢复
sync_planning_doc 程序化更新 .context/dev/{branch}/ 计划文档 在工作时记录决策,实时标记任务完成情况
should_reset_context 何时重置上下文的智能建议 任务结束自动化,主动警告

安装

先决条件

  • Python 3.11+(在3.13上测试)
  • 紫外线 包管理器
  • 克劳德代码CLI

安装步骤

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

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

配置

选项1:全局配置

添加到 ~/.claude/mcp.json:

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

选项2:项目级配置

添加到 <your-project>/.claude/mcp.json:

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

验证安装

重启Claude Code后,这些工具将可用于代理和斜线命令。您可以通过以下方式进行验证:

“你能使用MCP工具检查上下文预算吗?”


工具参考

1. check_context_budget

查询当前上下文窗口的使用情况和剩余容量。

参数:

  • context_limit (可选):最大上下文标记。默认值:156000(200K×0.78阈值)

退货:

{
  "tokens_used": 45230,
  "tokens_remaining": 110770,
  "percentage_used": 29.0,
  "context_limit": 156000,
  "status": "sufficient"
}

状态值:

  • sufficient:使用率<60%
  • low:已使用60-80%
  • critical:使用率>80%

Slash命令中的示例用法:

<!-- .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

获取当前会话状态的统一快照。

参数:

  • working_directory (可选):git操作的工作目录。默认为当前目录。

退货:

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

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

了解本次会议取得的成果。

参数:

  • working_directory (可选):git操作的工作目录。默认为当前目录。

退货:

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

示例用法 /reset-context 命令:

<!-- .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

程序化更新 .context/dev/{branch}/ 规划文件。

参数:

  • mode (必填):以下之一:

    • append_progress_log:在进度日志中添加带时间戳的条目
    • update_active_work:替换活动工作部分
    • mark_tasks_complete:将任务标记为 [x] 在实施计划中
  • completed_tasks (array):已完成的任务(用于 append_progress_log 或 mark_tasks_complete)

  • in_progress (string):当前工作描述(适用于 update_active_work)

  • decisions (数组):做出的关键决策( append_progress_log)

  • blockers (阵列):电流阻断器(用于 update_active_work 或 append_progress_log)

  • next_steps (array):接下来的直接步骤(for update_active_work)

  • working_directory (可选):工作目录。默认为当前目录。

退货:

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

示例1:附加进度日志

{
  "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": []
}

示例2:更新当前工作

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

示例3:标记任务已完成

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

这将改变:

- [ ] Implement authentication
- [ ] Write tests

致:

- [x] Implement authentication
- [x] Write tests

5. should_reset_context

获取是否重置上下文的智能建议。

参数:

  • working_directory (可选):工作目录。默认为当前目录。

退货:

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

决策逻辑:

条件 建议
上下文>80%+清理git+完成待办事项 should_reset: true, confidence: high
上下文60-80%+待办事项完成+清理git should_reset: true, confidence: high
上下文60-80%+干净的git should_reset: true, confidence: medium
上下文>60%+未提交的更改 should_reset: false, safe_to_reset: false
会话>60分钟+完成待办事项+清理git should_reset: true, confidence: medium

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

用例

用例1:智能代理生成

问题: 代理生成了一个子代理,但上下文为85%,导致立即压缩和上下文丢失。

解决方案:

<!-- 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

用例2:避免重复的待办事项

问题: 上下文重置后,代理为已在进行的工作创建重复的待办事项。

解决方案:

<!-- 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

用例3:实时计划文档更新

问题: 规划文档 .context/dev/{branch}/ 只在会话结束时更新,丢失宝贵的决策历史记录。

解决方案:

<!-- 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

用例4:自动会话摘要

问题: 在上下文重置之前手动编写会话摘要既繁琐又容易出错。

解决方案:

<!-- .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

建筑

运作原理

  1. 成绩单发现:扫描 /tmp/claude-code-transcripts/ 对于最近的 .jsonl 文件
  2. 令牌计数:将成绩单解析为求和 input_tokens + output_tokens + cache_creation_input_tokens + cache_read_input_tokens
  3. Todo解析:阅读 ~/.claude/todos/{session_id}*.json 文件(处理代理生成)
  4. Git操作:子流程调用 git CLI用于分支、状态、提交
  5. 计划文档更新:使用正则表达式解析Markdown部分,保留格式

文件位置

~/.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

上下文限制计算

克劳德代码触发器 /compact 在200K上下文窗口的约78%处:

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

阈值:

  • 足够的:<60%的限额(<93600个代币)
  • 低:限额的60-80%(93600-124800个代币)
  • 关键的:>80%的限额(>124800个代币)

发展

运行测试

# 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

测试覆盖率

  • 47项测试通过 涵盖:
    • 转录解析(令牌计数、会话开始时间、边缘情况)
    • Git实用程序(状态检测、提交、规划文档路径)
    • Todo解析(会话Todo、代理生成、最新Todo)
    • 所有5个MCP工具(具有模拟依赖关系的集成测试)

项目结构

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

添加新功能

  1. 新解析器: 添加到 src/ccsession/parsers/
  2. 新工具: 在中添加处理程序 server.py 在...之下 handle_tool_call()
  3. 添加测试: 创建 tests/test_*.py 带固定装置
  4. 更新文档: 本自述文件

故障排除

未找到MCP服务器

错误: MCP server 'claude-session' not found

解决方案:

  1. 检查 ~/.claude/mcp.json 或 <project>/.claude/mcp.json 存在
  2. 验证 cwd 路径指向正确的目录
  3. 重新启动Claude Code以重新加载MCP配置

未找到成绩单

错误: 工具返回空/零值

解决方案:

  1. 验证 /tmp/claude-code-transcripts/ 目录存在
  2. 检查 .jsonl 正在会话期间创建文件
  3. MCP按修改时间使用最新文件

未找到计划文档

错误: sync_planning_doc return“未找到计划文件”

解决方案:

  1. 验证 .context/dev/{branch}/{branch}-detailed-plan.md 存在
  2. 检查你是否在正确的git分支上
  3. 计划文档路径遵循以下模式:分支名称带破折号,而不是斜线

测试失败

错误: 导入错误或测试失败

解决方案:

# 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

致谢


许可证

MIT许可证-有关详细信息,请参阅许可证文件


贡献

欢迎投稿!拜托:

  1. 复刻仓库
  2. 创建要素分支(git checkout -b feat/amazing-feature)
  3. 添加新功能的测试
  4. 确保所有测试通过(uv run pytest)
  5. 提交拉取请求

未来的增强功能

潜在波2+特征(见 PLAN.md 完整列表):

  • 会话比较: 区分两场会议,看看有什么变化
  • 成本跟踪: 令牌使用情况→ 美元成本估算
  • 时间跟踪: 每项任务花了多长时间
  • 计划文档模板: 从模板自动生成计划文档
  • 多会话搜索: 查找具体工作完成的时间/地点
  • 会话重播: 重建上一节课中发生的事情

看到缺少什么了吗? 打开一个问题!