convez.ai
MCP ServerDevOps & InfraestruturaIntermediário
ramushev

Direct Context

ramushev/direct-context

Converta repositórios em contexto agentic pesquisável via MCP

Ver no GitHub
InicialPluginScore · de 0 a 100

MCP server que transforma qualquer repositório em contexto pesquisável para agentes IA. Indexa documentação Markdown existente, gera mapas estruturais automaticamente e oferece busca por texto, BM25, semântica ou híbrida em múltiplos repositórios locais ou remotos.

Instalação

$npx convez-ai ramushev/direct-context

1 comando no terminal: detecta o formato do repositório (marketplace ou plugin avulso) e instala via Claude Code. Requer Node 18+ e o Claude Code instalado.

Métricas

Estrelas
4
Forks
0
Acompanhando
0
Saúde
42%
Último commit
há 5 meses
Versão
v2.0.0
Issues abertas
0
Contribuidores
1

Casos de uso

  • Integrar repositórios como contexto estruturado em agentes Claude
  • Buscar documentação e código através de múltiplos repositórios simultaneamente
  • Gerar documentação agentic otimizada para retrieval com prompts predefinidos

Veredito

Ferramenta robusta e bem pensada para transformar repositórios em contexto agentic de primeira classe. Suporta buscas avançadas, múltiplos repositórios e repositórios remotos — é uma peça essencial na infraestrutura de agentes que precisam navegar codebases complexas.

README

A tradução para o português deste README ainda está na fila.

Direct Context

An MCP server that turns any repository into searchable agent context.

Point it at any repo and it works immediately — direct-context serves each repo to agents over MCP: local checkouts live from their working tree, remote repos cloned into a local cache. It's two things in one package:

  1. An MCP server. Exposes one or more repos to agents via MCP tools (search_agent_docs, get_agent_doc, read_source_file, …) and prompts. For every repo it serves committed docs/agentic/ (when present), the repo's existing Markdown (README, docs/**, ADRs, …), and a programmatically synthesized structure map — combined — so any repo works out of the box.
  2. A doc-generation toolkit. A library of prompts (under prompts/) you run against a target repo to produce richer docs/agentic/ for sharper retrieval than source alone.

Features

  • Docs-agnostic — works on any repo: it ingests the repo's existing Markdown (README, docs/**, ADRs, design notes) as searchable docs and always adds a programmatically synthesized structure map (no AI), merged with any committed docs/agentic/. See Load docs.
  • Doc-generation toolkit — 18 prompts plus a one-shot orchestrator that produce richer per-repo docs/agentic/.
  • MCP server — stdio or HTTP, for any MCP client (Cursor, Claude Desktop, etc.).
  • Multi-repo — any number of local checkouts or GitHub / Bitbucket refs (SSH), indexed together for cross-repo navigation.
  • Four search engines — text, bm25, semantic, hybrid; chunk-level hits with line ranges and snippets. See Search engines.
  • Source-file reads — sandboxed read_source_file / list_source_dir / search_source_files to open the actual files behind the docs.

Quickstart

Step 1 — Install and build

pnpm install   # requires Node ≥ 20
pnpm build     # produces dist/index.js, the entry point your MCP client will spawn

Remote repos (GitHub / Bitbucket) are cloned over SSH — ssh-add your key first if you want to serve any.

Step 2 — Configure which repos to serve

cp context.example.json context.json

Edit context.json — a JSON array listing each repo by absolute path or remote ref:

[
  "/Users/me/code/my-repo",
  "owner/some-github-repo@main"
]

Step 3 — Load into the local cache

pnpm ctx:load   # writes .cache/ctx.yaml

Every repo works immediately — its existing Markdown and a synthesized structure map are served automatically, merged with any committed docs/agentic/. See Load docs.

Step 4 — Wire your MCP client and run

Add the server to your editor's MCP config (Cursor, Claude Desktop, etc.) — see Client configuration below for the exact snippet. For stdio clients (the common case) the editor spawns the server on demand, so there's nothing else to start; restart the editor (or its MCP connection) so direct-context picks up the cache.

