Skip to content

mcp server

aakash-anko edited this page Jul 5, 2026 · 9 revisions

server.py (MCP)

The Codewalk MCP server — 42 tools for codebase onboarding, search, review, docs, voice, cloud sync, config generation, visualization, and human-in-the-loop fixes. Built on FastMCP.

Tool categories:

  • SETUP — analyze_codebase, generate_config
  • QUERY — search_codebase, get_module_info, explain_function, explain_class, lookup_symbol, get_overview, get_blast_radius_map, find_circular_dependencies, get_reading_order, get_execution_flow
  • ARCHITECTURE — get_architecture_health, call_chain
  • REVIEW — run_review, review_next_batch, submit_batch_findings, get_review_summary, review_file, get_review_details, get_stack_info, save_stack_context, finding_verdict, apply_accepted
  • MAINTENANCE — incremental_reindex, refresh_analysis, load_guidelines, run_static_analysis, run_tests
  • VOICE — voice_ask, speak
  • DOCS — index_docs, search_docs, ask_docs
  • HITL — approve_action, apply_fix, verify_fix
  • CLOUD — pull_index, index_status, connect_repo, check_version
  • VISUALIZATION — show_knowledge_graph

Key Concepts

Term Definition Example
MCP Model Context Protocol — standard for connecting AI models to external tools. Copilot calls codewalk_search_codebase("auth flow") via MCP.
FastMCP Python library for building MCP servers with @mcp.tool() decorators. mcp = FastMCP(name="codewalk") creates the server.
RAG Retrieval-Augmented Generation — retrieve code chunks, then answer. Search ChromaDB -> format context -> LLM generates answer.
blast radius All files affected if a file changes. config.py has blast radius of 15 files.
vertex A node in a graph (a file or module). pipeline.py is one vertex in the file graph.
edge A connection between two vertices (an import). pipeline.py -> scanner.py is an edge.
DAG Directed Acyclic Graph — no circular paths. A->B->C is a DAG. A->B->C->A is not.
betweenness centrality How often a vertex sits on shortest paths between others. config.py with betweenness=45.0 is a hub.
pagerank Ranks vertices by importance based on incoming links. utils.py with pagerank=0.12 is heavily depended on.
topological sort Order vertices so dependencies come first. C, B, A if A imports B and B imports C.
embedding Numerical vector representing text meaning. Code chunk -> [0.12, -0.45, ...] (768 numbers for jinaai/jina-code-embeddings-1.5b via Ollama/MPS).
vector store Database for fast similarity search on embeddings. ChromaDB finds the 5 most similar code chunks.
ChromaDB Open-source vector database used to store code chunk embeddings. collection.query(query_texts=["scan files"], n_results=5)
DuckDB Embedded SQL database storing file metadata and import edges. SELECT path FROM files WHERE language='python'
chunk A piece of source code stored as a search unit. def scan_directory(root): ... is one chunk.
igraph High-performance C library for graph analysis. ig.Graph.TupleList(edges, directed=True) builds a graph.
diff Changes between two code versions. - old\n+ new shows a replacement.
cosine distance Measures vector difference. 0.0 = identical, 1.0 = different. Distance 0.15 to scan_directory = very similar.
LLM Large Language Model for text generation. get_llm() returns ChatOpenAI.
STT Speech-to-Text — mic audio to text transcript. User speaks -> "What does scan_directory do?"
TTS Text-to-Speech — text to spoken audio. speak("The config module loads settings") plays audio.

Server Setup

mcp = FastMCP(name="codewalk", instructions="...")

Creates the MCP server with detailed routing instructions for Copilot. The instructions string teaches Copilot which tool to call for each type of question.


Global State

Variable Type Description
_pending_approval_token str | None Single-use token from the last codewalk_approve_action; required by codewalk_apply_fix.
batch_state.json file Per-session batch queue created by codewalk_run_review and advanced by codewalk_review_next_batch. Stored in .codewalk/review_session/<folder_name>/.

Every public tool is wrapped with _refresh_state_if_moved, which re-discovers the current working directory from codewalk.yaml and resets cached state if the workspace changes.


Tool 1: codewalk_analyze_codebase

Analyzes repo structure and indexes for search. Supports three modes:

