knock

io.github.HasanGilani由 GitHub 帳號 HasanGilani 發布v0.2.0更新於 Nov 7, 2026

面向AI編碼代理的程式碼地圖與記憶:關鍵函式、行範圍、呼叫者、程式碼變更原因。

AI 翻譯由 AI 模型根據下方的原文描述翻譯,可能有誤。

原文描述

Code map and memory for AI coding agents: key functions, line ranges, callers, why code changed.

已驗證STDIO僅桌面開發者工具AI 與機器學習

概覽

knock 的本機 MCP 服務;無需登入;STDIO;8 個工具。

暫無 AI 概覽:以下資訊來自註冊中心條目和服務本身。

安裝

在 SourceWeft 中

  1. 開啟 儀表板中的 knock,將其新增到工作區。
  2. 為需要使用其工具的對話啟用該服務。

Desktop only,透過 STDIO。 STDIO 服務會啟動本機處理程序,因此需要 SourceWeft 桌面主機。

其他 MCP 客戶端

參照 儲存庫 中的啟動說明。

README

🚪 knock

Give your AI coding agent a memory of your codebase.

Stop paying your agent to re-read the same files every session. Knock first, then read only what matters.

[PyPI] [tests] [License: Apache-2.0] [Python 3.10+] [MCP server] [100% local] [No API key needed]

[Side by side: the same investigation in Saleor (4,776 files). Claude Code alone: a sub-agent makes 30 tool calls, 3 min 22 s of model time, $0.49. Claude Code with knock: 13 tool calls, 1 min 16 s, $0.25. Both answers correct.]

Two real Claude Code sessions on Saleor, abridged: each side's median-cost run out of three. Results vary between runs and repositories; on a small, well-known repo the difference was within noise. Full numbers: docs/benchmark.md.

📝 The story behind the numbers: I recorded 87 Claude Code sessions to find out where the money goes


🤔 The problem, in one table

Every new chat with a coding agent starts with amnesia. To answer "where is X?" or "how do we deploy?" it greps, opens big files, reads them... and next session it does it all over again.

😩 Without knock😎 With knock
First movegrep around, open whole files, or spawn a sub-agent to exploreone map call: the relevant code as a skeleton with exact line ranges
Text the agent reads~27,000–118,000 characters per question~4,300 characters per question
Finds "why did we do it this way?"only if it opens the right docdecisions and their rationale come back with the answer
Remembers yesterday's bug hunt❌✅ agents save findings with remember
Knows when its notes are outdated—✅ every answer says fresh or stale

Median characters per task on the held-out benchmark (targeted-grep and grep-and-read baselines vs knock). Fewer characters ≠ an identical cut in your bill; see the FAQ.

⚡ Getting started

You set knock up once, then you just keep using your AI agent as usual. The agent talks to knock in the background; you never have to run knock commands day to day.

1️⃣ Connect it to Claude Code (once per project)

From inside the project you work on:

bash
claude mcp add knock -- uvx knock-mcp serve --repo . --toolset map

This uses uv, which downloads and runs knock for you. No uv? Run pipx install knock-mcp (or pip install knock-mcp), then claude mcp add knock -- knock serve --repo . --toolset map.

--toolset map gives the agent three tools (map, open, remember) and is the setup measured in the results below. Leave it out to get the original eight tools.

That's the whole setup. The next time you open Claude Code in that project, knock reads the project and builds its notes automatically. This takes a few seconds for a small project and a minute or two for about 5,000 files; after that it only re-reads files that changed.

[!TIP] Add this line to your project's CLAUDE.md so the agent uses knock when it pays off: "Before exploring the repo (how/why questions, unclear bugs, changes across modules, code you can't find with one search), call knock's map tool with your task. For small edits you can locate with one grep, skip it. Save non-obvious findings with remember."

In our recordings, knock saved money on investigations in a large codebase but added a small cost to quick edits, so this line matters.

2️⃣ Work normally

Ask your agent what you'd always ask. Here's what changes behind the scenes:

You typeWhat the agent does
"Add rate limiting to the login endpoint"asks knock first and gets the login handler's file:line, your middleware conventions and the test setup, then opens only those lines
"Why do we use Postgres instead of Mongo?"gets the decision and its reasoning from your docs or ADRs, with a link to the source
"Tests fail with a Redis error, any idea?"finds the finding a previous session saved: "login tests need Redis running"
(after it figures something out)saves it with remember, so tomorrow's session already knows

Nothing to maintain: when code changes, knock updates its notes, and flags anything that may be outdated.

🖥️ Optional: use knock yourself from the terminal

You never need these, but they're handy.