You now have a working context server. Search, doc fetches, and source reads all work.

Local repos are served live and reflect working-tree edits automatically — no reload needed. Remote (git) repos load once at startup; after a later pnpm ctx:load for those, reload your client's MCP connection. For HTTP instead of stdio, see Run the server.

Usage

1. Generate agent docs

Optional — your repo's existing Markdown plus the synthesized structure map (§2) already serve usable context. Generating an docs/agentic/ folder upgrades a repo to structured, higher-signal context (architecture, modules, flows, APIs, business logic): AI-authored markdown capturing the flows, business logic, and design rationale the programmatic synthetic map can't, and that retrieves far better.

Recommended — the orchestrator. Open the target repo in an agentic editor that can spawn sub-agents and run prompts/initialize-docs.md. It discovers the repo's modules, flows, and APIs, auto-skips phases the repo has no signal for, writes a consolidated doc per phase (fanning out one sub-agent per data flow), then writes an AGENTS.md pointer and validates cross-doc links. See Architecture → Doc generation flow. Args:

ArgMeaning
EFFORTCost/quality tier: low | medium | high | max (default medium). Scales sub-agent model, fan-out breadth, and doc depth — not which phases run (that's decided by repo relevance, regardless of effort).
PARALLEL_SUBAGENTSCap on concurrent sub-agents in waves 4 & 5 (default 4).
SUBAGENT_MODELModel for wave-4 & wave-5 sub-agents. Default derives from EFFORT. Wave 1 stays on parent.

Manual — individual prompts. The orchestrator is built on 18 prompts under prompts/, each producing one doc and runnable on its own (partial coverage, re-runs, a missing doc). They cover understanding the system (00–06), the domain (07–12), and contributing (13–17). Each file declares its own inputs, output path, and any args (e.g. FLOW_NAME).

Commit the resulting docs/agentic/ and AGENTS.md to the target repo's VCS, then re-run pnpm ctx:load and reload your client (§2) to serve them — committing is how the docs persist and how the server picks them up on later loads.

2. Load docs

pnpm ctx:load clones or fetches each configured remote repo into .cache/repos/, builds its docs (committed docs/agentic/ if present + the repo's existing Markdown + a synthesized structure map), and writes a single merged manifest to .cache/ctx.yaml that the server reads at runtime — see Architecture → Loader flow. Local repos aren't copied or built by ctx:load at all — the server reads them live from their working tree (see Query loop). Remote repos are shallow-cloned or fetched over SSH, so auth relies on your local SSH agent. Sources come from context.json (gitignored; see context.example.json) by default, or from the file passed via pnpm ctx:load -- --config <file> (relative paths resolve against the package root). Repo names must be unique (the path/ref basename); collisions fail the load.

context.config.json is a flat JSON array; each entry is one of the following forms:

FormMeaning
/abs/path/to/checkoutLocal repo — served live from the working tree (synthesized on demand, never copied).
owner/repo / owner/repo@refGitHub via SSH (git@github.com:owner/repo.git).
github:owner/repo@refSame as above, explicit prefix.
git@github.com:owner/repo.git@refFull SSH URL, optional @ref suffix.
bitbucket:owner/repo@refBitbucket via SSH (git@bitbucket.org:owner/repo.git).
git@bitbucket.org:owner/repo.git@refFull SSH URL, optional @ref suffix.

The merged .cache/ctx.yaml lists every doc (id) for remote repos plus a source_roots: map the server auto-registers on startup. The top-level index doc — a table of every configured repo, its doc count, and whether it's cached (precomputed by ctx:load) or live (synthesized from its working tree) — is never written to .cache/: the server builds it fresh on every refresh, so it's always accurate even for an all-local config that never ran ctx:load.

Existing Markdown + synthesized structure (every repo). Every repo works out of the box — no LLM, no required folder. For each repo, up to three doc sources are produced and merged — by ctx:load for remote repos (into the cache), or live by the server for local repos (in memory, on each tool call):

  • Committed docs/agentic/ — loaded as-is when present (the curated/AI-authored set; see §1).
  • The repo's existing Markdown — every *.md/*.mdx outside docs/agentic/ (README, docs/**, CONTRIBUTING.md, ADRs, design notes, …) is surfaced as a first-class searchable doc, with frontmatter (id/title/tags) honored exactly like authored docs. Build/vendor dirs (via git ls-files) and low-signal noise (GitHub issue/PR templates, empty or oversized files) are skipped; each ingested doc carries the repo name as a tag.
  • A synthesized structure map — built programmatically from the repo's metadata and layout (file selection via git ls-files, skipping binary/oversized/lockfile entries), regenerated every load and written to the cache-only docs/synthesis/ folder (never into docs/agentic/, so a committed set is never clobbered). Each doc is named for what it holds so the map is always present at a stable id whether or not the repo has authored docs:
    • repo-summary — project metadata (name, version, description, dependencies, scripts, entry points) from every detected manifest, plus README excerpt + TOC and language stats.
    • file-map — directory tree, top-level areas, entry/key files.
    • code-map — one consolidated map of each area's files and regex-extracted exported symbols (TS/JS, Python, Go, Rust, Java/Kotlin, Ruby, C#, PHP, Swift, C/C++, Scala).
    • project-info — build/test/run commands, config, CI/deploy signals (when present).

These content-named ids never shadow the authored generation (overview, architecture, modules, …) — both coexist. Manifest metadata is read from each ecosystem's project file — package.json, composer.json, pyproject.toml (PEP 621 + Poetry), Cargo.toml, setup.cfg, setup.py, requirements.txt, go.mod, Gemfile/*.gemspec, build.gradle, pom.xml, *.csproj — so non-JS repos get a populated overview, not just a file count. Polyglot repos detect and merge every manifest found at the repo root.

Synthesized docs are tagged synthetic. Raw source files aren't indexed directly; agents reach them via the source-file tools (read_source_file, list_source_dir, search_source_files). The orchestrator (§1) is the upgrade path to richer, AI-authored docs/agentic/.

3. Run the server

# Dev — stdio (default; right for IDE clients)
pnpm dev

# Dev — HTTP on :3050
pnpm dev:http

# Production
pnpm build
node dist/index.js                              # stdio
node dist/index.js --transport http --port 3050 # HTTP

The server reads from .cache/ by default. Override with --docs <path> or AGENT_DOCS_DIR=<path>.

Client configuration

stdio (Cursor, Claude Desktop)

{
  "mcpServers": {
    "direct-context": {
      "command": "node",
      "args": [
        "/abs/path/to/direct-context/dist/index.js"
      ]
    }
  }
}

.cache/ is resolved relative to the package itself (not the client's working directory), so the client doesn't need a cwd. If you want to keep the cache elsewhere, pass --docs /abs/path or set AGENT_DOCS_DIR.

HTTP

Start the server (see §3 Run the server for the full command list), then point your client at it:

{
  "mcpServers": {
    "direct-context": {
      "url": "http://localhost:3050/"
    }
  }
}

Configuration reference

FlagEnv varDefaultNotes
--docsAGENT_DOCS_DIR.cacheExplicit docs/agentic directory override.
--engineCONTEXT_ENGINEhybridDefault search engine. One of text, bm25, semantic, hybrid. hybrid/semantic download a model on first query.
--transportCONTEXT_TRANSPORTstdioTransport. One of stdio, http.
--portCONTEXT_PORT3050Port for HTTP transport. Ignored when transport is stdio.
--source-rootAGENT_SOURCE_ROOTS(none)Source-code root the read_source_file tool may read from. Repeatable flag; env var is comma-separated.

MCP tools

ToolInputOutput
list_agent_docs(none){ count, docs: [{ id, title, tags, path }] }
get_agent_doc{ id }{ id, title, tags, path, frontmatter, body }
search_agent_docs{ query, k?, engine? }{ engine, query, hits: [{ id, title, score, snippet }] }
get_prompt{ id }{ id, description, body, args }
list_source_roots(none){ count, roots: [{ name }] }
read_source_file{ repo, path, max_bytes? }{ repo, path, bytes, truncated, content }
list_source_dir{ repo, path }{ repo, path, entries: [{ name, path, type }] }
search_source_files{ query, repo?, glob?, case_sensitive?, max_results?, max_file_bytes? }{ query, repo, count, truncated, matches: [{ repo, path, line, text }] }

The engine argument on search_agent_docs lets a single running server compare engines live — useful for picking the right default.

From docs to source files

Docs are plain Markdown — the server reads no special structure from them. The intended agent loop is: search_agent_docs → get_agent_doc for the full body → then open the source files the doc mentions with read_source_file({ repo, path }) (or locate more with search_source_files / list_source_dir). In multi-repo mode the repo is the source-root name, which matches the doc-id prefix. Docs produced by the doc-generation toolkit end each ## section with a **Sources:** line listing the repo-relative paths it was derived from — start there.

MCP prompts

Every *.md file under prompts/ (except README.md and _*-prefixed files) is registered as an MCP prompt. The MCP-protocol prompt name uses the file basename (without .md) with non-alphanumeric characters replaced by _ (e.g. 00-orientation.md → 00_orientation). The get_prompt tool uses the raw basename without that substitution (e.g. 00-orientation).

Each prompt's frontmatter declares args for any $VAR / ${VAR} tokens it references. These are passed through as documentation for the agent — the server does not perform variable substitution at the MCP protocol level. The agent interprets the tokens from the prompt text itself.

Search engines

All engines search chunks, not whole files: each doc is split into structure-aware slices (code on function/class boundaries, markdown on headings; long sections windowed with overlap). Hits therefore carry the parent doc id plus the matched startLine/endLine and a line-numbered snippet — so an agent can jump straight to the region with read_source_file. Chunking also keeps each unit near the embedding model's token window, so content deep in a large file stays retrievable.

EngineTechProsCons
textsubstring + tag/title boostzero deps, instant startup, predictableexact-match only, no stemming, no semantic recall
bm25minisearch (BM25, fuzzy, prefix) with a code-aware tokenizer that splits camelCase/snake_case identifiersstrong default for keyword-style queries; get user finds getUserById; no modelstill keyword-based
semantic@huggingface/transformers MiniLM-L6, in-processconceptual recall ("how do tokens get validated")first run downloads the model (cached under .transformers-cache); embeds all chunks at start
hybridReciprocal Rank Fusion of bm25 + semanticbest overall recall — combines exact-keyword and conceptual matchespulls in the semantic engine, so it carries the same model-download cost

The semantic and hybrid engines are initialized lazily on first query, so startup stays snappy if you never use them.

Architecture

Doc generation flow

The initialize-docs orchestrator runs inside an agentic editor opened on the target repo. It resolves each kept phase's spec once via get_prompt and embeds it in a shared context bundle, then fans out sub-agents — one per consolidated phase (e.g. modules.md, api.md), plus one per data flow — each of which writes its markdown file from the bundle and reports back. The EFFORT arg (low/medium/high/max) scales sub-agent model, fan-out breadth, and per-doc depth across this whole flow; it doesn't change which phases are kept — that's decided by repo relevance alone.

sequenceDiagram
    participant Dev as Developer
    participant Editor as Editor session<br/>(Claude Code / Cursor)
    participant Orch as Orchestrator<br/>(initialize-docs)
    participant Sub as Sub-agent
    participant Repo as Target repo

    Dev->>Editor: Run initialize-docs prompt
    Editor->>Orch: Execute orchestrator
    Orch->>Repo: Discover modules, flows, APIs
    Repo-->>Orch: Repo structure
    loop per doc — waves 1 → 4 → 5 (2 & 3 are orchestrator-only setup)
        Orch->>Sub: Spawn with prompt ID + args
        Sub->>Repo: Read source files
        Repo-->>Sub: Source content
        Sub->>Repo: Write docs/agentic/<id>.md
        Sub-->>Orch: Done
    end
    Orch->>Repo: Write AGENTS.md
    Orch->>Orch: Validate cross-doc links
    Dev->>Repo: git commit docs/agentic/

Loader flow

pnpm ctx:load reads the repo list from context.config.json. For each remote repo it clones/fetches into .cache/repos/, builds its docs (committed docs/agentic/ + the repo's existing Markdown + a synthesized structure map), and writes a single merged .cache/ctx.yaml that the server reads at runtime. Local repos aren't copied — they're just recorded as live source roots for the server (see Query loop).

sequenceDiagram
    participant Dev as Developer
    participant CLI as pnpm ctx:load
    participant Cfg as context.config.json
    participant Remote as GitHub / Bitbucket<br/>(SSH)
    participant Repos as .cache/repos/
    participant Cache as .cache/

    Dev->>CLI: pnpm ctx:load
    CLI->>Cfg: Read repo list
    Cfg-->>CLI: ["/path/to/repo-a", "owner/repo-b@main"]

    Note over CLI: repo-a is local — not copied,<br/>recorded as a live source root

    CLI->>Repos: Shallow clone (or fetch+reset) repo-b into .cache/repos/repo-b/
    Repos->>Remote: git clone / git fetch (SSH)
    Remote-->>Repos: Repo at ref
    CLI->>Repos: Build docs — git-tracked docs/agentic/ (if any) + repo Markdown + synthesized structure
    Repos-->>CLI: docs[] for repo-b

    CLI->>Cache: Write ctx.yaml (repo-b docs, source_roots)
    Note over Cache: index doc isn't written here —<br/>LiveStore builds it on every refresh

    CLI-->>Dev: ✓ 1 repo(s) loaded, repo-a served live, N total doc(s)

Query loop

At runtime, an agent typically searches docs, fetches a doc's body, then reads the source files it points at directly. The server resolves source paths against registered roots and rejects anything that escapes them. For local source roots, the server runs a cheap refresh before every doc/search tool call — if the working tree changed since the last call, that repo's docs are re-synthesized in memory and re-indexed, so local edits show up without re-running pnpm ctx:load.

sequenceDiagram
    participant Agent as Agent<br/>(Cursor / Claude)
    participant MCP as MCP server
    participant Live as LiveStore
    participant Reg as EngineRegistry
    participant Cache as .cache/
    participant Src as Source root<br/>(local checkout)

    Note over MCP: Startup
    MCP->>Cache: loadDocs() — read ctx.yaml + referenced *.md
    Cache-->>MCP: LoadedDocs (docs[], sourceRoots[])
    MCP->>Reg: setDocs(docs)

    Note over Agent,Src: Query loop — every doc/search call starts with a refresh
    Agent->>MCP: search_agent_docs { query, engine? }
    MCP->>Live: refresh()
    Live-->>MCP: current docs
    MCP->>Reg: search(query, engine)
    Reg-->>MCP: hits[{ id, score, snippet }]
    MCP-->>Agent: hits

    Agent->>MCP: get_agent_doc { id }
    MCP->>Live: refresh()
    Live-->>MCP: current docs
    MCP-->>Agent: doc body + frontmatter

    Agent->>MCP: read_source_file { repo, path }
    MCP->>Src: Read file (path validated within source root)
    Src-->>MCP: File content
    MCP-->>Agent: { content, bytes, truncated }

Doc format

The server is docs-agnostic: a doc is just plain Markdown. Folder names and file names carry no special meaning — drop any .md files under docs/agentic/ (subfolders are fine) and they're all loaded. No frontmatter is required or generated; id and title are inferred:

FieldInferred from
idPath relative to the docs root, .md stripped.
titleFirst # heading in the body. Falls back to id.
# Authentication

…

Optional YAML frontmatter can still override id/title for legacy docs; any other keys are parsed but ignored.

pnpm ctx:load writes a single merged .cache/ctx.yaml listing each doc's id and path — authors never write or edit this file by hand.

License

MIT — see LICENSE.

Ver o original no GitHub

Bom para

Relacionados