mode Behavior
"auto" (default) Full build if no index; "INDEX READY" if complete; warning if index is behind (missing files).
"reindex" Smart re-index — only changed/new/deleted files. Use this to resume a partial index.
"full" Wipe existing index and re-embed everything from scratch.

analyze(auto) does not silently resume or reindex. It reads ChromaDB + manifest.json from disk, compares indexed files with files on disk, and reports status. If the index is behind, it tells you to run codewalk_incremental_reindex or codewalk_analyze_codebase(mode="reindex").

Index state is determined from ChromaDB + manifest.json on disk. graph.duckdb and the knowledge graph are rebuilt automatically whenever a build/reindex runs.

Example (first run)

@codewalk analyze this codebase

Return:

"Codebase analyzed and indexed successfully.\nFiles found: 120\nFiles indexed: 118\nChunks embedded: 412\nModules found: api, analysis, embeddings, ingestion, rag, review, mcp"

Return (subsequent run, unchanged)

"Codebase analyzed successfully.\nSearch index: INDEX READY — 412 chunks available.\n✅ Loaded existing index."

Return (index behind)

"⚠️ Indexing is behind from repo.\nFiles found: 120\nIndexed files: 75\nMissing files: 45\nRun `codewalk_incremental_reindex` or `codewalk_analyze_codebase(mode='reindex')` to sync."

Tool 2: codewalk_generate_config

Create a starter codewalk.yaml with stack-specific exclusions based on the detected tech stack. Run this before the first analyze if the repo does not have a config yet.

Example

@codewalk Generate a codewalk.yaml for this repo.
@codewalk Run codewalk_generate_config.

To overwrite an existing config:

@codewalk Regenerate codewalk.yaml from scratch.
@codewalk Run codewalk_generate_config with force=true.

Tool 3: codewalk_search_codebase

Single deterministic semantic search (no external LLM call in the tool). Returns raw chunks for the host LLM to analyze.

For every conceptual question, the host should call this tool 1-3 times with different phrasings and synthesize the merged chunks.

Example

Input: query = "how does authentication work?"

Return:

"--- src/auth.py | function: login (lines 10-25) ---\ndef login(user):...\n\n---\nConfidence: 0.65 | Retrieval good: True | Chunks: 3"

Multi-angle pattern

For broad questions, run parallel searches:

codewalk_search_codebase("how does authentication work")
codewalk_search_codebase("authentication login flow")
codewalk_search_codebase("verify user credentials")

Then synthesize the returned chunks into one answer.


Tool 4: codewalk_get_module_info

Returns module files, symbols, dependencies. Auto-resolves sub-folders as features.

Example

Input: module_name = "analysis"

Return

"## Module: analysis\nFiles: 6\nLanguages: python (6)\nDepends on: ingestion\nDepended on by: pipeline\n\n### Files & Symbols\n- blast_radius.py: `get_blast_radius` (function, L10-L45)..."

Tool 5: codewalk_explain_function

Looks up a function/class by name, returns source code + blast radius.


Tool 6: codewalk_explain_class

Looks up a class by name, returns source code + related symbols.


Tool 7: codewalk_lookup_symbol

Deterministic symbol lookup via the DuckDB knowledge graph + ChromaDB (no LLM). Finds symbols mentioned in the query and returns their chunks, optionally including caller or callee symbols.

Parameters

Param Type Default Purpose
query str (required) Symbol name or question containing a symbol
include_callers bool True Also return chunks for caller symbols
include_callees bool False Also return chunks for callee symbols

Tool 8: codewalk_get_overview

Returns tech stack, module list, dependency flow, top riskiest files.


Tool 9: codewalk_get_blast_radius_map

Shows change risk for files. Can target a module, file, or show the top riskiest files.


Tool 10: codewalk_find_circular_dependencies

Finds circular import dependencies in the indexed codebase. Returns strongly-connected cycle groups and suggested edges to break.


Tool 11: codewalk_get_reading_order

Returns all files in dependency order (read dependencies first).


Tool 12: codewalk_get_execution_flow

Module-to-module or file-to-file dependency flow.


Tool 13: codewalk_get_architecture_health

Returns graph stats, bottleneck files (betweenness), important files (PageRank), circular dependencies with suggested fixes.


Tool 14: codewalk_call_chain

Traces the shortest import chain between two files using igraph.

