context-forge-cli 0.2.3__tar.gz → 0.3.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. {context_forge_cli-0.2.3 → context_forge_cli-0.3.0}/PKG-INFO +107 -1
  2. {context_forge_cli-0.2.3 → context_forge_cli-0.3.0}/README.md +105 -0
  3. {context_forge_cli-0.2.3 → context_forge_cli-0.3.0}/contextforge/adapters/altimate_code.py +47 -23
  4. {context_forge_cli-0.2.3 → context_forge_cli-0.3.0}/contextforge/adapters/claude_code.py +65 -17
  5. {context_forge_cli-0.2.3 → context_forge_cli-0.3.0}/contextforge/adapters/codex.py +83 -19
  6. {context_forge_cli-0.2.3 → context_forge_cli-0.3.0}/contextforge/cli.py +25 -0
  7. {context_forge_cli-0.2.3 → context_forge_cli-0.3.0}/contextforge/core/token_analyzer.py +23 -1
  8. context_forge_cli-0.3.0/contextforge/mcp_server.py +219 -0
  9. {context_forge_cli-0.2.3 → context_forge_cli-0.3.0}/contextforge/models/session.py +2 -0
  10. context_forge_cli-0.3.0/contextforge/tui/widgets/tokens_panel.py +290 -0
  11. context_forge_cli-0.3.0/contextforge/utils/tokens.py +25 -0
  12. {context_forge_cli-0.2.3 → context_forge_cli-0.3.0}/pyproject.toml +3 -1
  13. context_forge_cli-0.3.0/tests/conftest.py +32 -0
  14. context_forge_cli-0.3.0/tests/test_mcp_server.py +285 -0
  15. {context_forge_cli-0.2.3 → context_forge_cli-0.3.0}/uv.lock +357 -2
  16. context_forge_cli-0.2.3/contextforge/tui/widgets/tokens_panel.py +0 -134
  17. context_forge_cli-0.2.3/contextforge/utils/tokens.py +0 -17
  18. {context_forge_cli-0.2.3 → context_forge_cli-0.3.0}/.contextforge.toml +0 -0
  19. {context_forge_cli-0.2.3 → context_forge_cli-0.3.0}/.github/workflows/publish.yml +0 -0
  20. {context_forge_cli-0.2.3 → context_forge_cli-0.3.0}/.gitignore +0 -0
  21. {context_forge_cli-0.2.3 → context_forge_cli-0.3.0}/.python-version +0 -0
  22. {context_forge_cli-0.2.3 → context_forge_cli-0.3.0}/AGENTS.md +0 -0
  23. {context_forge_cli-0.2.3 → context_forge_cli-0.3.0}/PLAN.md +0 -0
  24. {context_forge_cli-0.2.3 → context_forge_cli-0.3.0}/contextforge/__init__.py +0 -0
  25. {context_forge_cli-0.2.3 → context_forge_cli-0.3.0}/contextforge/adapters/__init__.py +0 -0
  26. {context_forge_cli-0.2.3 → context_forge_cli-0.3.0}/contextforge/adapters/base.py +0 -0
  27. {context_forge_cli-0.2.3 → context_forge_cli-0.3.0}/contextforge/adapters/claude_desktop.py +0 -0
  28. {context_forge_cli-0.2.3 → context_forge_cli-0.3.0}/contextforge/adapters/gemini.py +0 -0
  29. {context_forge_cli-0.2.3 → context_forge_cli-0.3.0}/contextforge/adapters/registry.py +0 -0
  30. {context_forge_cli-0.2.3 → context_forge_cli-0.3.0}/contextforge/core/__init__.py +0 -0
  31. {context_forge_cli-0.2.3 → context_forge_cli-0.3.0}/contextforge/core/analytics.py +0 -0
  32. {context_forge_cli-0.2.3 → context_forge_cli-0.3.0}/contextforge/core/compactor.py +0 -0
  33. {context_forge_cli-0.2.3 → context_forge_cli-0.3.0}/contextforge/core/db.py +0 -0
  34. {context_forge_cli-0.2.3 → context_forge_cli-0.3.0}/contextforge/core/injector.py +0 -0
  35. {context_forge_cli-0.2.3 → context_forge_cli-0.3.0}/contextforge/core/scanner.py +0 -0
  36. {context_forge_cli-0.2.3 → context_forge_cli-0.3.0}/contextforge/core/summarizer.py +0 -0
  37. {context_forge_cli-0.2.3 → context_forge_cli-0.3.0}/contextforge/models/__init__.py +0 -0
  38. {context_forge_cli-0.2.3 → context_forge_cli-0.3.0}/contextforge/models/config.py +0 -0
  39. {context_forge_cli-0.2.3 → context_forge_cli-0.3.0}/contextforge/tui/__init__.py +0 -0
  40. {context_forge_cli-0.2.3 → context_forge_cli-0.3.0}/contextforge/tui/app.py +0 -0
  41. {context_forge_cli-0.2.3 → context_forge_cli-0.3.0}/contextforge/tui/styles.tcss +0 -0
  42. {context_forge_cli-0.2.3 → context_forge_cli-0.3.0}/contextforge/tui/widgets/__init__.py +0 -0
  43. {context_forge_cli-0.2.3 → context_forge_cli-0.3.0}/contextforge/tui/widgets/session_detail.py +0 -0
  44. {context_forge_cli-0.2.3 → context_forge_cli-0.3.0}/contextforge/tui/widgets/session_table.py +0 -0
  45. {context_forge_cli-0.2.3 → context_forge_cli-0.3.0}/contextforge/tui/widgets/stats_panel.py +0 -0
  46. {context_forge_cli-0.2.3 → context_forge_cli-0.3.0}/contextforge/tui/widgets/status_bar.py +0 -0
  47. {context_forge_cli-0.2.3 → context_forge_cli-0.3.0}/contextforge/tui/widgets/transfer_panel.py +0 -0
  48. {context_forge_cli-0.2.3 → context_forge_cli-0.3.0}/contextforge/utils/__init__.py +0 -0
  49. {context_forge_cli-0.2.3 → context_forge_cli-0.3.0}/contextforge/utils/display.py +0 -0
  50. {context_forge_cli-0.2.3 → context_forge_cli-0.3.0}/tests/__init__.py +0 -0
  51. {context_forge_cli-0.2.3 → context_forge_cli-0.3.0}/tests/adapters/__init__.py +0 -0
  52. {context_forge_cli-0.2.3 → context_forge_cli-0.3.0}/tests/adapters/test_claude_code.py +0 -0
  53. {context_forge_cli-0.2.3 → context_forge_cli-0.3.0}/tests/core/__init__.py +0 -0
  54. {context_forge_cli-0.2.3 → context_forge_cli-0.3.0}/tests/core/test_compactor.py +0 -0
  55. {context_forge_cli-0.2.3 → context_forge_cli-0.3.0}/tests/core/test_db.py +0 -0
  56. {context_forge_cli-0.2.3 → context_forge_cli-0.3.0}/tests/core/test_injector.py +0 -0
  57. {context_forge_cli-0.2.3 → context_forge_cli-0.3.0}/tests/core/test_summarizer.py +0 -0
  58. {context_forge_cli-0.2.3 → context_forge_cli-0.3.0}/tests/core/test_token_analyzer.py +0 -0
  59. {context_forge_cli-0.2.3 → context_forge_cli-0.3.0}/tests/fixtures/claude_session_sample.jsonl +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: context-forge-cli