CommandWhen you'd use it
knock map "where are expired checkouts cleaned up?"see the same code map your agent gets
knock open SomeClass.methodexact code for a symbol, with its callers and callees
knock context "how do we deploy?"ask a question yourself, e.g. when onboarding onto an unfamiliar repo
knock search "rate limit"look up what knock knows about a topic
knock statuscheck how fresh the notes are and how much knock knows
knock index .update the notes right now; your agent normally does this for you
knock index . --fullrebuild everything from scratch after a huge refactor
knock forget . --yesdelete everything knock stored about this project

Want knock to ignore some files? List them in a .knockignore file (same format as .gitignore).

👥 Setting it up for a whole team

Commit a .mcp.json file to your repo, and every teammate's Claude Code picks up knock automatically (each person needs knock installed):

json
{  "mcpServers": {    "knock": { "command": "knock", "args": ["serve", "--repo", ".", "--toolset", "map"] }  }}

Each person's notes live on their own machine. Sharing findings across a team isn't supported yet (see Status below).

🧠 How it works

mermaid
flowchart LR    A["📁 Your repo<br/>code · docs · configs · git log"] -->|"knock index<br/>(only changed files)"| B["🗂️ Notes<br/>each one points to<br/>file + lines + hash"]    B --> C[("💾 SQLite<br/>on your machine")]    C -->|"map"| D["🤖 Your agent"]    D -->|"open / Read<br/>(verify the real lines)"| A    D -->|"remember<br/>(save what it learned)"| C
  1. Index: knock reads your repo without running anything in it. It writes short notes: what each module defines, what the docs say about setup and deployment, which tools and dependencies you use, why decisions were made, and which recent commits fixed bugs.
  2. Ask: your agent asks a question and gets a small, ranked answer with file:line pointers, instead of reading whole files.
  3. Verify: before editing, the agent reads just the lines it needs. The original files are always the source of truth.
  4. Remember: the agent saves what it learned. If those files change later, knock marks the note stale so nobody trusts outdated info.

🧰 What your agent gets

With --toolset map (recommended):

ToolWhat it does
map🗺️Use when you'd otherwise explore. The code relevant to a task as a skeleton: signatures, exact line ranges, what each function uses and catches, who calls it; plus the history behind it and the docs that matter. For change requests, a lighter version with the exact range to read and existing code to copy.
open📄Exact, line-numbered code for a function or class with its callers and callees, a line range, or a file's skeleton
remember✍️Save a finding for future sessions; it's flagged automatically when the cited files change
The original 8-tool set (default without --toolset map)
ToolWhat it does
get_context🔎Start here when you'd otherwise explore. A ranked package for a task: notes, functions with file:line, files worth opening, related commits, and honest "nothing known about X" gaps
search_knowledge📚Search notes, filtered by category (architecture, decision, workflow, …) or folder
get_knowledge🧾One note with full provenance: where it came from, when, and whether it is still current
get_source📄Read real lines from a file, with secrets redacted. Only files knock indexed
record_knowledge✍️Save a finding; duplicates are merged, contradictions flagged
update_knowledge_status✅Mark a note verified, or wrong
get_repository_status🩺How fresh the index is, plus counts and stats
refresh_repository🔄Re-index changed files (takes milliseconds, no AI calls)
👀 See a real example session (8-tool set, Flask)

On Flask, an agent is told: "sessions signed with an old key in SECRET_KEY_FALLBACKS are rejected after rotating SECRET_KEY".

  1. get_context returns ~7.7 KB containing:
    • src/flask/sessions.py:317: SecureCookieSessionInterface.get_signing_serializer
    • tests/test_basic.py:374: test_session_secret_key_fallbacks
    • related commits fb54159861 secret key rotation: fix key list ordering and e13373f838 enable secret key rotation
    • the docs sections on sessions and secret keys
  2. get_source("src/flask/sessions.py", symbol="get_signing_serializer") returns the ~80 relevant lines, not the whole file.
  3. record_knowledge saves the finding:
    json
    {"category": "debugging", "content": "get_signing_serializer builds the key list as SECRET_KEY_FALLBACKS followed by SECRET_KEY; ordering was fixed in fb54159.", "sources": [{"path": "src/flask/sessions.py", "start_line": 317, "end_line": 335}]}
    The next session gets it instantly. If sessions.py changes, the note is flagged stale.

📊 Does it actually help?

Measured with a reproducible benchmark: 12 engineering tasks per repo, covering architecture, finding a feature, deployment, bug investigation, design rationale and following conventions.

Held-out repo (full-stack-fastapi-template; knock was never tuned on it):