Example

Input: source="pipeline.py", target="config.py"

Return

"## Import Chain: pipeline.py → config.py\nHops: 1\nPath: pipeline.py → config.py"

Tool 15: codewalk_incremental_reindex

Re-indexes only changed files by comparing content hashes. Also resumes a partial/interrupted index and performs a full build when no local index exists.

  • Reads ChromaDB directly, so it works even if graph.duckdb or manifest.json are missing.
  • Adds, updates, and removes only changed chunks.
  • Fully rebuilds DuckDB and knowledge-graph.json from all Chroma chunks.
  • Re-indexes docs and guidelines.
  • Updates .codewalk/manifest.json with the current total chunk_count.

Tool 16: codewalk_refresh_analysis

Rebuilds dependency graph and module detection without re-embedding.


Tool 17: codewalk_run_review

Gathers the full review context (diff, changed files, Layer 0 risk annotations, blast-radius warnings, neighborhood callers/tests/interfaces, architecture flags, stack info, rubrics, and guidelines) and returns it to the host LLM. No LLM is called inside Codewalk; Copilot uses the returned context to write the review. For an API-generated review, use POST /review instead.

Parameters

Param Type Default Purpose
target_branch str | None None Diff against this branch
staged bool False Diff only staged changes
commit str | None None Review a specific commit by SHA or ref

Priority: commit > target_branch > staged > unstaged (default).


Tool 18: codewalk_review_next_batch

Get the next batch of files from an active batched review session. Call this after codewalk_submit_batch_findings until all batches are reviewed.

Parameters

Param Type Purpose
session_id str Session ID returned by codewalk_run_review

Tool 19: codewalk_submit_batch_findings

Save the host LLM's findings for the current batch to disk. Findings are appended to llm_findings.json in the session folder so context stays clean between batches.

Parameters

Param Type Purpose
session_id str Session ID returned by codewalk_run_review
findings list[dict] Finding dicts with file_path, line_number, severity, title, explanation, current_code, recommended_code, blocking

Tool 20: codewalk_get_review_summary

Combine Layer 0 deterministic findings and all submitted LLM findings into a structured Markdown summary after all batches are reviewed. The host LLM uses this to produce the final verdict.

Parameters

Param Type Purpose
session_id str Session ID returned by codewalk_run_review

Tool 21: codewalk_save_stack_context

Persist the project's detected tech stack to .codewalk/stack_context.json. Required before codewalk_run_review can proceed on a repo without an existing stack context. The file persists across all commits.

Parameters

Param Type Purpose
stack_json str JSON string with languages, frameworks, architecture, state_management, data_layer, testing, api_style

Tool 22: codewalk_get_review_details

Retrieve a persisted review context package by session_id. Use this after codewalk_run_review to inspect a previous review.

Parameters

Param Type Purpose
session_id str Session ID returned by codewalk_run_review

Tool 23: codewalk_review_file

Runs the full review pipeline (rubric loading, batched LLM review, deduplication, verification, verdict, summary) on a single file.

Parameters

Param Type Default Purpose
file_path str (required) Relative path to the file to review
target_branch str | None None Diff context branch
staged bool False Use staged diff context

Tool 24: codewalk_get_stack_info

Gathers deterministic stack signals for the current diff: changed files, imports, build/config files, and folder structure. Returns a markdown summary for the host LLM to interpret.


Tool 25: codewalk_load_guidelines

Loads team coding guidelines from a directory, embeds into a dedicated ChromaDB collection.


Tool 26: codewalk_finding_verdict

Record a user verdict (accepted/rejected) for a review finding. Use after codewalk_run_review or codewalk_review_file present findings.

Parameters

Param Type Purpose
session_id str Review session ID
finding_index int Index of the finding in the session
verdict str "accepted" or "rejected"
reason str Optional reason

Tool 27: codewalk_apply_accepted

Apply all accepted findings from a review session (findings where user_verdict="accepted" and recommended_code is present).

Parameters

Param Type Default Purpose
session_id str "" Session ID; uses the most recent session if empty

Tool 28: codewalk_approve_action

Presents a recommended action and asks the user to approve it before any edit is applied. Returns a single-use approval_token required by codewalk_apply_fix.

Parameters

Param Type Purpose
proposed_action str Human-readable description of the action

