Ketan-OS MCP Server
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@Ketan-OS MCP Server Snapshot the workspace and run the tests with rollback on failure"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
Ketan-OS πͺ (ΰ€ΰ₯ΰ€€ΰ€¨)
The Transactional Runtime for AI Agents
π± 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.
AI agents perform complex, multi-step actions across files, commands, and external tools β but they lack transaction semantics. When an agent writes a malformed file, executes a destructive shell command, or acts on stale assumptions, standard agent frameworks have no rollback mechanism.
Ketan-OS provides the transactional substrate for AI agents:
BEGIN β WAL JOURNAL β VERIFY β SANDBOX EXEC β COMMIT / ROLLBACK / COMPENSATEBy wrapping tool execution in content-addressed state snapshotting, durable WAL journal persistence, container sandbox isolation, pre-flight assertion guards, causal execution provenance, and prompt contradiction pruning, Ketan-OS makes agent tool execution safe, reversible, and debuggable.
Related MCP server: agent-rewind
π Core Architectural Subsystems
Subsystem | Component | What Ketan-OS Does |
1. Transactional Workspace Recovery |
| Takes incremental, content-addressed workspace snapshots using SHA-256 blob deduplication ( |
2. Durable Write-Ahead Journal (WAL) |
| Synchronously appends transaction events ( |
3. Execution Sandbox Engines |
| Provides isolated tool execution backends. Enforces strict canonical path confinement locally or runs commands in isolated Docker containers. |
4. System Compensation Drivers |
| Executes registered inverse operations ( |
5. Multi-Layer Pre-Flight Guards |
| Enforces strict workspace canonical path isolation ( |
6. Causal Execution Provenance DAG |
| Records tool calls, checkpoints, failures, and rollbacks into a directed acyclic graph (DAG). On failure, automatically traverses the DAG backwards to explain the execution lineage. |
7. State Belief & Fact Store |
| Tracks factual assertions about workspace state. Uses type coercion ( |
π‘οΈ Side-Effect Reversibility Matrix
Ketan-OS tracks tool operations across three distinct transaction recovery tiers:
System / Target | Reversibility Tier | Recovery Strategy |
Local Workspace Files |
| Automatic content-addressed state rollback via |
Git Repositories |
| Automated workspace restore / branch checkpoint reversion |
PostgreSQL / SQL Databases |
| Inverse transaction query or registered compensation handler |
S3 / Blob Storage |
| Object versioning rollback or compensation handler |
GitHub / AWS / Infrastructure |
| Registered API inverse call (e.g. close issue, delete resource) |
External Network APIs / Email |
| Pre-execution policy check & counterfactual failure hint |
π Formal Ketan-OS Transaction Protocol Specification
Ketan-OS formally defines the execution boundary around agent actions across four authoritative layers:
Component Layer | Persistent Storage | Role & Guarantee |
Write-Ahead Log (WAL) |
| Authoritative Transaction State Log β Synchronous |
Dual-Ledger Index |
| Checkpoint Index & Turn History β $O(1)$ append-only index mapping |
Workspace State Engine |
| Content-Addressed State Store β Incremental workspace snapshots with JSON manifests and deduplicated file blobs. |
Effect Contract Engine |
| Observable System Mutation Contract β Captures preconditions, postconditions, and compensation conflict detection. |
AGENT TRANSACTION LIFECYCLE
β
βΌ
ββββββββββββββββββββββββββββββββββββ
β WAL Journal (.ketan/journal) β
β TX_BEGIN β TX_EFFECT β COMMIT β
ββββββββββββββββββ¬ββββββββββββββββββ
β
ββββββββββββββββββ΄ββββββββββββββββββ
β Dual-Ledger (.ketan/ledger) β
β Hash-Chained State Commitment β
ββββββββββββββββββ¬ββββββββββββββββββ
β
ββββββββββββββββββ΄ββββββββββββββββββ
β ShadowFS (.ketan/snapshots) β
β Manifest & Blob Storage β
ββββββββββββββββββ¬ββββββββββββββββββ
β
ββββββββββββββββββ΄ββββββββββββββββββ
β Effect Contract Engine β
β Pre/Postcondition Verification β
ββββββββββββββββββββββββββββββββββββποΈ System Architecture
graph TD
subgraph AgentLayer [" π€ Agent Execution Layer "]
LLM["LLM Agent Loop
OpenAI β’ Claude β’ LangGraph β’ AutoGen"]
MCP["π FastMCP Server
Claude Code Integration"]
Wrapper["π‘οΈ KetanAgentWrapper
Tool Call Interceptor"]
LLM -->|Tool Call| Wrapper
MCP -->|Safe Tool Execution| Wrapper
end
subgraph CoreEngine [" πͺ Ketan-OS Transactional Substrate "]
Harness["πͺ KetanHarness
Thread-Safe Coordinator"]
subgraph WALJournal [" Durable WAL Journal "]
Journal["π TransactionJournal
.ketan/journal.jsonl Persistence"]
end
subgraph PreFlight [" Pre-Flight Guard Layer "]
Verifier["π‘οΈ InvariantVerifier
Canonical Path Confinement
Symlink Guard + AST & Safety Rules"]
end
subgraph Sandboxes [" Execution Sandbox Engines "]
Sandbox["π¦ Local / Docker Sandbox Engine
Path Confinement & Container Isolation"]
end
subgraph StorageLedger [" Dual-Ledger Substrate "]
Ledger["π KetanLedger
Checkpoint & Reversibility Registry"]
ShadowFS["πΎ KetanShadowFS
Content-Addressed Workspace Recovery"]
Ledger --> ShadowFS
end
subgraph Cognition [" State Belief Layer "]
Epistemic["π§ EpistemicBeliefEngine
Runtime Fact Store &
Prompt Contradiction Pruning"]
end
subgraph CTGSubsystem [" Causal Provenance Engine "]
CTG["𧬠KetanTraceGraph
Causal Execution Provenance DAG"]
RCA["π Provenance Analyzer
Execution Lineage Explanation"]
CTG --> RCA
end
subgraph TimeTravel [" Transaction Recovery & Compensation "]
Rollback["β±οΈ Rollback Controller
Workspace State Reversion"]
CompDrivers["π System Compensation Drivers
Git & SQL Inverse Actions"]
Counterfactual["π‘ Counterfactual Engine
Diagnostic Hint Injector"]
Rollback --> CompDrivers
CompDrivers --> Counterfactual
end
end
Wrapper -->|"β Intercept"| Harness
Harness -->|"β‘ WAL Record TX_BEGIN"| Journal
Journal -->|"β’ Pre-flight"| Verifier
Verifier -->|"β£ Pre-Flight Pass"| Epistemic
Epistemic -->|"β€ Checkpoint"| ShadowFS
ShadowFS -->|"β₯ Sandbox Exec"| Sandbox
Sandbox -->|"β¦ Execute Tool"| Execution["βοΈ Tool Execution"]
Verifier -.->|Path / Syntax / Safety Fail| Rollback
Execution -->|Crash / Exception| Rollback
Execution -->|Success| Commit["π’ WAL Commit & Record"]
Commit --> CTG
Commit --> Ledger
Rollback -->|"β§ Revert Workspace"| ShadowFS
Rollback -->|"β¨ Execute Compensations"| CompDrivers
Rollback -->|"β© Record Failure Node"| 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,Epistemic,Journal,Sandbox core
class Ledger,ShadowFS storage
class Rollback,CompDrivers,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 cleanlyπ Claude Code FastMCP Integration
Ketan-OS ships a ready-to-use FastMCP server that gives Claude Code native tools for safe, transactional, auditable agentic coding.
1. Install
git clone https://github.com/umang-algo/ketan-os.git
cd ketan-os
uv pip install -e .2. Configure Claude Code
Add to ~/.claude/claude.json:
{
"mcpServers": {
"ketan-os": {
"command": "python",
"args": ["-m", "ketan.mcp.server", "--workspace", "/absolute/path/to/your/project"]
}
}
}π§ͺ Running Tests & Benchmarks
# Run unit test suite
uv run pytest tests/
# Run performance benchmark suite
uv run python examples/benchmark_ketan_performance.pyπ License
MIT License. Copyright (c) 2026 umang-algo.
Available Tools
15 toolsketan_check_invariantA
Run a pre-flight invariant check WITHOUT executing anything. Validate a planned action before committing to it.
Args: tool_name: Name of the tool you plan to call (e.g., "write_file", "bash") tool_args_json: JSON string of the arguments you plan to pass
Inputs: tool_name (required), tool_args_json (required). Returns: result
ketan_explain_failureA
Get a root-cause explanation of the most recent failure in the CTG. Traces the exact execution chain that led to the failure. Returns a clean message if no failures exist.
Inputs: no named parameters. Returns: result
ketan_get_checkpointsA
List all available checkpoints in the Ketan dual-ledger (newest first). Each checkpoint captures the full workspace filesystem state and conversation prompt stack, enabling atomic rollback to any point.
Inputs: no named parameters. Returns: result
ketan_get_ctgA
Get the Causal Trace Graph (CTG) as a Mermaid diagram. The CTG is a live DAG showing every tool call, checkpoint, failure, and rollback in the session with causal edges between them. Paste the output into mermaid.live to visualize it.
Inputs: no named parameters. Returns: result
ketan_get_statusA
Get the current Ketan-OS ground-truth state report. Returns step count, checkpoint count, CTG node/edge counts, failure count, and workspace directory.
Inputs: no named parameters. Returns: result
ketan_init_workspaceA
Initialize Ketan-OS for a workspace directory. This MUST be called before any other Ketan-OS tools if you are switching workspaces. Creates a KetanHarness that manages transactional snapshotting, invariant enforcement, and causal tracing for the given workspace.
Args: workspace_path: Absolute path to the project/workspace directory to protect.
Inputs: workspace_path (required). Returns: result
ketan_list_beliefsA
List all active beliefs tracked by the Epistemic Belief Engine. These are facts observed about the workspace during this session.
Inputs: no named parameters. Returns: result
ketan_list_filesA
List all files in the workspace (or a subdirectory of it).
Args: subdirectory: Optional subdirectory relative to workspace root (default: root)
Inputs: subdirectory. Returns: result
ketan_observe_beliefA
Record a factual observation into the Epistemic Belief Engine. The engine tracks beliefs about the workspace and detects contradictions (e.g., "tests pass" followed by "tests fail") to prevent hallucination loops.
Args: subject: What the belief is about (e.g., "tests/test_main.py") predicate: The relationship (e.g., "exists", "passes", "contains_bug") value: The observed value (e.g., "true", "false", "syntax_error") confidence: Confidence level 0.0β1.0 (default 1.0)
Inputs: value (required), subject (required), predicate (required), confidence. Returns: result
ketan_read_fileA
Read a file from the workspace. Also records its existence as a belief.
Args: filepath: Path relative to workspace root (e.g., "src/main.py")
Inputs: filepath (required). Returns: result
ketan_rollbackA
Time-travel rollback the workspace to a previous checkpoint. Reverts ALL filesystem changes (file writes, deletions, renames) that occurred after that checkpoint was taken, in sub-second time.
Args: checkpoint_id: The checkpoint ID to roll back to (from ketan_get_checkpoints or ketan_snapshot).
Inputs: checkpoint_id (required). Returns: result
ketan_run_bash_safeA
Execute a shell command with FULL Ketan-OS protection:
Pre-flight dangerous command guard (blocks rm -rf /, fork bombs, etc.).
Atomic snapshot before execution.
Run the command in the workspace directory.
On non-zero exit or exception β automatic rollback to pre-command state.
Always prefer this over raw bash for state-changing commands.
Args: command: Shell command to run (executed in workspace directory) timeout_seconds: Maximum execution time before timeout (default: 30s)
Inputs: command (required), timeout_seconds. Returns: result
ketan_session_summaryA
Get a complete markdown summary of the Ketan-OS session: steps taken, checkpoints created, failures recorded, beliefs tracked.
Inputs: no named parameters. Returns: result
ketan_snapshotA
Take an atomic filesystem snapshot of the entire workspace. Creates a checkpoint you can roll back to if anything goes wrong. Always call this before a risky sequence of operations.
Returns the checkpoint ID you can use with ketan_rollback.
Inputs: no named parameters. Returns: result
ketan_write_file_safeA
Write a file to the workspace with FULL Ketan-OS protection:
Pre-flight invariant guard: Python AST syntax check for .py files, dangerous pattern detection.
Atomic snapshot of current workspace state before writing.
Write the file.
On any failure β automatic rollback to pre-write state.
Always prefer this over direct file writes for safe, reversible mutations.
Args: filepath: Path relative to workspace root (e.g., "src/main.py") content: Full file content to write
Inputs: content (required), filepath (required). Returns: result
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelogβ¦
TDQS
Scored across 15 tools
Most tools are clearly distinct: snapshotting, rollback, safe file writes, safe bash, invariant checks, CTG, beliefs, and file operations all target unique actions. The only overlap is between get_status and session_summary, both providing session state, but at different detail levels (quick report vs comprehensive markdown), so agents can distinguish them with care.
All tools share the ketan_ prefix and use snake_case, with a dominant verb_noun pattern (get_status, list_files, write_file_safe). Minor deviations include one-word verbs (snapshot, rollback) and session_summary lacking a verb, but the pattern is predictable and readable overall.
With 15 tools, the server sits at the upper edge of the well-scoped range. Each tool earned its place in the workspace-protection workflow, though get_status and session_summary are slightly redundant, making the count marginally heavier than necessary.
The tool surface covers the full lifecycle: initialization, atomic snapshots, rollback, guarded mutations, invariant checks, causal tracing, failure explanation, and belief tracking. Minor gaps exist, such as no explicit checkpoint deletion or belief retraction, but these are workaroundable and do not block core workflows.
Maintenance
Related MCP Connectors
Persistent, inspectable memory for AI agents with lineage, correction, and a hosted MCP endpoint.
Context and control for any AI. Agent identity, scoped access, and proof across tools.
Provenance-carrying memory for AI agents: corrections supersede, never overwrite. Free, API + MCP.
MCP server for your apps' tools and custom tools, plus hosted AI agents and approval-gated workflows
Related MCP Servers
- AlicenseNot gradedqualityBmaintenanceLocal-first code intelligence and safety layer for AI coding agents. MCP server exposes dependency graph, impact analysis, and AST-compressed repo context, backed by typed local memory, patch-scope safety gates, and git-independent transaction rollback.1MIT
- AlicenseNot gradedqualityCmaintenanceProvides AI agents with a transparent proxy and journal for every tool action, including pre-state snapshots and approval gates for risky operations. Enables per-action undo, rewind to a point in time, and a kill switch that agents cannot override.6 npmBusiness Source 1.1
- AlicenseNot gradedqualityCmaintenanceEnables AI agents to operate through a local, signed boundary that blocks prompt injection and secret leakage, verifies outputs, preserves cross-session memory, and provides offline-verifiable receipts. It also exposes 900+ MCP tools for discoverable agent actions.7MIT
- FlicenseNot gradedqualityBmaintenanceEnables AI agents to execute real-world API actions with exactly-once reliability, deduplication, auditing, and human-in-the-loop safeguards via MCP.3-