ApproachFound the needed factsCharacters readTool calls
🐢 grep + read 3 files9 / 121,215,57072
🐇 targeted grep + read snippets7 / 12328,20660
🚪 knock10 / 1288,96217
More numbers, and the fine print
  • Flask (used during development, so optimistic): knock 12/12 with 92K chars, baselines 7/12 with 2.1M and 247K chars.
  • Speed: a ~200-file repo indexes in 0.3–0.6 s; re-indexing with no changes takes ~30 ms.
  • What this measures: whether the facts reached the agent, not whether the agent then solved the task. The baselines are simulations of agent behaviour.
  • In real Claude Code sessions (3 runs each), the result depends on the repository and the task:
    • Flask (small and well known): knock was break-even on a bug investigation and slightly more expensive on an easy edit, where its extra steps outweigh a single search.
    • Saleor (4,776 files, released days before the test), with the compact map toolset: on a multi-module investigation, knock cut the median cost from $0.49 to $0.29 and model time from 170 s to 78 s, and every knock run was cheaper. On a follow-up edit whose file one regex search found, knock cost more ($0.14 vs $0.08).
    • Latest version (adds edit mode and "skip knock for easy edits" guidance), over the full investigate-then-edit scenario: Saleor's median two-day cost fell from $0.70 to $0.43 (−39%). On Flask it was $0.31 vs $0.27, within run-to-run noise. Claude followed the guidance: it used knock for every investigation and skipped it for all the Flask edits.
    • Variance check (8 runs per side on the Saleor investigation): median cost $0.42 → $0.25 (−40%), 8/8 correct answers on both sides, and about half the spread. Without knock, Claude delegated to a sub-agent in 5 of 8 runs; with knock, in none.
    • The full story, including the versions that lost: I recorded 87 Claude Code sessions….
    • Details and caveats are in docs/benchmark.md.
  • Not yet measured: real billed tokens with a live model. The harness is ready (benchmarks/agent_bench.py) but costs API credits to run.
  • Where knock missed: wording mismatches ("linters" vs "lint") and module-level variables it doesn't index yet.

Full methodology: docs/benchmark.md.

🔒 Your code stays yours

  • 💻 Everything is local: one SQLite file in ~/.knock. No cloud, no telemetry, no network calls (a test enforces this).
  • 🙈 Secrets are skipped: .env files, keys and credentials are never indexed, and tokens or passwords inside code are redacted.
  • 🧱 Nothing is executed: knock never runs your scripts, hooks or tests. It only reads.
  • 🚧 Sandboxed reads: agents can only fetch files knock indexed, never ../../anything.

[!IMPORTANT] Whatever your agent retrieves through knock goes into the agent's context, just as if it had read the file itself. Exclude anything sensitive with a .knockignore file. Details: docs/security.md.

❓ FAQ

So it saves tokens?

That's the goal, and the benchmark shows far less text reaching the agent. But your bill also includes system prompts, reasoning, and output, and prompt caching already discounts repeated input. Expect the biggest wins on exploration-heavy questions ("how does X work?", "where is Y?", "how do we deploy?"), and little on pure code-writing. Faster answers and memory across sessions are wins either way.

Do I need an API key or a paid model?

No. Indexing and search are fully deterministic and local. The only thing that uses an API is the optional benchmark.

Which agents work with it?

