Terminal History MCP
Search and explore locally indexed shell history, rebuild the index, and inspect commands by directory, failures, and surrounding command chains.
Search all indexed shell commands with SQLite FTS5 keyword/prefix queries, newest first.
Reindex local zsh/bash history and the shell hook’s extended log; safe to run repeatedly.
List recent commands run in a specific working directory (requires the shell hook).
List recent failed commands by exit code with optional timestamp filtering (requires the hook).
Show time-ordered command chains around matches to reconstruct multi-step workflows.
Results include timestamp, command, shell, cwd, exit code, and duration when available, with secrets redacted at index time.
All exposed operations are local-only.
terminal-history-mcp
Search your shell history (zsh / bash / fish) from Claude Code, Cline, Cursor, Zed, or any MCP client. Local-only. SQLite FTS5. Secret-redacted before storage.

What you can ask
"When did I last ssh into the staging server?"
"Show recent failed commands."
"What did I run yesterday in
/etc/nginx?""What's that long docker compose flag I used 3 weeks ago?"
"Show command chains around
kubectl apply."
Related MCP server: ClaudeX
Install
npm install -g terminal-history-mcp
terminal-history-mcp index # one-time backfill from existing history(Or run from a clone: git clone … && npm install && npm run build && npm link.)
Wire to Claude Code
claude mcp add --scope user terminal-history -- terminal-history-mcp
claude mcp listWire to other MCP clients
Anywhere that takes a stdio MCP server config:
{
"mcpServers": {
"terminal-history": {
"command": "terminal-history-mcp"
}
}
}Connect via MCPize
Use this MCP server instantly with no local installation:
npx -y mcpize connect @HasanJahidul/terminal-history --client claudeOr connect at: https://mcpize.com/mcp/terminal-history
Capture cwd + exit code (recommended)
By default zsh/bash history files store only the command. To unlock recent_in_dir and failed_commands, install the shell hook:
terminal-history-mcp install-hook zsh # or bash, or fish
exec $SHELL # reloadThe hook appends pipe-delimited lines to ~/.terminal-history-mcp/extended.log. Reindex picks them up.
To inspect the snippet first:
terminal-history-mcp print-hook zshTo remove:
terminal-history-mcp uninstall-hook zshTools
Tool | What it does |
| FTS5 keyword + prefix match across all history. Optional |
| Last N commands in a working dir (needs hook) |
| Commands with non-zero exit (needs hook) |
| For each match, list commands within ±5 min |
| Re-parse history files + extended log |
| Build the vector index for semantic/hybrid search (needs an embedding endpoint) |
| Answer a question from your history, citing entries as |
Semantic search (optional, local)
Keyword search finds commands by the words in them. Semantic search finds them by meaning: "how did I free up docker disk space" finds docker system prune -af even though the query never says "prune". It uses embeddings from a model running on your machine. It is opt-in: search_history stays keyword-only unless you pass mode.
Set up Ollama
brew install ollama # or https://ollama.com/download
ollama serve # skip if the Ollama app is already running
ollama pull nomic-embed-text # embedding model (~274 MB)
ollama pull qwen2.5:7b # optional: chat model for ask_history answers (~4.7 GB)Then, after terminal-history-mcp index, call the reindex_embeddings tool from your MCP client. Each call embeds up to 2000 distinct commands (identical commands share one vector), newest first; call it again until remaining is 0, and again after new history is indexed.
Configuration
Env var | Default | Purpose |
|
| Any OpenAI-compatible endpoint (Ollama, LM Studio, llama.cpp server, vLLM, OpenAI) |
|
| Embedding model. Changing it re-embeds everything on the next |
| unset | Chat model for |
| unset | Sent as a Bearer token, for hosted endpoints |
| unset | Must be exactly |
Pass them through your MCP client, e.g.
claude mcp add --scope user terminal-history -e TERMINAL_HISTORY_CHAT_MODEL=qwen2.5:7b -- terminal-history-mcp{ "mcpServers": { "terminal-history": { "command": "terminal-history-mcp",
"env": { "TERMINAL_HISTORY_CHAT_MODEL": "qwen2.5:7b" } } } }Privacy
The endpoint defaults to localhost. Any other host is refused unless
TERMINAL_HISTORY_ALLOW_REMOTE_LLM=1.Only command text read from the local DB is embedded, i.e. after the secret scrubber ran at index time. Your search query or question is passed through the same scrubber before it is sent.
ask_historyalso sends the retrieved entries' timestamps, working directories and exit codes to the chat model.If you opt in to a remote endpoint, that redacted history leaves your machine. Redaction is pattern-based and can miss things.
Vectors live in the same local DB (
~/.terminal-history-mcp/history.db, tablecommand_embeddings).
Modes
| How it ranks | If embeddings are unavailable |
| FTS5 bm25, exactly the previous behaviour | n/a, never calls the endpoint |
| Cosine similarity between the query embedding and each command's embedding | Returns an error saying why |
| Top 50 keyword + top 50 semantic, fused with Reciprocal Rank Fusion (k=60); one row per distinct command | Falls back to keyword results and says so ( |
"Unavailable" means the endpoint is unreachable, reindex_embeddings has not run for the current model, or the guardrail refused the endpoint.
ask_history
ask_history(question, k=8) retrieves the top k entries with hybrid search and gives them to the chat model as delimited, untrusted data (never as instructions). The model is told to answer only from them and cite entries as [id:N], or reply exactly No relevant history found.. Cited ids are checked against what was retrieved; anything else is reported in invalid_citation_ids. Without TERMINAL_HISTORY_CHAT_MODEL it returns the retrieved entries only.
How well it works
Measured with npm run eval on a synthetic, author-written fixture (200 commands, 25 queries), nomic-embed-text via Ollama, Apple M4:
mode | recall@5 | MRR@10 |
keyword | 0.680 | 0.516 |
semantic | 0.680 | 0.587 |
hybrid | 0.720 | 0.583 |
Vector search is an exact brute-force scan: 23 ms median at 10k distinct commands, 237 ms at 100k. Numbers, caveats and design reasoning are in docs/adr/0001-semantic-search.md.
Privacy
Everything is local. The DB lives at ~/.terminal-history-mcp/history.db. Nothing is uploaded unless you point the optional semantic search at a non-localhost endpoint and opt in (see Semantic search → Privacy).
Secrets are scrubbed before insert. Detected patterns:
GitHub PATs (
ghp_*,gho_*, …)OpenAI keys (
sk-*)Slack tokens (
xox[baprs]-*)AWS access keys (
AKIA…)Authorization: Bearer/Basic <value>X-*-Token: …,X-*-Key: …,X-*-Secret: …headersEnv vars containing
TOKEN/KEY/SECRET/PASSWORD/API_KEYCLI flags
--token=…,--api-key …,-k …URL basic-auth
https://user:pass@hostJWTs (
eyJ.*.*)
If you find a leak, please open an issue. To wipe and re-index after upgrading patterns:
rm ~/.terminal-history-mcp/history.db*
terminal-history-mcp indexDevelopment
git clone https://github.com/hasanjahidul/terminal-history-mcp
cd terminal-history-mcp
npm install
npm run build
npm test # offline: unit + JSON-RPC e2e (fake embedding/chat endpoint on 127.0.0.1)
npm run eval # retrieval quality + vector-search latency; needs Ollama for the quality partLicense
MIT — see LICENSE.
Available Tools
7 toolsask_historyARead-onlyIdempotent
Read-only. Answers a natural-language question about your shell history, with citations (retrieval-augmented generation). Retrieves the top k entries with hybrid search, then, if TERMINAL_HISTORY_CHAT_MODEL is set, asks that chat model to answer only from those entries and cite them as [id:N]. Retrieved commands are passed as delimited untrusted data, never as instructions. Replies exactly "No relevant history found." when nothing retrieved is relevant. Without a chat model it returns the retrieved context only. Cited ids are checked against the retrieved set; any others are listed in invalid_citation_ids.
Inputs: question (required), k. Returns: note, answer, cited_ids, retrieved, +5 more
command_chainsARead-onlyIdempotent
Read-only. For each command matching query, returns the commands run within a time window around it (default ±5 min) — surfacing multi-step sequences like cd → npm run build → deploy. Useful for reconstructing "how did I do X last time?". Returns up to limit chains, each a time-ordered list of command rows. Local index only.
Inputs: query (required), limit, window_ms. Returns: count, chains
failed_commandsARead-onlyIdempotent
Read-only. Lists recent commands that exited non-zero — a quick "what just broke?" feed. Optionally restrict to commands after a given epoch-millisecond timestamp. Requires the shell hook for exit-code capture (legacy entries have no exit code). Newest first. Local index only.
Inputs: limit, since_ts_ms. Returns: count, results
recent_in_dirARead-onlyIdempotent
Read-only. Lists the most recent commands that were run with a given working directory — answers "what was I doing in this project?". Requires the shell hook to have been installed (legacy entries have no cwd and won't appear). Returns newest first with timestamps and exit codes. Local index only.
Inputs: cwd (required), limit. Returns: count, results
reindexAIdempotent
Re-parses the local shell history files (~/.zsh_history, ~/.bash_history) and the hook's extended log into the SQLite index. Idempotent — already-indexed commands are skipped by hash, so it is safe to call repeatedly. Run it after a burst of shell activity to make recent commands searchable. Reads only local files; writes only to ~/.terminal-history-mcp/. Takes no arguments. Returns counts of parsed / inserted / skipped entries.
Inputs: no named parameters. Returns: parsed, skipped, inserted, ext_applied, +1 more
reindex_embeddingsAIdempotent
Builds the vector index behind search_history semantic/hybrid modes and ask_history. Embeds distinct indexed command texts (identical commands share one vector) that have no vector yet for the configured model, newest first, in batches of 64, via the OpenAI-compatible endpoint in TERMINAL_HISTORY_LLM_BASE_URL (default Ollama at http://localhost:11434/v1, model nomic-embed-text from TERMINAL_HISTORY_EMBED_MODEL). Non-localhost endpoints are refused unless TERMINAL_HISTORY_ALLOW_REMOTE_LLM=1. Sends only already-redacted text read from the local index. Changing the embedding model re-embeds everything for the new model. Run reindex first, then call until remaining is 0. Returns embedded / skipped / failed / remaining counts.
Inputs: limit. Returns: error, model, failed, skipped, +2 more
search_historyARead-onlyIdempotent
Read-only. Full-text search (SQLite FTS5, stemmed, Unicode-aware) over all indexed shell commands. Supports keyword and prefix queries — e.g. docker build, git reb*. Returns the most recent matches first, each with timestamp, shell, cwd, and exit code when available. Default keyword mode is local index only; nothing is sent anywhere. semantic and hybrid modes embed only the query through the configured OpenAI-compatible endpoint (localhost Ollama by default) and need reindex_embeddings to have run. If a query returns nothing you may need reindex first.
Inputs: query (required), mode, limit. Returns: mode, count, results, keyword_error, +2 more
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 7 tools
Each tool has a clearly distinct role: raw indexing, embedding indexing, keyword/semantic search, RAG-style Q&A, command-chain reconstruction, failure listing, and cwd-scoped recency listing. The two reindex tools are explicitly differentiated by their descriptions, and search_history vs. ask_history is cleanly separated as retrieval vs. natural-language answering.
Names are all snake_case and readable, but they mix verb_noun forms (search_history, ask_history), a bare verb (reindex), and noun/adjective phrases (command_chains, failed_commands, recent_in_dir). The pattern is not predictable from one tool to the next, though the names remain understandable.
Seven tools is well-scoped for a terminal-history server, covering indexing, search, semantic retrieval, and several targeted history views. Each tool has a clear reason to exist and none feels redundant or excessive.
The surface covers the core lifecycle: index raw history, build embeddings, search, ask questions, and inspect chains/failures/recent directory activity. Minor gaps exist, such as fetching a specific indexed command by id or managing/pruning the index, but these are not blocking for the stated purpose.
Maintenance
Related MCP Connectors
One searchable history across every AI coding tool, with secret scanning and a shared task board.
Search your AI chat history (ChatGPT, Claude, Codex) from any MCP client. Remote, private, read-only
Work on your own computers from Claude or ChatGPT: run commands, edit and search files.
Hosted MCP memory: save sessions/decisions once, search from Claude, Cursor, ChatGPT. EU-hosted FTS.
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceA powerful tool for exploring, searching, and managing your shell command history through the MCP (Model Control Protocol) interface. This project allows you to easily access, search, and retrieve your previously executed shell commands.2MIT
- AlicenseAqualityDmaintenancePersistent memory + FTS5 full-text search for Claude Code conversation history. Indexes ~/.claude/projects/ JSONL into SQLite, exposes 10 MCP tools (store/recall/search memories, browse sessions, get summaries) plus prompts. Includes a web UI for visual exploration10102 npm97MIT
- AlicenseAqualityDmaintenanceInspect, manage, and kill local dev servers via MCP. Stop guessing what's on :3000. Five tools: list servers with framework detection, inspect ports, find zombies, diagnose conflicts, safe-kill with dry-run default. Local, no cloud, no telemetry.521 npm4MIT
- AlicenseAqualityDmaintenanceSemantic git queries via MCP. Beyond git log — answer who/what/why about any line, file, or branch with blame, co-change, PR linkage.613 npm2MIT