Ketan-OS MCP Server

Ketan-OS MCP Server

Provides transactional intelligence for AI agents, enabling safe tool execution with pre-flight invariant checks, sub-second filesystem snapshots/rollback, causal tracing, belief contradiction detection, and 15 native MCP tools for Claude Code.

Category
Visit Server

README

Ketan-OS ๐Ÿช” (เค•เฅ‡เคคเคจ)

The Transactional Intelligence Substrate & Beacon of Ground Truth for AI Agents

License: MIT Python Version Tests MCP


๐Ÿ”ฑ Origin & Philosophy

"Aham ฤtmฤ guแธฤkeล›a sarva-bhลซtฤล›aya-sthitaแธฅ" โ€” Bhagavad Gita, Chapter 10, Verse 20

"I am the Self, O Gudakesha, seated in the hearts of all beings. I am the beginning, the middle, and the end of all beings."

Ketan (เค•เฅ‡เคคเคจ) literally means Banner, Beacon, or Dwelling in Sanskrit โ€” the fixed, unmovable point of reference from which all navigation begins. In the context of AI agents, Ketan-OS is that beacon of ground truth: the substrate that ensures an agent's environment, memory, and decisions are always anchored to verifiable, uncorrupted reality.

Modern AI agent frameworks (LangGraph, AutoGen, CrewAI) are powerful orchestration layers โ€” but they are blind to what is actually happening on disk and in memory. When an agent writes a malformed file, executes a destructive command, or hallucinates a state that no longer exists, these frameworks have no recovery mechanism. The environment corrupts silently and irrecoverably.

Ketan-OS solves this at the substrate level โ€” not by patching agents, but by wrapping every tool call in transactional guarantees, sub-second snapshot/rollback, pre-flight invariant verification, live causal tracing, and epistemic contradiction detection. It is the OS beneath the agent, not the agent itself.


๐ŸŒŸ Capability Comparison

Capability LangGraph AutoGen CrewAI Ketan-OS ๐Ÿช” What Ketan-OS Does
Environment Filesystem Snapshotting โŒ โŒ โŒ โœ… Sub-Second ShadowFS Before every tool call, Ketan-OS takes an incremental, content-addressed snapshot of the entire workspace filesystem using KetanShadowFS. Stores only changed bytes with LRU eviction. Average snapshot time: 8ms for 1,000 files.
Time-Travel Substrate Rollback โŒ โŒ โŒ โœ… Sub-Second Atomic On any failure โ€” crash, invariant violation, syntax error, bad output โ€” the workspace is reverted byte-for-byte to the last clean checkpoint in < 10ms. No partial writes, no corrupted state. The agent gets a counterfactual hint explaining what went wrong.
Pre-Flight Invariant Assertion Guards โŒ โŒ โŒ โœ… AST + Rule Engine Before a tool executes, Ketan-OS runs pluggable assertion rules: Python AST syntax validation (blocks broken .py files from ever touching disk), financial bounds checking, path safety guards, and custom user-defined rules. Tool is blocked before execution if any rule fails.
Live Causal Execution Trace Graph (CTG) โŒ โŒ โŒ โœ… Live DAG Lineage Every tool call, checkpoint, failure, and rollback is recorded as a node in a directed acyclic graph (DAG). The CTG tracks causal edges โ€” which action led to which outcome. On failure, Ketan-OS traverses the DAG backwards to generate a root cause explanation automatically.
Epistemic Belief Engine & Memory Pruner โŒ โŒ โŒ โœ… Contradiction-Aware Tracks explicit factual beliefs the agent holds about the workspace (e.g., "file X is valid Python"). When a new observation contradicts a prior belief (e.g., "file X now has a syntax error"), the contradiction is detected, the stale belief is marked invalid, and the relevant prompt stack entries are auto-pruned to prevent hallucination loops.
eBPF-Style Symbolic Invariant Kernel โŒ โŒ โŒ โœ… Micro-Patching An in-process rule engine that evaluates temporal logic constraints on tool arguments in sub-millisecond time โ€” inspired by Linux eBPF probes. Instead of just blocking, it can also micro-patch tool args in-flight (e.g., clamp an out-of-range financial amount to a safe value instead of rejecting it).
Predictive Speculative Task Kernel โŒ โŒ โŒ โœ… < 5ms Commit Runs multiple potential tool execution branches in parallel speculatively โ€” like CPU branch prediction, but for AI workflows. The kernel selects and commits the best-outcome branch in < 5ms, discarding the rest. Reduces latency for long tool chains.
Scope-Locked Policy Engine (RBAC) โŒ โŒ โŒ โœ… Declarative RBAC Declarative role-based access control for tools. Define which agent roles can call which tools, which file paths they can write to, and what argument ranges are allowed. Policies are enforced at the substrate level โ€” the agent cannot bypass them.
JIT Skill Trajectory Compilation โŒ โŒ โŒ โœ… Zero-Token Re-runs Compiles repeated agent skill sequences into cached, zero-token executors. If an agent runs the same workflow twice (e.g., "read orders โ†’ validate โ†’ process refund"), the 2nd run executes from a compiled cache with 0 LLM tokens consumed.
Persona State Freeze, Fork & Diff โŒ โŒ โŒ โœ… Portable State Freeze the complete agent state (workspace + memory + conversation), fork it into parallel experiment branches, then diff what changed between branches. Enables A/B testing of agent strategies without any state contamination.
Claude Code MCP Integration โŒ โŒ โŒ โœ… 15 MCP Tools Ships a full Model Context Protocol (MCP) server. Connect Ketan-OS to Claude Code in one config line โ€” Claude gets all 15 Ketan-OS tools natively: safe writes, bash with rollback, CTG visualization, belief tracking, and more.