Any agent that supports MCP over stdio. Verified: Claude Code (the session at the top of this page is a real recording of Claude using knock's tools) and the official MCP Python SDK client (all 8 tools, in the test suite). Cursor, Windsurf and others should work but are untested. Setup: docs/agents.md.

Which languages and files does it understand?

Python and JavaScript/TypeScript (including JSX, React components, Vue and Svelte scripts) get the full map: line ranges, what each function calls and uses, and who calls it. Go, Rust, Java, Kotlin, C#, Ruby, PHP, Swift, C/C++ and more get their functions, classes and types. It also reads Markdown and reStructuredText docs, ADRs, package.json, pyproject.toml, go.mod, Cargo.toml, Dockerfiles, Makefiles, GitHub Actions, linter configs and git history. Full list: docs/architecture.md.

What if the docs are wrong or outdated?

Every note is labelled with where it came from (extracted from docs, recorded by an agent, git history) and how fresh it is. Agents can mark a note as wrong, and it stays hidden until the source changes. The real file is always one get_source away.

How is this different from "RAG over my repo"?

No embeddings and no vector database. knock stores small structured facts that point back to exact lines, tracks when those lines change, and lets agents add what they learn. It's closer to a team wiki that maintains itself than to a search index.

🗺️ Status

knock is an early MVP (v0.1). What works today and what's next:

  • Incremental, resumable indexing that respects .gitignore and skips secrets
  • Structured knowledge with sources, freshness and lifecycle
  • MCP server with 8 tools, caching and local metrics
  • Reproducible benchmark with a held-out repo
  • Model-in-the-loop token and cost benchmark (harness ready)
  • Compact 3-tool "code map" (--toolset map), measured in real Claude Code sessions on Flask and Saleor
  • Measure on more large repositories, and on private codebases
  • Smarter matching for synonyms, and indexing module-level variables
  • Optional AI-assisted extraction (opt-in, disclosed)
  • Sharing knowledge across a team

🤝 Contributing

Issues and PRs are welcome. Start with CONTRIBUTING.md.

bash
.venv/bin/pip install -e '.[dev]' && .venv/bin/pytest

Deeper docs: Architecture · Security · Agents · Benchmark · Troubleshooting

📜 License

Apache-2.0

來源:README.md,提交 4d4d1dd

工具

8

get_context

Get task context

Use before exploring (how/why questions, unclear bugs, unfamiliar code); skip for small edits one grep can locate. Returns a compact, ranked context package for a natural-language task: relevant knowledge items (with source references, provenance and freshness), matching symbols with file:line, the files most worth opening, recent commits touching them, and explicit gaps where nothing is known. Bounded by max_chars. Does not rescan the repository or call any model.

輸入參數task必填pathsmax_charsrepository

search_knowledge

Search knowledge

Full-text search over stored knowledge items, ranked by relevance, source authority, verification and freshness. Filter by category and/or path prefix. Returns concise facts with source references; use get_knowledge for full provenance. Categories: architecture, decision, dependency, workflow, convention, implementation, debugging.

輸入參數limitquery必填max_charscategoriesrepositorypath_prefixinclude_inactive

get_knowledge

Get knowledge item

Fetch one knowledge item by id with full provenance: every source reference and whether it still matches the indexed file, lifecycle status and reason, verification, timestamps, revision, and links (supersedes/conflicts). Set include_evidence=true to also get the cited source excerpts.

輸入參數repositoryknowledge_id必填include_evidence

get_source

Get source excerpt

Read the current, authoritative contents of an indexed repository file (line-numbered, secrets redacted), by line range or by symbol name. Use it to verify knowledge before relying on it. Only files in the index are served: excluded, ignored, sensitive or out-of-repository paths are refused. Max ~200 lines per call.

輸入參數path必填symbolend_linerepositorystart_line

record_knowledge

Record knowledge

Persist one reusable, verified-by-you fact for future sessions: a debugging root cause and fix, a non-obvious workflow step, a decision and its rationale, a convention, or where something is implemented. One concise fact per call; cite the files (and lines) that support it so it is automatically marked stale when they change. Exact and near-duplicates are merged rather than stored twice; contradictions with existing items are reported. Do not record speculation, temporary state, or secrets. Stored as 'unverified'.

輸入參數titlecontent必填sourcescategory必填entitiesrationaleconfidencerepositorysupersedes

update_knowledge_status

Verify or invalidate knowledge

Change an item's lifecycle after checking it against the source: 'verify' (agent-recorded items only; marks it verified at the current indexed revision and clears staleness) or 'invalidate' (it is wrong or no longer applies; kept for history but excluded from results). Give a short reason.

輸入參數action必填reasonrepositoryknowledge_id必填

get_repository_status

Repository status

Report index freshness (indexed vs current Git revision, files modified since indexing, stale items, last run), knowledge counts by category/status/provenance, cache statistics and local usage counters.

輸入參數repository

refresh_repository

Refresh repository index

Incrementally re-index the repository: only added/modified/deleted files are reprocessed (deterministic, local, no model calls). Knowledge from changed sources is updated or invalidated, and agent-recorded items citing changed files are marked stale. Use full=true only if the index seems inconsistent.

輸入參數fullrepository

版本歷史

2
  1. v0.2.0最新Nov 3, 2026
  2. v0.1.1Nov 3, 2026

評分

已滿足適用檢查項的 90%

該評分衡量此收錄條目的完整程度,依據註冊中心條目、端點與公開來源計算得出。它不是對伺服器本身的評價,也不表示伺服器安全或目前可用:可連通性是帶日期的檢查結果,評分也不包含安裝量或使用者評價。

  • 近 30 天內可連通25 分
  • 已宣告認證方式10 分

    請在註冊中心條目中宣告憑證請求標頭,或保持端點能夠回應探測,以便判定其認證方式。

  • 已列出工具必需15 分
  • 描述必需15 分
  • 圖示10 分
  • 文件15 分
  • 授權條款10 分