Tool 29: codewalk_apply_fix

Applies an approved fix to the codebase. Requires the approval_token from codewalk_approve_action.

Parameters

Param Type Default Purpose
file_path str (required) Relative file path
old_code str (required) Code to replace
new_code str (required) Replacement code
approval_token str (required) Token from codewalk_approve_action
session_id str | None None Optional session for finding lookup
finding_index int | None None Optional finding index for lookup

Tool 30: codewalk_verify_fix

Verifies the applied fix by running static analysis + tests and reporting the results.

Parameters

Param Type Default Purpose
file_paths list[str] | None None Files to verify; runs full suite if omitted

Tool 31: codewalk_run_static_analysis

Runs language-aware static analyzers (linters, type checkers, security scanners) on the given files. Detects the language from file extensions and runs the appropriate tools; missing tools are skipped gracefully.

Parameters

Param Type Purpose
file_paths list[str] Relative file paths to analyze

Tool 32: codewalk_run_tests

Runs the project's test suite with language-aware auto-detection (pytest, npm test, go test, cargo test, etc.).

Parameters

Param Type Default Purpose
file_paths list[str] | None None Optional changed files for language detection

Tool 33: codewalk_voice_ask

Records from mic, transcribes via local Whisper, returns transcript for Copilot to route to the right tool.

Example

@codewalk_voice_ask

Return

'Transcript: "What does scan_directory do?"\n\nRoute and respond:\n1. Pick the correct tool...\n2. Show the FULL tool result...\n3. Call codewalk_speak() with summary'

Tool 34: codewalk_speak

Speaks text aloud via TTS (edge-tts). Called after tool results to give a spoken summary.

Parameters

Param Type Purpose
text str Plain English text to speak

Tool 35: codewalk_index_docs

Indexes a folder of .md, .pdf, .txt documents into a separate ChromaDB docs collection for semantic search.

Example

Input: docs_path="/Users/me/team-docs"

Return

"Indexed 5 documents → 42 chunks. You can now use codewalk_search_docs or codewalk_ask_docs."

Tool 36: codewalk_search_docs

Semantic search across indexed documents. Returns raw chunks for browsing.

Example

Input: query="deployment process", n_results=5

Return

"## Doc Search Results\n\n### 1. deploy.md > Deploy Steps (distance: 0.12)\n..."

Tool 37: codewalk_ask_docs

Search + answer grounded in documents with citations.

Example

Input: question="How do we deploy to production?"

Return

"Based on the following document excerpts, answer...\n\n---\nSource: deploy.md > Steps\n..."

Tool 38: codewalk_pull_index

Pulls the latest cloud index for the current repo into the local workspace. Warns and requires force=True when the local .codewalk/manifest.json index_version is ahead of the cloud version.

Parameters

Param Type Default Purpose
force bool False Bypass local-ahead guard

Tool 39: codewalk_connect_repo

Connects the local workspace to a Codewalk Cloud repo and pulls its token/index. Warns and requires force=True when the local index version is ahead of cloud.


Tool 40: codewalk_index_status

Checks whether the current workspace is indexed and reports the local index_version and chunk_count from .codewalk/manifest.json.


Tool 41: codewalk_check_version

Reports the Codewalk server/API version and basic health.


Tool 42: codewalk_show_knowledge_graph

Starts the pre-built production Next.js frontend (npm start) and returns a URL to open the interactive knowledge graph in a browser. If the .next bundle is missing, the tool auto-builds it first.

Example

@codewalk Show me the knowledge graph.
@codewalk Open the knowledge graph for this repo.
@codewalk Run codewalk_show_knowledge_graph.

Cloud Admin UI

The web frontend includes a Cloud Admin page at /admin for registering repos, listing repos, triggering an index, copying access tokens, and checking server health/version.


Frontend Index Gate

Index-dependent tabs in the frontend KineticShell remain locked until GET /index-status reports indexed: true.


_TOOL_MAP

Dictionary mapping tool names to functions. Used by codewalk_voice_ask and backends.py for programmatic tool dispatch.

_TOOL_MAP = {
    "codewalk_analyze_codebase": codewalk_analyze_codebase,
    "codewalk_search_codebase": codewalk_search_codebase,
    ...  # all 42 public tools
}

Clone this wiki locally