3
- Version: 0.2.3
3
+ Version: 0.3.0
4
4
  Summary: Session manager and context bridge for agentic CLI tools
5
5
  Project-URL: Homepage, https://github.com/emmver/contextforge
6
6
  Project-URL: Repository, https://github.com/emmver/contextforge
@@ -18,6 +18,7 @@ Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
18
18
  Classifier: Topic :: Utilities
19
19
  Requires-Python: >=3.13
20
20
  Requires-Dist: anthropic>=0.89.0
21
+ Requires-Dist: mcp>=1.9.0
21
22
  Requires-Dist: pydantic>=2.12.5
22
23
  Requires-Dist: rich>=14.3.3
23
24
  Requires-Dist: sqlite-utils>=3.39
@@ -304,6 +305,111 @@ Press `t` on any session to open the transfer panel. Choose:
304
305
  - **Preview** — shows the exact shell command (no side effects)
305
306
  - **Execute** — builds the bundle and launches the target tool
306
307
 
308
+ ## MCP Server
309
+
310
+ ContextForge ships a [Model Context Protocol](https://modelcontextprotocol.io) server that exposes session data and token analytics to LLM agents.
311
+
312
+ ### Setup
313
+
314
+ ```bash
315
+ # Run directly (after installation)
316
+ cf-mcp
317
+
318
+ # From source
319
+ uv run python -m contextforge.mcp_server
320
+ ```
321
+
322
+ Register the server with your agentic tool of choice:
323
+
324
+ #### Claude Code
325
+
326
+ Add to `~/.claude/claude_desktop_config.json` (global) or `.claude/mcp.json` (project):
327
+ ```json
328
+ {
329
+ "mcpServers": {
330
+ "contextforge": {
331
+ "command": "cf-mcp"
332
+ }
333
+ }
334
+ }
335
+ ```
336
+
337
+ #### Cursor
338
+
339
+ Add to `~/.cursor/mcp.json` (global) or `.cursor/mcp.json` (project):
340
+ ```json
341
+ {
342
+ "mcpServers": {
343
+ "contextforge": {
344
+ "command": "cf-mcp"
345
+ }
346
+ }
347
+ }
348
+ ```
349
+
350
+ Restart Cursor fully after saving.
351
+
352
+ #### Codex CLI
353
+
354
+ Add to `~/.codex/config.toml` (global) or `.codex/config.toml` (project):
355
+ ```toml
356
+ [mcp_servers.contextforge]
357
+ command = "cf-mcp"
358
+ enabled = true
359
+ ```
360
+
361
+ #### Gemini CLI
362
+
363
+ Add to `~/.gemini/settings.json` (global) or `.gemini/settings.json` (project):
364
+ ```json
365
+ {
366
+ "mcpServers": {
367
+ "contextforge": {
368
+ "command": "cf-mcp"
369
+ }
370
+ }
371
+ }
372
+ ```
373
+
374
+ #### Antigravity
375
+
376
+ Add to `mcp_servers.json` in your project root:
377
+ ```json
378
+ {
379
+ "servers": [
380
+ {
381
+ "name": "contextforge",
382
+ "transport": "stdio",
383
+ "command": "cf-mcp",
384
+ "enabled": true
385
+ }
386
+ ]
387
+ }
388
+ ```
389
+
390
+ ### Tools
391
+
392
+ | Tool | Description |
393
+ |---|---|
394
+ | `list_sessions` | List indexed sessions; filter by `tool`, limit up to 200 |
395
+ | `get_session` | Full detail for a single session by ID |
396
+ | `get_session_tokens` | Per-turn token breakdown; optionally return only the N heaviest turns |
397
+ | `get_token_analytics` | Aggregated token stats across all sessions for a time window |
398
+ | `get_activity_timeline` | Session count and token usage bucketed over time |
399
+ | `get_top_projects` | Top projects by session count within a time window |
400
+ | `compare_sessions` | Side-by-side token comparison for 2–10 sessions |
401
+
402
+ All tools are **read-only** and accept a `window` parameter of `7d`, `30d`, `6m`, or `1y` where applicable.
403
+
404
+ ### Example usage
405
+
406
+ ```
407
+ # In Claude Code with the MCP server registered:
408
+ "Show me token usage for all my Claude Code sessions this month"
409
+ "Compare sessions <id1> and <id2> side by side"
410
+ "What are my top 5 projects by session count?"
411
+ ```
412
+
307
413
  ## Troubleshooting
308
414
 
309
415
  ### `command not found: cf`
@@ -276,6 +276,111 @@ Press `t` on any session to open the transfer panel. Choose:
276
276
  - **Preview** — shows the exact shell command (no side effects)
277
277
  - **Execute** — builds the bundle and launches the target tool
278
278
 
279
+ ## MCP Server
280
+
281
+ ContextForge ships a [Model Context Protocol](https://modelcontextprotocol.io) server that exposes session data and token analytics to LLM agents.
282
+
283
+ ### Setup
284
+
285
+ ```bash
286
+ # Run directly (after installation)
287
+ cf-mcp
288
+
289
+ # From source
290
+ uv run python -m contextforge.mcp_server
291
+ ```
292
+
293
+ Register the server with your agentic tool of choice:
294
+
295
+ #### Claude Code
296
+
297
+ Add to `~/.claude/claude_desktop_config.json` (global) or `.claude/mcp.json` (project):
298
+ ```json
299
+ {
300
+ "mcpServers": {
301
+ "contextforge": {
302
+ "command": "cf-mcp"
303
+ }
304
+ }
305
+ }
306
+ ```
307
+
308
+ #### Cursor
309
+
310
+ Add to `~/.cursor/mcp.json` (global) or `.cursor/mcp.json` (project):
311
+ ```json
312
+ {
313
+ "mcpServers": {
314
+ "contextforge": {
315
+ "command": "cf-mcp"
316
+ }
317
+ }
318
+ }
319
+ ```
320
+
321
+ Restart Cursor fully after saving.
322
+
323
+ #### Codex CLI
324
+
325
+ Add to `~/.codex/config.toml` (global) or `.codex/config.toml` (project):
326
+ ```toml
327
+ [mcp_servers.contextforge]
328
+ command = "cf-mcp"
329
+ enabled = true
330
+ ```
331
+
332
+ #### Gemini CLI
333
+
334
+ Add to `~/.gemini/settings.json` (global) or `.gemini/settings.json` (project):
335
+ ```json
336
+ {
337
+ "mcpServers": {
338
+ "contextforge": {
339
+ "command": "cf-mcp"
340
+ }
341
+ }
342
+ }
343
+ ```
344
+
345
+ #### Antigravity
346
+
347
+ Add to `mcp_servers.json` in your project root:
348
+ ```json
349
+ {
350
+ "servers": [
351
+ {
352
+ "name": "contextforge",
353
+ "transport": "stdio",
354
+ "command": "cf-mcp",
355
+ "enabled": true
356
+ }
357
+ ]
358
+ }
359
+ ```
360
+
361
+ ### Tools
362
+
363
+ | Tool | Description |
364
+ |---|---|
365
+ | `list_sessions` | List indexed sessions; filter by `tool`, limit up to 200 |
366
+ | `get_session` | Full detail for a single session by ID |
367
+ | `get_session_tokens` | Per-turn token breakdown; optionally return only the N heaviest turns |
368
+ | `get_token_analytics` | Aggregated token stats across all sessions for a time window |
369
+ | `get_activity_timeline` | Session count and token usage bucketed over time |
370
+ | `get_top_projects` | Top projects by session count within a time window |
371
+ | `compare_sessions` | Side-by-side token comparison for 2–10 sessions |
372
+
373
+ All tools are **read-only** and accept a `window` parameter of `7d`, `30d`, `6m`, or `1y` where applicable.
374
+
375
+ ### Example usage
376
+
377
+ ```
378
+ # In Claude Code with the MCP server registered:
379
+ "Show me token usage for all my Claude Code sessions this month"
380
+ "Compare sessions <id1> and <id2> side by side"
381
+ "What are my top 5 projects by session count?"
382
+ ```
383
+
279
384
  ## Troubleshooting
280
385
 
281
386
  ### `command not found: cf`
@@ -25,6 +25,16 @@ def _count_tokens(text: str) -> int:
25
25
  return len(text) // 4
26
26
 
27
27
 
28
+ def _compute_message_tokens(msg) -> int:
29
+ """Count tokens across all content: text + tool_call inputs + tool_result outputs."""
30
+ total = _count_tokens(msg.content)
31
+ for tc in msg.tool_calls:
32
+ total += _count_tokens(tc.get("input", ""))
33
+ for tr in msg.tool_results:
34
+ total += _count_tokens(tr.get("output", ""))
35
+ return total
36
+
37
+
28
38
  class AltimateCodeAdapter(ToolAdapter):
29
39
  tool_name = "altimate_code"
30
40
  default_paths = [_OPENCODE_DB]
@@ -86,8 +96,6 @@ class AltimateCodeAdapter(ToolAdapter):
86
96
  conn = sqlite3.connect(str(_OPENCODE_DB))
87
97
  conn.row_factory = sqlite3.Row
88
98
  cur = conn.cursor()
89
- # Join message + part to get full content
90
- # Note: altimate-code stores data as JSON in 'data' column
91
99
  cur.execute(
92
100
  """
93
101
  SELECT
@@ -95,7 +103,11 @@ class AltimateCodeAdapter(ToolAdapter):
95
103
  json_extract(m.data, '$.role') as role,
96
104
  m.time_created as ts,
97
105
  json_extract(p.data, '$.type') as part_type,
98
- json_extract(p.data, '$.text') as content
106
+ json_extract(p.data, '$.text') as text_content,
107
+ json_extract(p.data, '$.tool') as tool_name,
108
+ json_extract(p.data, '$.callID') as call_id,
109
+ json_extract(p.data, '$.state.input') as tool_input,
110
+ json_extract(p.data, '$.state.output') as tool_output
99
111
  FROM message m
100
112
  LEFT JOIN part p ON p.message_id = m.id
101
113
  WHERE m.session_id = ?
@@ -112,24 +124,29 @@ class AltimateCodeAdapter(ToolAdapter):
112
124
  current_msg_id: str | None = None
113
125
  current_role: str | None = None
114
126
  current_parts: list[str] = []
127
+ current_tool_calls: list[dict] = []
128
+ current_tool_results: list[dict] = []
115
129
  current_ts: datetime | None = None
116
130
 
117
131
  def flush():
118
132
  nonlocal current_msg_id, current_role, current_parts, current_ts
119
- if current_role and current_parts:
133
+ nonlocal current_tool_calls, current_tool_results
134
+ if current_role and (current_parts or current_tool_calls):
120
135
  content = "\n".join(p for p in current_parts if p)
121
- if content:
122
- messages.append(
123
- Message(
124
- role=current_role,
125
- content=content,
126
- timestamp=current_ts,
127
- token_count=_count_tokens(content),
128
- )
129
- )
136
+ msg = Message(
137
+ role=current_role,
138
+ content=content,
139
+ timestamp=current_ts,
140
+ tool_calls=list(current_tool_calls),
141
+ tool_results=list(current_tool_results),
142
+ )
143
+ msg.token_count = _compute_message_tokens(msg)
144
+ messages.append(msg)
130
145
  current_msg_id = None
131
146
  current_role = None
132
147
  current_parts = []
148
+ current_tool_calls = []
149
+ current_tool_results = []
133
150
  current_ts = None
134
151
 
135
152
  for row in rows:
@@ -138,7 +155,6 @@ class AltimateCodeAdapter(ToolAdapter):
138
155
  if role not in ("user", "assistant"):
139
156
  continue
140
157
 
141
- # Flush when message ID changes (new message in the message table)
142
158
  if msg_id != current_msg_id:
143
159
  flush()
144
160
  current_msg_id = msg_id
@@ -149,28 +165,36 @@ class AltimateCodeAdapter(ToolAdapter):
149
165
  current_ts = None
150
166
 
151
167
  part_type = row["part_type"] or ""
152
- content = row["content"] or ""
153
168
 
154
- if part_type in ("text", "reasoning") and content:
155
- if isinstance(content, str):
169
+ if part_type in ("text", "reasoning"):
170
+ content = row["text_content"] or ""
171
+ if isinstance(content, str) and content:
156
172
  try:
157
173
  parsed = json.loads(content)
158
174
  if isinstance(parsed, dict):
159
175
  content = parsed.get("text", str(parsed))
160
176
  except (json.JSONDecodeError, TypeError):
161
177
  pass
162
- current_parts.append(str(content).strip())
178
+ content = str(content).strip()
179
+ if content:
180
+ current_parts.append(content)
181
+
182
+ elif part_type == "tool":
183
+ tool_name = row["tool_name"] or "?"
184
+ tool_input = row["tool_input"] or ""
185
+ tool_output = row["tool_output"] or ""
186
+ # input from json_extract is already a JSON string; keep as-is for token counting
187
+ current_tool_calls.append({"name": tool_name, "input": tool_input})
188
+ if tool_output:
189
+ current_tool_results.append({"output": tool_output})
163
190
 
164
191
  flush()
165
192
  return messages
166
193
 
167
194
  def _count_session_tokens(self, session_id: str) -> int:
168
- """Count total tokens in a session."""
195
+ """Count total tokens in a session (text + tool inputs + tool outputs)."""
169
196
  messages = self.load_messages(session_id)
170
- total = 0
171
- for msg in messages:
172
- total += msg.token_count or _count_tokens(msg.content)
173
- return total
197
+ return sum(msg.token_count or _compute_message_tokens(msg) for msg in messages)
174
198
 
175
199
  def build_inject_command(
176
200
  self,
@@ -64,6 +64,16 @@ def _count_tokens(text: str) -> int:
64
64
  return len(text) // 4
65
65
 
66
66
 
67
+ def _compute_message_tokens(msg: Message) -> int:
68
+ """Count tokens across all content in a message: text + tool_call inputs + tool_result outputs."""
69
+ total = _count_tokens(msg.content)
70
+ for tc in msg.tool_calls:
71
+ total += _count_tokens(tc.get("input", ""))
72
+ for tr in msg.tool_results:
73
+ total += _count_tokens(tr.get("output", ""))
74
+ return total
75
+
76
+
67
77
  class ClaudeCodeAdapter(ToolAdapter):
68
78
  tool_name = "claude_code"
69
79
  default_paths = [_HISTORY_PATH, _PROJECTS_DIR]
@@ -309,17 +319,6 @@ class ClaudeCodeAdapter(ToolAdapter):
309
319
  role = msg_data.get("role", entry_type)
310
320
  content_raw = msg_data.get("content", "")
311
321
 
312
- # Skip entries where content is an array of tool results/tool use
313
- # (these are Claude's internal messages, not user input or assistant responses)
314
- if isinstance(content_raw, list):
315
- # Only include arrays that contain text blocks (actual assistant content)
316
- if not any(block.get("type") == "text" for block in content_raw if isinstance(block, dict)):
317
- continue
318
-
319
- content = _parse_content(content_raw)
320
- if not content:
321
- continue
322
-
323
322
  ts_str = entry.get("timestamp")
324
323
  ts = None
325
324
  if ts_str:
@@ -328,14 +327,63 @@ class ClaudeCodeAdapter(ToolAdapter):
328
327
  except (ValueError, AttributeError):
329
328
  pass
330
329
 
331
- messages.append(
332
- Message(
333
- role="user" if role == "user" else "assistant",
334
- content=content,
335
- timestamp=ts,
336
- token_count=_count_tokens(content),
330
+ if isinstance(content_raw, list):
331
+ has_text = any(
332
+ isinstance(b, dict) and b.get("type") == "text"
333
+ for b in content_raw
337
334
  )
335
+ has_tool_result = any(
336
+ isinstance(b, dict) and b.get("type") == "tool_result"
337
+ for b in content_raw
338
+ )
339
+
340
+ # tool_result-only user entries: attribute their outputs to the
341
+ # last assistant turn (the one that issued the tool calls)
342
+ if has_tool_result and not has_text:
343
+ if messages and messages[-1].role == "assistant":
344
+ last = messages[-1]
345
+ for block in content_raw:
346
+ if not isinstance(block, dict) or block.get("type") != "tool_result":
347
+ continue
348
+ inner = block.get("content", "")
349
+ if isinstance(inner, list):
350
+ for item in inner:
351
+ if isinstance(item, dict) and item.get("type") == "text":
352
+ output = item.get("text", "")
353
+ if output:
354
+ last.tool_results.append({"output": output})
355
+ elif isinstance(inner, str) and inner:
356
+ last.tool_results.append({"output": inner})
357
+ # Recompute token_count now that tool_results have been added
358
+ last.token_count = _compute_message_tokens(last)
359
+ continue
360
+
361
+ # Extract tool_call entries from assistant content arrays
362
+ tool_calls: list[dict] = []
363
+ if role != "user":
364
+ for block in content_raw:
365
+ if not isinstance(block, dict) or block.get("type") != "tool_use":
366
+ continue
367
+ try:
368
+ input_str = json.dumps(block.get("input", {}))
369
+ except (TypeError, ValueError):
370
+ input_str = ""
371
+ tool_calls.append({"name": block.get("name", "?"), "input": input_str})
372
+ else:
373
+ tool_calls = []
374
+
375
+ content = _parse_content(content_raw)
376
+ if not content and not tool_calls:
377
+ continue
378
+
379
+ msg = Message(
380
+ role="user" if role == "user" else "assistant",
381
+ content=content,
382
+ timestamp=ts,
383
+ tool_calls=tool_calls,
338
384
  )
385
+ msg.token_count = _compute_message_tokens(msg)
386
+ messages.append(msg)
339
387
 
340
388
  return messages
341
389
 
@@ -41,6 +41,30 @@ def _count_tokens(text: str) -> int:
41
41
  return len(text) // 4
42
42
 
43
43
 
44
+ def _compute_message_tokens(msg: Message) -> int:
45
+ total = _count_tokens(msg.content)
46
+ for tc in msg.tool_calls:
47
+ total += _count_tokens(tc.get("input", ""))
48
+ for tr in msg.tool_results:
49
+ total += _count_tokens(tr.get("output", ""))
50
+ return total
51
+
52
+
53
+ def _extract_function_output(raw_output: str) -> str:
54
+ """Extract the human-readable output from a Codex function_call_output payload.
55
+
56
+ The `output` field is a JSON string: {"output": "...", "metadata": {...}}.
57
+ Returns the inner "output" string, or the raw string on parse failure.
58
+ """
59
+ try:
60
+ parsed = json.loads(raw_output)
61
+ if isinstance(parsed, dict):
62
+ return str(parsed.get("output", raw_output))
63
+ except (json.JSONDecodeError, TypeError):
64
+ pass
65
+ return raw_output
66
+
67
+
44
68
  class CodexAdapter(ToolAdapter):
45
69
  tool_name = "codex"
46
70
  default_paths = [_CODEX_DB, _CODEX_SESSIONS_DIR]
@@ -87,7 +111,10 @@ class CodexAdapter(ToolAdapter):
87
111
  cwd=row["cwd"] or None,
88
112
  created_at=created,
89
113
  updated_at=updated,
90
- token_count=row["tokens_used"],
114
+ # tokens_used in state_5.sqlite is cumulative API billing spend
115
+ # (re-sends full context each call), NOT conversation footprint.
116
+ # Leave token_count=None so cf refresh computes it from rollout content.
117
+ token_count=None,
91
118
  raw_path=row["rollout_path"] or None,
92
119
  status="unknown",
93
120
  )
@@ -184,6 +211,31 @@ class CodexAdapter(ToolAdapter):
184
211
 
185
212
  def _parse_rollout(self, path: Path) -> list[Message]:
186
213
  messages: list[Message] = []
214
+
215
+ # Pending tool data for the current assistant turn (buffered until
216
+ # we see the agent_message that closes the turn).
217
+ pending_tool_calls: list[dict] = []
218
+ pending_tool_results: list[dict] = []
219
+
220
+ def flush_pending_assistant(text: str = "", ts=None):
221
+ """Emit an assistant message with any buffered tool data."""
222
+ nonlocal pending_tool_calls, pending_tool_results
223
+ if not text and not pending_tool_calls:
224
+ pending_tool_calls = []
225
+ pending_tool_results = []
226
+ return
227
+ msg = Message(
228
+ role="assistant",
229
+ content=text,
230
+ timestamp=ts,
231
+ tool_calls=list(pending_tool_calls),
232
+ tool_results=list(pending_tool_results),
233
+ )
234
+ msg.token_count = _compute_message_tokens(msg)
235
+ messages.append(msg)
236
+ pending_tool_calls = []
237
+ pending_tool_results = []
238
+
187
239
  with path.open() as f:
188
240
  for line in f:
189
241
  line = line.strip()
@@ -196,30 +248,42 @@ class CodexAdapter(ToolAdapter):
196
248
 
197
249
  entry_type = entry.get("type", "")
198
250
  payload = entry.get("payload", {})
251
+ ts_str = entry.get("timestamp")
252
+ ts = None
253
+ if ts_str:
254
+ try:
255
+ ts = datetime.fromisoformat(ts_str.replace("Z", "+00:00"))
256
+ except (ValueError, AttributeError):
257
+ pass
199
258
 
200
259
  if entry_type == "event_msg":
201
260
  msg_type = payload.get("type", "")
202
- # user_message / agent_message are the clean human-facing turns.
203
- # response_item entries are skipped — they contain system context
204
- # injections (AGENTS.md, environment_context) and duplicate content.
205
261
  if msg_type == "user_message":
206
- text = payload.get("message", "")
262
+ # New user turn — flush any orphaned tool data first
263
+ flush_pending_assistant()
264
+ text = str(payload.get("message", ""))
207
265
  if text:
208
- text_str = str(text)
209
- messages.append(Message(
210
- role="user",
211
- content=text_str,
212
- token_count=_count_tokens(text_str),
213
- ))
266
+ msg = Message(role="user", content=text, timestamp=ts)
267
+ msg.token_count = _count_tokens(text)
268
+ messages.append(msg)
214
269
  elif msg_type == "agent_message":
215
- text = payload.get("message", "")
216
- if text:
217
- text_str = str(text)
218
- messages.append(Message(
219
- role="assistant",
220
- content=text_str,
221
- token_count=_count_tokens(text_str),
222
- ))
270
+ text = str(payload.get("message", ""))
271
+ flush_pending_assistant(text=text, ts=ts)
272
+
273
+ elif entry_type == "response_item":
274
+ item_type = payload.get("type", "")
275
+ if item_type == "function_call":
276
+ name = payload.get("name", "?")
277
+ arguments = payload.get("arguments", "")
278
+ pending_tool_calls.append({"name": name, "input": arguments})
279
+ elif item_type == "function_call_output":
280
+ raw_output = payload.get("output", "")
281
+ output = _extract_function_output(raw_output)
282
+ if output:
283
+ pending_tool_results.append({"output": output})
284
+
285
+ # Flush any trailing tool data (e.g. incomplete / aborted turn)
286
+ flush_pending_assistant()
223
287
 
224
288
  return messages
225
289
 
@@ -578,6 +578,31 @@ def refresh(
578
578
  )
579
579
 
580
580
 
581
+ # ---------------------------------------------------------------------------
582
+ # cf mcp
583
+ # ---------------------------------------------------------------------------
584
+
585
+ @app.command(name="mcp")
586
+ def mcp_server():
587
+ """Start the ContextForge MCP server (stdio transport).
588
+
589
+ Exposes session data and token analysis as MCP tools so LLM agents
590
+ can query token usage, list sessions, and pull analytics directly.
591
+
592
+ Add to your Claude Code MCP config:
593
+ {
594
+ "mcpServers": {
595
+ "contextforge": {
596
+ "command": "cf",
597
+ "args": ["mcp"]
598
+ }
599
+ }
600
+ }
601
+ """
602
+ from contextforge.mcp_server import main as _run_mcp
603
+ _run_mcp()
604
+
605
+
581
606
  # ---------------------------------------------------------------------------
582
607
  # cf dashboard
583
608
  # ---------------------------------------------------------------------------