๐Ÿ—๏ธ System Architecture

graph TD
    subgraph AgentLayer [" ๐Ÿค– Agent Execution Layer "]
        LLM["LLM Agent Loop
        OpenAI โ€ข Claude โ€ข LangGraph โ€ข AutoGen"]
        MCP["๐Ÿ”Œ MCP Server
        Claude Code Integration
        15 Native Tools"]
        Wrapper["๐Ÿ›ก๏ธ KetanAgentWrapper
        Tool Call Interceptor"]
        LLM -->|Tool Call| Wrapper
        MCP -->|Safe Tool Execution| Wrapper
    end

    subgraph CoreEngine [" ๐Ÿช” Ketan-OS Core Substrate "]
        Harness["๐Ÿช” KetanHarness
        Thread-Safe Coordinator"]

        subgraph PreFlight [" Pre-Flight Guard Layer "]
            Verifier["๐Ÿ›ก๏ธ InvariantVerifier
            AST + Rule Engine"]
            Policy["๐Ÿ” PolicyEngine
            RBAC Scope Lock"]
            Symbolic["โšก SymbolicInvariantKernel
            eBPF-Style Micro-Patching"]
            Verifier --> Policy --> Symbolic
        end

        subgraph Speculative [" Speculative Execution "]
            SpecKernel["๐Ÿ”ฎ PredictiveSpeculativeKernel
            Branch Prediction < 5ms"]
        end

        subgraph StorageLedger [" Dual-Ledger Substrate "]
            Ledger["๐Ÿ“‹ KetanLedger
            Checkpoint Registry"]
            ShadowFS["๐Ÿ’พ KetanShadowFS
            Incremental Snapshot
            8ms / 1000 files"]
            Ledger --> ShadowFS
        end

        subgraph Cognition [" Epistemic & Belief Layer "]
            Epistemic["๐Ÿง  EpistemicBeliefEngine
            Contradiction Detection
            Prompt Auto-Pruning"]
        end

        subgraph CTGSubsystem [" Causal Provenance Engine "]
            CTG["๐Ÿงฌ KetanTraceGraph
            Live Execution DAG"]
            RCA["๐Ÿ” Root Cause Analyzer
            Failure Explanation"]
            CTG --> RCA
        end

        subgraph TimeTravel [" Time-Travel Rollback "]
            Rollback["โฑ๏ธ Rollback Controller
            Sub-Second Reversion"]
            Counterfactual["๐Ÿ’ก Counterfactual Engine
            Diagnostic Hint Injector"]
            Rollback --> Counterfactual
        end
    end

    Wrapper -->|"โ‘  Intercept"| Harness
    Harness -->|"โ‘ก Pre-flight"| Verifier
    Symbolic -->|"โ‘ข Pass / Micro-Patch"| Epistemic
    Epistemic -->|"โ‘ฃ Checkpoint"| ShadowFS
    ShadowFS -->|"โ‘ค Execute"| Execution["โš™๏ธ Tool Execution"]

    Symbolic -.->|Fail โ†’ Block| Rollback
    Execution -->|Crash / Error| Rollback

    Execution -->|Success| Commit["๐ŸŸข Commit & Record"]
    Commit --> CTG
    Commit --> Ledger

    Rollback -->|"โ‘ฅ Revert FS"| ShadowFS
    Rollback -->|"โ‘ฆ Record Failure"| CTG
    Counterfactual -->|"โ‘ง Inject Hint"| LLM

    classDef agent    fill:#f3e8ff,stroke:#7c3aed,stroke-width:2px,color:#1e1b4b
    classDef core     fill:#e0f2fe,stroke:#0284c7,stroke-width:2px,color:#0c4a6e
    classDef storage  fill:#d1fae5,stroke:#059669,stroke-width:2px,color:#064e3b
    classDef rollback fill:#ffe4e6,stroke:#e11d48,stroke-width:2px,color:#881337
    classDef ctg      fill:#fef3c7,stroke:#d97706,stroke-width:2px,color:#78350f
    classDef exec     fill:#f0fdf4,stroke:#16a34a,stroke-width:2px,color:#14532d

    class LLM,Wrapper,MCP agent
    class Harness,Verifier,Policy,Symbolic,Epistemic,SpecKernel core
    class Ledger,ShadowFS storage
    class Rollback,Counterfactual rollback
    class CTG,RCA ctg
    class Execution,Commit exec

โšก Quickstart

from ketan import KetanHarness, KetanAgentWrapper

# 1. Initialize Ketan-OS for your project workspace
harness = KetanHarness(workspace_dir="./my_project")
wrapper = KetanAgentWrapper(harness)

# 2. Wrap any tool with transactional protection
def write_code(args):
    with open(args["filepath"], "w") as f:
        f.write(args["content"])
    return "File written"

safe_write = wrapper.wrap_tool("write_file", write_code)

# 3. Execute โ€” Ketan-OS handles snapshot, pre-flight, rollback automatically
result = safe_write(
    tool_args={"filepath": "main.py", "content": "def run():\n    return 42\n"},
    prompt_stack=[{"role": "user", "content": "Create main function"}]
)
print(result)
# โ†’ {"success": True, "result": "File written", "hint": ""}
# If content had a syntax error โ†’ {"success": False, "hint": "Fix SyntaxError on line 1..."}
# โ†’ workspace auto-rolled back, not a single byte changed on disk

๐Ÿ”Œ Claude Code MCP Integration

Ketan-OS ships a ready-to-use MCP server that gives Claude Code 15 native tools for safe, transactional, auditable agentic coding.

1. Install

git clone https://github.com/your-username/ketan-os.git
cd ketan-os
pip install ".[mcp]"

2. Configure Claude Code

Add to ~/.claude/claude.json:

{
  "mcpServers": {
    "ketan-os": {
      "command": "ketan-mcp",
      "args": ["--workspace", "/absolute/path/to/your/project"]
    }
  }
}

That's it. After pip install ".[mcp]", the ketan-mcp command is on your PATH. No --directory flags, no absolute repo paths needed.

3. Start Claude Code

claude

Claude Code will auto-discover and start the Ketan-OS MCP server. You'll see ketan-os in the available tools.

Available MCP Tools

Tool What it does
ketan_get_status Ground-truth state: steps, checkpoints, failures
ketan_snapshot Take atomic workspace snapshot โ†’ get rollback point
ketan_rollback Time-travel revert to any checkpoint
ketan_get_checkpoints List all restore points
ketan_write_file_safe Write file with pre-flight guards + auto rollback
ketan_run_bash_safe Run shell command with snapshot + auto rollback
ketan_check_invariant Dry-run invariant check (no execution)
ketan_get_ctg Causal Trace Graph as Mermaid diagram
ketan_explain_failure Root cause of the last failure
ketan_observe_belief Record a workspace fact into Epistemic Engine
ketan_list_beliefs See all tracked beliefs
ketan_read_file Read file + record as belief
ketan_list_files Browse workspace files
ketan_session_summary Full markdown session report
ketan_init_workspace Switch to a different workspace

๐Ÿงฉ Module Map

Module Class What It Does
ketan/core.py KetanHarness Central thread-safe coordinator engine
ketan/shadow_fs.py KetanShadowFS Incremental workspace snapshotting & rollback
ketan/dual_ledger.py KetanLedger Checkpoint registry synchronizing FS + prompt state
ketan/verifier.py InvariantVerifier Pre-flight AST syntax, safety, and custom rule checks
ketan/epistemic.py EpistemicBeliefEngine Belief tracking, contradiction detection, prompt pruning
ketan/symbolic_kernel.py SymbolicInvariantKernel eBPF-style sub-ms rule eval & in-flight arg micro-patching
ketan/speculative_kernel.py PredictiveSpeculativeKernel Parallel branch speculative execution < 5ms commit
ketan/causal_graph.py KetanTraceGraph Live execution DAG + root cause failure explanation
ketan/policy.py PolicyEngine Declarative RBAC scope-lock for tool calls
ketan/jit_compiler.py JITCompiler Zero-token cached skill trajectory compiler
ketan/persona.py PersonaManager Agent state freeze, fork & diff
ketan/adapters/ KetanAgentWrapper LangGraph + generic LLM adapter middleware
ketan/mcp/server.py MCP Server 15 Claude Code MCP tools via stdio transport

๐Ÿงช Running Tests

uv run python -m unittest discover tests
# โ†’ Ran 67 tests in 0.18s OK
# โ†’ [BENCHMARK] 50 Files Snapshot Time: ~8ms
# โ†’ [BENCHMARK] 50 Files Rollback Time: ~4ms

๐Ÿ“œ License

MIT License. Copyright (c) 2026 umang-algo.

Recommended Servers

playwright-mcp

playwright-mcp

A Model Context Protocol server that enables LLMs to interact with web pages through structured accessibility snapshots without requiring vision models or screenshots.

Official
Featured
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

An AI-powered tool that generates modern UI components from natural language descriptions, integrating with popular IDEs to streamline UI development workflow.

Official
Featured
Local
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

Enables interaction with Audiense Insights accounts via the Model Context Protocol, facilitating the extraction and analysis of marketing insights and audience data including demographics, behavior, and influencer engagement.

Official
Featured
Local
TypeScript
VeyraX MCP

VeyraX MCP

Single MCP tool to connect all your favorite tools: Gmail, Calendar and 40 more.

Official
Featured
Local
graphlit-mcp-server

graphlit-mcp-server

The Model Context Protocol (MCP) Server enables integration between MCP clients and the Graphlit service. Ingest anything from Slack to Gmail to podcast feeds, in addition to web crawling, into a Graphlit project - and then retrieve relevant contents from the MCP client.

Official
Featured
TypeScript
Kagi MCP Server

Kagi MCP Server

An MCP server that integrates Kagi search capabilities with Claude AI, enabling Claude to perform real-time web searches when answering questions that require up-to-date information.

Official
Featured
Python
E2B

E2B

Using MCP to run code via e2b.

Official
Featured
Neon Database

Neon Database

MCP server for interacting with Neon Management API and databases

Official
Featured
Exa Search

Exa Search

A Model Context Protocol (MCP) server lets AI assistants like Claude use the Exa AI Search API for web searches. This setup allows AI models to get real-time web information in a safe and controlled way.

Official
Featured
Qdrant Server

Qdrant Server

This repository is an example of how to create a MCP server for Qdrant, a vector search engine.

Official
Featured