Ctx Claude Context¶
Ctx Claude Context — mvp.ctx_claude_context
Cluster: Context & Retrieval | Type: component | MCP Tools: 26
Overview¶
Sliding context window manager for Claude conversations, tracking token counts via tiktoken (chars/4 heuristic fallback) and providing compress and trim operations to keep the conversation within a token budget. Compression replaces the oldest messages with an extractive summary; trim performs a single O(n) slice to drop oldest messages until the total fits.
When to use:
- Managing long Claude conversation histories without exceeding the context window
- Automatically summarising older turns before appending new messages
- Maintaining a system prompt alongside a rolling message window
Launch-readiness caveat
ctx_claude_context is a practical v1 context-window utility, not a semantic memory system or full long-term context intelligence layer. Its default compression is heuristic/extractive, token counts may be approximate when Anthropic token counting is unavailable, and one block instance is not thread-safe across concurrent sessions. For production agent workflows, use it to bound and inspect context before LLM calls, but do not rely on it as the only preservation mechanism for critical facts, audit evidence, or regulated-domain decisions.
Capability discovery (info) discloses the current weakest links in machine-readable form: backend sqlite, semantic preservation unvalidated, search mode substring_tf, and thread safety not_enforced. Concurrent callers must provide distinct session IDs; the component reports this limitation but does not enforce isolation.
Untrusted-content / authority caveat
Conversation content (user, assistant, and tool messages) is untrusted external input. Every compaction and persistence seam (compress, compress_structured, summarize_category, and session rehydrate on load_session) injection-scans the message text and stamps evidence.content_provenance (untrusted_compacted_context / untrusted_persisted_session) plus an authority_note. Because compaction collapses untrusted content into a role="system" summary, a prompt-injection signal attaches a G6_E_CONTEXT_COMPACTION_INJECTION warning card and marks the output degraded (content preserved, not dropped). Residual: the summary is still emitted with role="system" — the authority elevation is annotated, not structurally removed (declared via the untrusted_content_promoted_to_authority contract failure mode). Downstream consumers must not treat compacted or rehydrated content as trusted system instructions.
Example:
from mvp.ctx_claude_context import CtxClaudeContextBlock, ClaudeContextInput
block = CtxClaudeContextBlock(name="ctx_cc")
block.infer(ClaudeContextInput(operation="add", role="user", content="Hello, world!"))
result = block.infer(ClaudeContextInput(operation="trim", max_tokens=2000))
# result.value.total_tokens → token count after trim
Works well with: ctx_ace, ctx_recursive, llm_router
Public API¶
CtxClaudeContextDecisionError(ValueError)¶
The LLM did not produce a usable, validated retention decision.
ContextRetentionDecision¶
Validated advisory retention verdict over an existing message set.
| Field | Type | Default |
|---|---|---|
retained_indices | tuple[int, ...] | required |
dropped_indices | tuple[int, ...] | () |
rationale | str | '' |
messages_fingerprint | str | '' |
confidence | float | 0.0 |
degraded | bool | False |
raw_response | str | '' |
LLMContextRetentionRuntime¶
Provider-neutral retention runtime backed by G6's LLM caller interface.
Constructor:
| Parameter | Type | Default |
|---|---|---|
llm | LLMCaller \| None | None |
Methods:
select(messages: list[tuple[str, str]], token_counts: list[int], budget: int) -> ContextRetentionDecision¶
CtxClaudeContextRetentionPatternRuntime¶
Stateless, load-bearing budget-ceiling enforcement.
Methods:
enforce_budget(decision: ContextRetentionDecision, messages: list[tuple[str, str]], token_counts: list[int], budget: int, recency_retained: list[int]) -> tuple[list[int], list[tuple[str, str]], bool, bool]¶
CtxClaudeContextPlanner¶
Runtime-first advisory retention facade with deterministic fallback.
Constructor:
| Parameter | Type | Default |
|---|---|---|
runtime | ContextRetentionRuntime \| None | None |
pattern_runtime | CtxClaudeContextRetentionPatternRuntime \| None | None |
Methods:
select(messages: list[tuple[str, str]], token_counts: list[int], budget: int) -> list[int]¶
Return the retained message indices (chronological) under the budget.
CtxClaudeContextBlock(AIBlock[ClaudeContextInput, ClaudeContextOutput, dict])¶
Sliding context window manager for Claude conversations.
| Field | Type | Default |
|---|---|---|
name | str | 'ctx_claude_context' |
resource_bounds | ResourceBounds \| None | None |
usage | ResourceUsage | field(default_factory=ResourceUsage) |
agentic_planner | CtxClaudeContextPlanner \| None | None |
Methods:
infer(data: ClaudeContextInput) -> Result[ClaudeContextOutput]¶
ContextMessage(BaseModel)¶
| Field | Type | Default |
|---|---|---|
role | str | required |
content | str | required |
token_count | int | 0 |
ClaudeContextInput(BaseModel)¶
| Field | Type | Default |
|---|---|---|
operation | Literal['add', 'compress', 'get', 'clear', 'trim'] | required |
role | str | 'user' |
content | str | '' |
max_tokens | int | 4096 |
system_prompt | str | '' |
compress_ratio | float | 0.5 |
request_id | str | '' |
task_id | str | '' |
run_id | str | '' |
agentic_retention | bool \| None | None |
run_mode | Literal['beta', 'production'] | 'beta' |
reviewer_signature | str | '' |
Methods:
max_tokens_positive(v: int) -> int¶
compress_ratio_valid(v: float) -> float¶
ClaudeContextOutput(BaseModel)¶
| Field | Type | Default |
|---|---|---|
messages | list[ContextMessage] | required |
total_tokens | int | required |
compressed_count | int | 0 |
operation | str | required |
message | str | '' |
token_backend | str | '' |
degraded | bool | False |
degradation_reason | str | '' |
completion_state | str | 'complete' |
warning_card | dict | Field(default_factory=dict) |
evidence | dict | Field(default_factory=dict) |
request_id | str | '' |
task_id | str | '' |
run_id | str | '' |
agentic_evidence | dict | Field(default_factory=dict) |
CtxClaudeContextMCPBlock(AIBlock[MCPContextInput, MCPContextOutput, dict])¶
25-op MCP block for context engineering with SQLite persistence.
| Field | Type | Default |
|---|---|---|
name | str | 'ctx_claude_context_mcp' |
state | dict \| None | None |
db_path | str | ':memory:' |
resource_bounds | ResourceBounds \| None | None |
usage | ResourceUsage | field(default_factory=ResourceUsage) |
Methods:
infer(data: MCPContextInput) -> Result[MCPContextOutput]¶
MCPContextInput(BaseModel)¶
| Field | Type | Default |
|---|---|---|
op | MCPContextOp | required |
role | str | 'user' |
content | str | '' |
system_prompt | str | '' |
max_tokens | int | 4096 |
compress_ratio | float | 0.5 |
target_tokens | int | 8192 |
strategy | str | 'auto' |
agentic_retention | bool \| None | None |
run_mode | Literal['beta', 'production'] | 'beta' |
reviewer_signature | str | '' |
name | str | '' |
tags | list[str] | Field(default_factory=list) |
notes | str | '' |
total_limit | int | 0 |
reserved_buffer | int | 0 |
category_limits_json | str | '' |
limit | int | 50 |
category | str | '' |
max_length | int | 200 |
query | str | '' |
top_k | int | 5 |
request_id | str | '' |
task_id | str | '' |
run_id | str | '' |
Methods:
max_tokens_positive(v: int) -> int¶
compress_ratio_valid(v: float) -> float¶
MCPContextRecord(BaseModel)¶
| Field | Type | Default |
|---|---|---|
id | int | 0 |
table | str | '' |
name | str | '' |
summary | str | '' |
data | dict | Field(default_factory=dict) |
timestamp | str | '' |
MCPContextOutput(BaseModel)¶
| Field | Type | Default |
|---|---|---|
op | str | '' |
message | str | '' |
found | bool | False |
count | int | 0 |
value | dict | Field(default_factory=dict) |
records | list[MCPContextRecord] | Field(default_factory=list) |
messages_data | list[dict] | Field(default_factory=list) |
total_tokens | int | 0 |
scores | list[float] | Field(default_factory=list) |
summary | str | '' |
metadata | dict | Field(default_factory=dict) |
degraded | bool | False |
degradation_reason | str | '' |
completion_state | str | 'complete' |
warning_card | dict | Field(default_factory=dict) |
evidence | dict | Field(default_factory=dict) |
request_id | str | '' |
task_id | str | '' |
run_id | str | '' |
agentic_evidence | dict | Field(default_factory=dict) |
char_ratio_score | float | 0.0 |
semantic_preservation_validated | bool | False |
semantic_preservation | str | '' |
search_mode | str | '' |
ContextStore¶
SQLite store for context engineering persistence.
Constructor:
| Parameter | Type | Default |
|---|---|---|
db_path | str | ':memory:' |
Methods:
save_session(name: str, messages_json: str, system_prompt: str, total_tokens: int, message_count: int, tags: list[str] | None = None, notes: str = '') -> int¶
load_session(name: str) -> dict | None¶
list_sessions(limit: int = 50, query: str = '') -> list[dict]¶
upsert_budget(name: str, total_limit: int, reserved_buffer: int = 0, category_limits_json: str = '{}') -> int¶
get_budget(name: str) -> dict | None¶
add_degradation_event(health_score: float, status: str, utilization: float, degradation_score: float, poisoning_risk: float, total_tokens: int, message_count: int, recommendations_json: str = '[]') -> int¶
get_degradation_history(limit: int = 50) -> list[dict]¶
clear_degradation_events() -> int¶
add_compression_record(method: str, messages_before: int, messages_after: int, tokens_before: int, tokens_after: int, quality_score: float = 0.0, probe_results_json: str = '{}') -> int¶
upsert_category(category: str, message_count: int, token_count: int, summary: str = '') -> int¶
get_categories() -> list[dict]¶
clear_categories() -> int¶
add_context_snapshot(session_name: str, messages_json: str, total_tokens: int, operation: str, notes: str = '') -> int¶
add_metric(metric_type: str, metric_value: float, details_json: str = '{}') -> int¶
text_search(query: str, top_k: int = 5) -> list[dict]¶
Substring search across sessions, budgets, categories, contexts.
search(query: str, top_k: int = 5) -> list[dict]¶
set_budget(name: str, total_limit: int, reserved_buffer: int = 0, category_limits_json: str = '{}') -> int¶
categorize() -> list[dict]¶
metrics() -> dict[str, int]¶
capabilities() -> dict¶
health() -> dict¶
translate_error(exc: Exception) -> dict¶
count_all() -> dict[str, int]¶
close() -> None¶
Functions¶
agentic_planner_enabled(default_enabled: bool) -> bool¶
Decide whether the agentic retention planner should be used.
messages_fingerprint(messages: list[tuple[str, str]]) -> str¶
sha256 over the existing (role, content) message set (order-sensitive).
validate_retention_decision(decision: ContextRetentionDecision, n_messages: int, expected_fingerprint: str) -> None¶
Structural / anti-injection guard for a retention decision (FAIL-CLOSED).
recency_floor_indices(token_counts: list[int], budget: int) -> list[int]¶
The deterministic RECENCY floor: the LARGEST FITTING SUFFIX under the budget.
planner_is_llm_trusted(planner: Any) -> bool¶
Whether the BLOCK may report
llm_used=Trueforplanner.
MCP Tools¶
| Operation | Source |
|---|---|
add | claude_context_mcp |
get | claude_context_mcp |
compress | claude_context_mcp |
trim | claude_context_mcp |
clear | claude_context_mcp |
status | claude_context_mcp |
optimize | claude_context_mcp |
analyze | claude_context_mcp |
compress_structured | claude_context_mcp |
evaluate_compression | claude_context_mcp |
generate_probes | claude_context_mcp |
set_budget | claude_context_mcp |
get_budget | claude_context_mcp |
check_budget | claude_context_mcp |
detect_degradation | claude_context_mcp |
get_degradation_history | claude_context_mcp |
reset_degradation | claude_context_mcp |
save_session | claude_context_mcp |
load_session | claude_context_mcp |
list_sessions | claude_context_mcp |
categorize_messages | claude_context_mcp |
summarize_category | claude_context_mcp |
get_categories | claude_context_mcp |
search | claude_context_mcp |
info | claude_context_mcp |
list_patterns | claude_context_mcp |