Cognitive Context Protocol (CCP)
The World’s First Cognitive Architecture for AI Agents
Transform AI from passive context consumers into self-aware, contract-driven cognitive agents.
CCP provides the missing cognitive layer for Large Language Models. It acts as a Hippocampus for episodic memory, a Prefrontal Cortex for meta-cognition, and now a Frontal Lobe Executive for enforced, contract-driven task execution. By tracking confidence, confusion, causal relationships, and now verified execution contracts, CCP enables agents that don’t just retrieve data, but remember, reason, plan, and guarantee outcomes over time.
π The Problem We Solve
Current AI systems suffer from cognitive blindness:
| Problem | Traditional AI | CCP-Enabled AI |
|---|---|---|
| Self-Awareness | None – operates blindly | Knows what it understands and what it doesn’t |
| Confidence | Overconfident or underconfident | Calibrated confidence from outcome tracking |
| Memory | Stateless or simple RAG | Episodic memory with emotional valence and decay |
| Learning | Requires retraining | Continuous learning from every interaction |
| Reasoning | Correlational | Causal β can answer “what if?” questions |
| Context | Fixed window, dump everything | Hierarchical, load-adaptive, attention-gated |
| Execution | Ad-hoc, unverified steps | Contract-enforced plans with preconditions & repair |
π‘ What Makes CCP Revolutionary
1. Cognitive State Awareness
Unlike any existing system, CCP maintains a multi-dimensional cognitive state vector that tracks:
{
understanding_depth: 0.85, // How deeply the AI comprehends the task
confidence_score: 0.72, // Calibrated via Rescorla-Wagner prediction error
cognitive_load: 0.63, // Current processing demands
knowledge_gaps: [ // Explicit awareness of unknowns
{ domain: "user_preferences", severity: "moderate", impact: 0.45 }
],
meta_cognitive_flags: {
needs_clarification: false, // Should it ask questions?
exploration_required: true, // Should it seek more context?
confidence_threshold_met: true
}
}
This is the first AI system that knows when it doesn’t know. It employs a Bayesian-inspired learning model (Rescorla-Wagner) where confidence is updated based on prediction error, dampened by high cognitive load, and accelerated by surprise.
2. Episodic Memory Architecture
CCP doesn’t just retrieve contextβit forms semantic episodes that mirror human memory:
{
id: "ep_2025_11_18_001",
type: "problem_solving_session",
semantic_summary: "User requested budget analysis with focus on Q4 anomalies",
cognitive_elements: {
entities: ["budget", "Q4", "anomaly_detection"],
relationships: [
{ type: "causal", from: "spending_increase", to: "budget_overrun" }
],
outcomes: { success: true, user_satisfaction: 0.9 }
},
emotional_valence: 0.7, // Positive experience
relevance_decay: {
function: "exponential",
half_life: "30_days"
},
associative_links: ["ep_2025_oct_12_043", "ep_2025_nov_01_089"]
}
Episodes are linked, decayed, and retrieved by analogyβjust like human memory.
3. Causal Cognitive Modeling (Breakthrough)
CCP doesn’t just find correlationsβit builds causal graphs and reasons counterfactually:
Q: "What would have happened if we hadn't added caching?"
A: "Based on causal analysis of 47 similar episodes:
- Response time would be 340% higher (confidence: 0.84)
- User satisfaction would drop to 0.45 (confidence: 0.71)
- Causal path: no_cache β slow_queries β timeout_errors β user_frustration"
This is the first AI that can answer “what if?” questions about its own experiences.
4. Hierarchical Context Abstraction (Breakthrough)
CCP organizes information across 4 abstraction levels, dynamically selecting based on task:
Level 4: Strategic Insight β "Market shift toward sustainability"
Level 3: Tactical Summary β "Q3 +12%, Q4 +8%, driven by green products"
Level 2: Operational Detail β "Product A: $2.4M +15%; Product B: $1.8M +8%"
Level 1: Complete Data β [Full transaction records, timestamps, etc.]
For strategic planning β L3-L4. For debugging β L1-L2. Automatic.
This is the first AI that compresses context hierarchically like human working memory.
5. Gated Attention Filtering (Breakthrough)
Instead of dumping all context, CCP uses 5 learned attention heads to filter:
| Head | What It Prioritizes |
|---|
| Recency | Recent experiences | | Causal Importance | Episodes with clear cause-effect | | Domain Similarity | Related knowledge domains | | Outcome Relevance | Successful past experiences | | Semantic Match | Query-relevant content |
Weights are learned from outcomesβthe system gets better at filtering over time.
This is the first AI with learned, multi-head context attention.
6. Episodic Drift & Continuous Learning (Breakthrough)
CCP updates its understanding continuously without retraining:
Initial belief: "Marketing campaigns increase sales" (confidence: 0.6)
β 50 campaigns later
Updated: "Campaigns + seasonal timing explains 73% of variance" (confidence: 0.82)
β 200 campaigns later
Refined: "Effectiveness varies by channel, timing, product category (RΒ²=0.89)"
With safety guardrails:
- Reversal protection (70% evidence required)
- Drift bounds (max 15% change per cycle)
- Paradigm shift detection with human review triggers
This is the first AI that learns incrementally while maintaining stability.
7. Contract-Oriented Graph Prompting (COGP) (v2.0 β Phase 11)
CCP now natively enforces the COGP protocol β a three-phase execution discipline that turns ad-hoc AI reasoning into machine-verifiable, contract-driven plans:
Phase 1 β Contract Synthesis
AI calls ccp_cogp_plan() with a DAG of ContractNodes, each specifying:
goal, preconditions, successCriteria, failurePolicy, tool, dependencies
Phase 2 β Contract Execution
Nodes execute one at a time in dependency order:
ccp_cogp_execute_node(action="start") β marks node running
ccp_cogp_execute_node(action="succeed") β persists output to shared state
ccp_cogp_execute_node(action="fail") β applies failure policy atomically
βββ retry β resets node to pending for another attempt
βββ skip β marks skipped, unlocks dependents
βββ escalate β triggers Phase 3 reflection immediately
βββ abort β halts the entire graph
Phase 3 β Contract Reflection
Critic reviews all executed nodes:
ccp_cogp_reflect() β scores every node, identifies failures,
returns shouldContinue + repair actions
Why this matters: Previous prompting techniques (Chain-of-Thought, ReAct, Tree-of-Thoughts) structured thinking but couldn’t enforce it. COGP provides the runtime layer β precondition verification, dependency scheduling, atomically applied failure policies, and a shared blackboard state β all as first-class MCP tools. No external Python orchestrator. No LangGraph. No Swarm middleware. Pure MCP.
// Example: 3-node contract graph
await mcp.callTool('ccp_cogp_plan', {
task: 'Analyze codebase and create PR',
nodes: [
{ id: 'analyze', role: 'executor', kind: 'tool_step',
goal: 'Read src/ and identify refactor targets',
tool: { name: 'read', params: { path: 'src/' } },
successCriteria: ['at least one file analyzed'],
failurePolicy: 'retry', maxRetries: 2, dependencies: [] },
{ id: 'plan', role: 'planner', kind: 'thought',
goal: 'Produce a ranked list of changes with rationale',
successCriteria: ['list has β₯1 item'],
failurePolicy: 'escalate', dependencies: ['analyze'] },
{ id: 'pr', role: 'executor', kind: 'tool_step',
goal: 'Create pull request with the planned changes',
tool: { name: 'create_pull_request', params: {} },
successCriteria: ['PR URL returned'],
failurePolicy: 'abort', dependencies: ['plan'] }
]
});
// β graph_id returned; ready_nodes: [analyze]
// Execute nodes as they become ready, reflect after each wave
π οΈ The 31 MCP Tools
Core Cognitive Tools (7)
| Tool | What It Does |
|---|---|
ccp_query_state | Get current cognitive state (understanding, confidence, gaps) |
ccp_update_state | Update state with outcome-based calibration |
ccp_create_episode | Form episodic memory with embedding |
ccp_retrieve_memory | Semantic + temporal + emotional retrieval |
ccp_adaptive_context | Load-aware progressive disclosure |
ccp_meta_decide | Should I proceed, clarify, or explore? |
ccp_multimodal_fuse | Unify text + visual + contextual data |
Breakthrough Tools (Phases 5-8)
| Tool | What It Does |
|---|---|
ccp_causal_analyze | Build causal graphs, counterfactuals, root cause |
ccp_hierarchical_context | L1-L4 dynamic abstraction |
ccp_gated_attention | Multi-head attention filtering |
ccp_drift_detect | Continuous learning + paradigm shifts |
Advanced Cognitive Tools (Phase 9+)
| Tool | What It Does |
|---|---|
ccp_inject_rules | Neuro-symbolic reasoning with rule injection |
ccp_meta_decide_reflective | Iterative reflection with self-critique |
ccp_query_state_introspective | Introspective state with reasoning chains |
ccp_fuse_efficient | Mixture-of-Experts multimodal routing |
ccp_model_agent_belief | Theory of Mind β model agent beliefs |
ccp_meta_learning | Task signatures and transfer learning |
ccp_simulate_future | World model simulation and planning |
ccp_temporal_query | Allen’s Interval Algebra temporal reasoning |
ccp_adaptive_biometric | EEG/HRV biometric-aware context |
Claude Skills Integration (8)
| Tool | What It Does |
|---|---|
ccp_discover_skills | List available Claude skills with metadata |
ccp_activate_skill | Progressive skill activation (L1/L2/L3) |
ccp_find_skills | Semantic search for task-matching skills |
ccp_ingest_skills | Ingest skills from directory or GitHub |
ccp_load_skill_resource | Load specific script/reference from skill |
ccp_execute_skill_script | Run skill scripts in sandbox |
ccp_record_skill_outcome | Record effectiveness for meta-learning |
ccp_skill_recommendations | Get recommendations from usage history |
COGP β Contract-Oriented Graph Prompting (4) β¨ New in v2.0
| Tool | What It Does |
|---|---|
ccp_cogp_plan | Phase 1 β Submit a contract graph (DAG of nodes with preconditions, tools, failure policies). Validates dependencies; returns the first wave of ready nodes. |
ccp_cogp_execute_node | Phase 2 β Report start / succeed / fail for each node. Failure policy applied atomically: retry resets, skip unlocks dependents, escalate triggers reflection, abort halts graph. |
ccp_cogp_reflect | Phase 3 β Critic evaluates all executed nodes against success criteria. Returns per-node verdicts, overall quality score, critical issues, and repair recommendations. |
ccp_cogp_status | Any phase β Inspect progress counters, shared blackboard state, and next schedulable node wave for any graph. |
π Quick Start
1. Start the Server
cd server
npm install
npm run dev # stdio MCP server (default)
npm run build # compile to dist/
npm start # production build
2. Add to Your MCP Config
{
"ccp-server": {
"command": "npx",
"args": ["tsx", "path/to/ccp/server/src/mcp-server.ts"],
"env": {
"OLLAMA_BASE_URL": "http://localhost:11434",
"OLLAMA_EMBED_MODEL": "nomic-embed-text"
}
}
}
3. Start Using Cognitive AI
// ββ Know what you don't know ββββββββββββββββββββββββββββββββββββββ
const state = await mcp.callTool('ccp_query_state', {});
console.log(`Confidence: ${state.confidence_score}`);
console.log(`Knowledge gaps: ${state.knowledge_gaps.length}`);
// ββ Remember and learn ββββββββββββββββββββββββββββββββββββββββββββ
await mcp.callTool('ccp_create_episode', {
type: 'debugging',
semantic_summary: 'Fixed race condition in auth flow',
entities: ['auth', 'race_condition', 'async'],
success: true
});
// ββ Ask "what if?" ββββββββββββββββββββββββββββββββββββββββββββββββ
const counterfactual = await mcp.callTool('ccp_causal_analyze', {
mode: 'counterfactual',
intervention: 'remove async call',
target: 'race condition'
});
// ββ Execute a COGP contract graph βββββββββββββββββββββββββββββββββ
const { graph_id, ready_nodes } = await mcp.callTool('ccp_cogp_plan', {
task: 'Analyze repo and open a PR',
nodes: [
{ id: 'read', role: 'executor', kind: 'tool_step',
goal: 'Read source files',
tool: { name: 'read', params: { path: 'src/' } },
successCriteria: ['files returned'],
failurePolicy: 'retry', maxRetries: 2, dependencies: [] },
{ id: 'analyze', role: 'planner', kind: 'thought',
goal: 'Identify top 3 improvement areas',
successCriteria: ['list has β₯1 item'],
failurePolicy: 'escalate', dependencies: ['read'] },
{ id: 'pr', role: 'executor', kind: 'tool_step',
goal: 'Create pull request',
tool: { name: 'create_pull_request', params: {} },
successCriteria: ['PR URL returned'],
failurePolicy: 'abort', dependencies: ['analyze'] }
]
});
// Execute each ready node, then reflect
await mcp.callTool('ccp_cogp_execute_node',
{ graph_id, node_id: 'read', action: 'start' });
// β¦ perform work β¦
await mcp.callTool('ccp_cogp_execute_node',
{ graph_id, node_id: 'read', action: 'succeed', output: { files: ['index.ts'] } });
// After a wave completes, run the critic
const report = await mcp.callTool('ccp_cogp_reflect', { graph_id });
console.log(`Quality score: ${report.overallScore}`);
console.log(`Continue: ${report.shouldContinue}`);
π¦ SDKs
Note: The SDKs are optional client libraries for easier integration with the CCP server. The server runs independently and can be accessed directly via MCP tools without the SDKs.
TypeScript
import { CCPClient } from '@ccp/sdk';
const ccp = new CCPClient(mcpClient);
// Cognitive state
const state = await ccp.queryState();
// Causal reasoning
const result = await ccp.counterfactual({
intervention: 'double team size',
target: 'project velocity'
});
// Continuous learning
const insights = await ccp.getLearningInsights();
console.log(`Model health: ${insights.modelHealth}`);
Python
from ccp import CCPClient
ccp = CCPClient(mcp_call_tool)
# Hierarchical context
context = await ccp.hierarchical_context(
task_type='strategic_planning',
cognitive_load=0.7
)
print(f"Abstraction level: {context['level_name']}")
# Drift detection
drift = await ccp.detect_drift()
if drift['paradigmShifts']:
print("Major learning shift detected!")
ποΈ Architecture
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β MCP Interface Layer β
β (31 Tools + 3 Resources for AI Agents) β
βββββββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββββββ€
β β β
β ββββββββββββββββββββββββ β ββββββββββββββββββββββββββββββββββββ β
β β COGP Engine (NEW) β β β Meta-Cognitive Reasoner β β
β β Phase 1: Plan graph β β β (Reflection, Self-Critique, β β
β β Phase 2: Exec nodes β β β Iterative Refinement) β β
β β Phase 3: Reflect β β ββββββββββββββββ¬ββββββββββββββββββββ β
β β FailurePolicy engineβ β β β
β ββββββββββββ¬ββββββββββββ β ββββββββββββββββΌββββββββββββββββββββ β
β β β β Causal Engine + World Model β β
β β β β (Counterfactuals, Simulation, β β
β β β β Neuro-Symbolic Rules) β β
β β β ββββββββββββββββββββββββββββββββββββ β
β β β β
βββββββββββββββΌββββββββββββββββΌβββββββββββββββββββββββββββββββββββββββββ€
β Cognitive State Manager β
β (Understanding, Confidence, Gaps, Load, Introspection) β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Episodic Memory Engine β
β (Vector Embeddings + Semantic Episodes + Temporal Algebra) β
ββββββββββββββββββββ¬ββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββ€
β Hierarchical β Gated Attention β Antigravity Bridge β
β Context (L1-L4) β (5 Learned Heads) β (Multi-Agent + ToM) β
ββββββββββββββββββββ΄ββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββ€
β Episodic Drift β Meta-Learning β Biometric Adaptation β
β (Continuous Learn)β (Task Signatures) β (EEG/HRV/GSR) β
βββββββββββββββββββββββ΄ββββββββββββββββββββ΄ββββββββββββββββββββββββββ-ββ€
β Claude Skills Integration (Discover, Activate, Execute) β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Persistence (SQLite + Ollama Embeddings) β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
π Current Implementation
What’s Built
CCP is a fully functional MCP server with 31 cognitive tools, implemented across 11 development phases:
| Phase | Feature | Status | Files |
|---|---|---|---|
| Phase 1 | Core Cognitive State (Bayesian) | β Complete | cognitiveState.ts |
| Phase 2 | MCP Server β sole entrypoint | β Complete | mcp-server.ts |
| Phase 3 | Vector Embeddings | β Complete | embeddings.ts, persistence.ts |
| Phase 5 | Causal Cognitive Modeling | β Complete | causalEngine.ts |
| Phase 6 | Hierarchical Context | β Complete | hierarchicalContext.ts |
| Phase 7 | Gated Attention | β Complete | gatedAttention.ts |
| Phase 8 | Episodic Drift | β Complete | episodicDrift.ts |
| Phase 9.1 | Neuro-Symbolic AI | β Complete | causalEngine.ts (enhanced) |
| Phase 9.2 | Reflection & Self-Critique | β Complete | metaReasoner.ts (enhanced) |
| Phase 9.3 | Introspective Awareness | β Complete | cognitiveState.ts (enhanced) |
| Phase 9.4 | Efficient Multimodal (MoE) | β Complete | multimodal.ts (enhanced) |
| Phase 9.6 | Meta-Learning | β Complete | episodicDrift.ts (enhanced) |
| Phase 9.7 | World Models | β Complete | worldModel.ts |
| Phase 9.8 | Temporal Reasoning | β Complete | episodicMemory.ts (enhanced) |
| Phase 9.9 | Biometric Cognition | β Complete | adaptiveContext.ts (enhanced) |
| Phase 10 | Claude Skills Integration | β Complete | skillLoader.ts, skill-executor.ts |
| Phase 11 | COGP β Contract Execution β¨ | β v2.0 | cogpEngine.ts, schemas.ts |
Code Structure
server/src/
βββ mcp-server.ts # Sole MCP entrypoint β 31 Tools, 3 resources
βββ services/
β βββ cogpEngine.ts # β¨ NEW: COGP 3-phase contract execution engine
β βββ cognitiveState.ts # Cognitive state + introspection
β βββ episodicMemory.ts # Episodic memory + temporal reasoning
β βββ embeddings.ts # Ollama integration (nomic-embed-text)
β βββ persistence.ts # SQLite storage (sql.js)
β βββ adaptiveContext.ts # Load-aware + biometric + skills
β βββ metaReasoner.ts # Meta-cognitive + reflection + skills
β βββ multimodal.ts # Multi-modal + MoE routing
β βββ causalEngine.ts # Causal + neuro-symbolic
β βββ hierarchicalContext.ts # L1-L4 abstraction
β βββ gatedAttention.ts # Multi-head attention
β βββ episodicDrift.ts # Continuous learning + meta-learning
β βββ worldModel.ts # World simulation + planning
β βββ skillLoader.ts # Claude Skills ingestion
βββ integration/
β βββ skill-executor.ts # Sandboxed skill script execution
βββ protocol/
βββ schemas.ts # β¨ UPDATED: TypeScript types + COGP contract types
βββ ccp.capnp # Binary schema
Total: ~8,500+ lines of TypeScript + 302 lines Cap’n Proto
v2.0 change: The Express/WebSocket HTTP REST server (
index.ts) has been removed.mcp-server.tsis the single, canonical entrypoint. All intelligence β including COGP contract execution β is surfaced as MCP tools with no external orchestration framework required.
Cap’n Proto Schema
We’ve implemented a complete Cap’n Proto schema (ccp.capnp) for high-performance binary serialization:
# Core types defined
struct CognitiveStateVector { ... } # Understanding, confidence, gaps
struct Episode { ... } # Episodic memory with embeddings
struct AdaptiveContextRequest { ... } # Load-adaptive retrieval
struct MetaCognitiveDecision { ... } # Reasoning about reasoning
# RPC interfaces ready for binary transport
interface CognitiveStateService { ... }
interface EpisodicMemoryService { ... }
interface AdaptiveContextService { ... }
interface MetaCognitiveService { ... }
interface AgentCoordinationService { ... }
Current Transport: JSON-RPC 2.0 (MCP standard)
Future Option: Cap’n Proto binary transport for zero-copy, sub-millisecond latency
SDKs
| SDK | Language | Status | Features |
|---|---|---|---|
| TypeScript | @ccp/sdk | β Complete | Type-safe wrappers, 290 lines |
| Python | ccp-sdk | β Complete | Async + type hints, 320 lines |
Dependencies
| Dependency | Purpose |
|---|---|
@modelcontextprotocol/sdk | MCP protocol implementation |
sql.js | Pure-JS SQLite for persistence |
zod | Runtime type validation |
uuid | Unique IDs for contract graphs and nodes |
Roadmap
- Neuro-Symbolic AI: Hybrid neural+symbolic reasoning with rule injection
- Reflection & Self-Critique: Iterative decision refinement with quality rubrics
- Theory of Mind: Epistemic modeling of agent beliefs
- World Models: Physics-aware simulation and planning
- Temporal Reasoning: Allen’s Interval Algebra for time-aware queries
- Claude Skills Integration: Ingest, activate, and execute Claude Skills
- COGP Contract Execution: Native 3-phase contract graph enforcement as MCP tools
- Binary Transport: Enable Cap’n Proto for 50-70% smaller payloads
- Distributed Memory: Sharded episodic memory across agent pools
- COGP Persistence: Durable graph state surviving server restarts
π Documentation
| Document | Description |
|---|
| Cognitive Breakthrough Spec | Full 1100-line protocol specification | | Cap’n Proto + MCP Integration | Binary transport design | | TypeScript SDK | Type-safe client with examples | | Python SDK | Async client with type hints |
π§ Configuration
| Variable | Default | Description |
|---|
| OLLAMA_BASE_URL | http://localhost:11434 | Ollama API |
| OLLAMA_EMBED_MODEL | nomic-embed-text | 768-dim embeddings |
License
MIT
Built for the next generation of AI
CCP: Because AI should understand itself
Developed and Engineered by Anthony Cavanaugh for Cavanaugh Design Studio
[cavanaughdesignstudio.com]



