Skip to main content
Glama
nimelkot
by nimelkot

Astra — это локальный сервис кодовой аналитики для ИИ-агентов. Он разбирает файлы репозитория в структурный граф NetworkX и индексируемый локальный индекс фрагментов кода, с обогащением на уровне AST для корректных Python-файлов. Тот же движок доступен через CLI astra и официальный MCP Python SDK.

Архитектура

Знак созвездия представляет связи, которые Astra обнаруживает в кодовой базе. Его конвейер состоит из четырёх этапов: обнаружение файлов без их выполнения, построение структурного графа, индексация фрагментов кода и получение семантических совпадений с расширением графа.

Компонент

Роль

Выход

Парсер AST и текста

Читает объявления Python, docstring-и, символы и вызовы; индексирует другие читаемые файлы проекта как фрагменты уровня файла.

Фрагменты кода и ссылки

Структурный граф

Строит направленные связи NetworkX между модулями, объявлениями и вызывающими.

.astra_graph.json

Векторный индекс

Хранит искомые фрагменты локально, с опциональным ускорением Sentence Transformers и Chroma.

.astra_vectors/

Двойные интерфейсы

Делает один и тот же движок доступным для пользователей терминала и MCP-хостов.

astra и astra-mcp

Поверхность MCP предоставляет четыре инструмента: astra_index_repo, astra_semantic_search, astra_get_callers и astra_hybrid_context.

Related MCP server: codebase-mcp

Установка

Требуется Python 3.10+. Выберите один из этих путей установки.

Установка напрямую из GitHub

Это самый простой вариант для использования Astra. Он устанавливает команды astra и astra-mcp без размещения копии в текущей папке:

python -m pip install "git+https://github.com/nimelkot/astra.git"

Для изолированной установки из командной строки используйте pipx:

pipx install "git+https://github.com/nimelkot/astra.git"

Клонирование для разработки

Используйте этот вариант, если хотите редактировать Astra или запускать его тесты. Запустите редактируемую установку из корня клонированного репозитория — каталога, содержащего pyproject.toml:

git clone https://github.com/nimelkot/astra.git
cd astra
Get-ChildItem pyproject.toml
python -m venv .venv
.venv\Scripts\Activate.ps1
python -m pip install -e ".[dev]"

Если Get-ChildItem pyproject.toml не может найти файл, вы ещё не в корне репозитория Astra. Папка, которую вы хотите анализировать, может находиться где угодно; она не обязана быть внутри копии Astra.

Быстрый старт

Сначала проиндексируйте проект. Замените пример пути на папку, которую Astra должна анализировать:

astra index C:\Users\YourName\Downloads\my-project

Команда рекурсивно сканирует вложенные папки на предмет файлов, не импортируя и не выполняя их. Корректные Python-файлы получают объявления и связи вызовов на уровне AST; другие читаемые исходные, конфигурационные, разметочные и документационные файлы получают искомые фрагменты уровня файлов. Бинарные файлы, неподдерживаемые кодировки, файлы размером более 2 МБ, а также сгенерированные или зависимые каталоги, такие как .git, .venv, node_modules и .astra_vectors, пропускаются.

Полную матрицу поддержки см. в docs/supported-file-types.md.

my-project/
├── .astra_graph.json   # structural modules, declarations, and call relationships
└── .astra_vectors/     # local searchable code chunks

Запустите astra index снова после изменения исходного кода. Индексация заменяет предыдущий граф и индекс фрагментов для этого целевого каталога.

CLI

Семантический поиск

Поиск по концепции, поведению, имени символа или тексту docstring:

astra search "authentication token validation" --path C:\Users\YourName\Downloads\my-project --limit 8

Таблица результатов показывает оценку совпадения, вид объявления, путь к файлу, символ и строки исходного кода. Результаты поиска пусты, когда ни один индексированный фрагмент не разделяет термины с запросом.

Структурные вызывающие

Найти функции, которые вызывают целевую функцию:

astra query callers calculate_total --path C:\Users\YourName\Downloads\my-project

Запрос callers использует сохранённый AST-граф и сообщает о совпадающих узлах-вызывающих в формате JSON. Текущий тип структурного запроса CLI — callers.

Поведение поиска

Индекс по умолчанию детерминирован и работает офлайн с использованием локального лексического сопоставления. Чтобы включить Sentence Transformers и векторный поиск Chroma, установите это перед индексацией и поиском:

$env:ASTRA_ENABLE_EMBEDDINGS = "1"
astra index C:\Users\YourName\Downloads\my-project
astra search "rate limiting and retries" --path C:\Users\YourName\Downloads\my-project

Первый запуск с включёнными эмбеддингами может загрузить модель all-MiniLM-L6-v2. Если доступ к модели или векторному хранилищу недоступен, Astra возвращается к локальной реализации поиска.

Визуализация индекса

После индексации создайте локальный HTML-отчёт для целевой папки:

astra visualize C:\Users\YourName\Downloads\my-project

Это записывает .astra_visualization.html в целевую папку. Откройте этот файл в браузере, чтобы просмотреть два представления:

  • Структурный граф: интерактивные модули, классы, функции, методы и рёбра определений/вызовов из .astra_graph.json.

  • Векторные фрагменты: искомые карточки файлов и символов из .astra_vectors/chunks.json с раскрывающимися предпросмотрами исходного кода.

Вы можете выбрать другой путь вывода:

astra visualize C:\Users\YourName\Downloads\my-project --output C:\Users\YourName\Desktop\astra-report.html

Отчёт использует библиотеку браузера Vis Network из её CDN для структурного холста. Векторное представление и сгенерированные данные остаются локальными; интернет-соединение требуется только для загрузки интерактивной библиотеки графов при открытии отчёта.

Примеры визуализации

Представление структурного графа отображает связанные модули, объявления и связи по всему индексированному проекту:

Представление векторных фрагментов предоставляет искомые карточки с путями к файлам, символами, диапазонами строк и расширяемыми предпросмотрами исходного кода:

MCP

Astra также предоставляет свой движок как официальный MCP-сервер через stdio. Настройте ваш MCP-хост на запуск astra-mcp; сервер должен быть установлен в среде, используемой этим хостом.

Четыре нативных инструмента:

Инструмент

Назначение

astra_index_repo(path)

Индексирует локальный репозиторий.

astra_semantic_search(path, query, limit)

Ищет по индексированным фрагментам кода.

astra_get_callers(path, target, limit)

Находит вызывающих через структурный граф.

astra_hybrid_context(path, query, limit, expansion)

Объединяет семантические совпадения с расширением графа.

astra_visualize(path, output)

Создаёт локальный HTML-отчёт графа и возвращает его путь и URL.

Репозиторий включает .vscode/mcp.json для MCP-клиентов VS Code. Для других хостов зарегистрируйте сервер в конфигурации хоста:

[mcp_servers.astra]
command = "astra-mcp"
args = []

Если хост не может найти команды из вашей оболочки, используйте абсолютный путь к исполняемому файлу: .venv\Scripts\astra-mcp.exe на Windows или .venv/bin/astra-mcp на macOS/Linux. Сервер общается через stdio, поэтому не перенаправляйте его stdout.

Разработка

pytest
ruff check .

Astra никогда не импортирует и не выполняет файлы, которые индексирует. Ошибки разбора пропускаются и сообщаются только через итоговые счётчики, что сохраняет индексацию полезной для частично сломанных рабочих деревьев.

Available Tools

5 tools
astra_get_callersB

Find exact callers of a function or method using the structural graph.

ParametersJSON Schema
NameRequiredDescriptionDefault
pathYes
limitNo
targetYes

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

B3.3/5.0
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, the description carries the full burden. It discloses the structural-graph mechanism and implies a read-only lookup, but it does not mention prerequisites such as an indexed repository, whether callers are direct or indirect, limits on traversal, or error behavior. This is too little transparency for an unannotated tool.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

A single sentence with no filler. 'Exact' and 'structural graph' are meaningful qualifiers, and the core purpose is front-loaded. Every word earns its place.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Even though an output schema exists, this unannotated tool has three undocumented parameters and no usage guidance. The description does not explain how to construct path/target values, whether the repo must be indexed first, or how result limits behave. An agent would need to guess important invocation details.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters2/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, so the description must compensate. It only hints that 'target' refers to a function or method; it does not explain what 'path' means, how 'limit' applies, or the expected format of 'target'. The description fails to close the parameter documentation gap.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description uses a specific verb ('Find') and names the resource ('exact callers of a function or method') plus the mechanism ('structural graph'). The qualifiers 'exact' and 'structural' help differentiate it from semantic-search siblings, so an agent can tell what the tool does.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The phrase 'exact callers' implies a precise, structural query rather than a semantic one, giving some context for when to use it. However, the description never explicitly names alternatives like astra_semantic_search or states when not to use this tool.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

astra_hybrid_contextC

Combine semantic matches with structural expansion.

ParametersJSON Schema
NameRequiredDescriptionDefault
pathYes
limitNo
queryYes
expansionNo

TDQS

C2/5.0
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description must carry the full behavioral burden. It does not disclose whether the operation reads or writes, whether it is safe to call repeatedly, or any side effects. The phrase 'Combine semantic matches with structural expansion' is too abstract to convey behavioral implications.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness2/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single under-specified fragment rather than a properly sized explanation. It is not well-structured and does not front-load any practical information. While brief, the brevity sacrifices clarity, making it inadequate for an agent selecting the tool.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness1/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

With no output schema, no annotations, and a two-line description, the tool is critically incomplete. The agent lacks information on what the tool returns, how to construct the path/query, what limit and expansion control, and any usage constraints. This is insufficient for correct invocation.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters1/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The schema describes four parameters (path, query, limit, expansion) with 0% coverage from the description. The description does not explain any parameter's meaning, acceptable values, or how they interact, forcing the agent to guess from names alone. This is a severe gap.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose3/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description gives a general sense of the tool's role ('Combine semantic matches with structural expansion') but does not state a concrete verb+resource outcome or differentiate from siblings like astra_semantic_search and astra_get_callers. It implies a hybrid behavior but is ambiguous about what it actually produces.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

No guidance on when to use this tool versus relying on astra_semantic_search alone or astra_get_callers. No exclusions, prerequisites, or context that would help an agent decide between siblings. The description merely states the concept without any conditions for use.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

astra_index_repoC

Index a local Python code directory into Astra's graph and vector store.

ParametersJSON Schema
NameRequiredDescriptionDefault
pathYes

TDQS

C2.9/5.0
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are present, so the description carries the full burden of behavioral disclosure. It only states the action without disclosing whether the operation is destructive, requires permissions, is additive or overwriting, or what the return value or side effects are. This is a significant gap for a mutating tool.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, direct sentence with zero filler. It is appropriately concise and the primary action is stated immediately.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For an indexing operation with no annotations, no output schema, and an undocumented parameter, the description is critically incomplete. It does not explain prerequisites, the effect on an existing index, or the result of the operation. An agent cannot predict what happens on success or failure.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters1/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The schema provides no description for the sole parameter 'path' (0% coverage), and the tool description does not reference it at all. There is no indication of expected format (absolute vs relative, file vs directory), whether it must exist, or what constraints apply. The agent has no way to correctly populate the parameter.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description states a specific verb ('Index') and a specific resource ('local Python code directory'), and it is clearly distinct from the sibling tools which are query/visualization operations. The purpose is unambiguous and immediately understood.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

No guidance is provided on when to use this tool versus the alternatives. There is no mention that indexing is a prerequisite for search tools, nor any exclusions or conditions that would help an agent decide to call this instead of astra_semantic_search or astra_visualize.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

astra_visualizeC

Generate a local HTML visualization and return its path and file URL.

ParametersJSON Schema
NameRequiredDescriptionDefault
pathYes
outputNo

TDQS

C2.9/5.0
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, the description carries the full disclosure burden. It does reveal the key side effect: generating a local HTML file and returning its path/URL. However, it omits whether the file overwrites an existing output, whether it is temporary or persistent, and any resource or environment constraints.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single sentence that is front-loaded with the action and clearly states the return value. Every word contributes to understanding, with no filler or repetition.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

There is no output schema, so mentioning the returned path and file URL is useful. However, the required 'path' parameter is unexplained, the optional 'output' parameter is undefined, and there is no context about what should be visualized. A simple tool with two parameters still needs at least minimal input semantics to be invoked correctly.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters1/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, and the description does not explain the meaning of the required 'path' parameter or the optional 'output' parameter. The phrase 'return its path and file URL' refers to the result, not the input parameters, leaving the agent without enough information to construct a valid invocation.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description states a specific action and result: 'Generate a local HTML visualization and return its path and file URL.' It is clear about what the tool does. However, it does not differentiate from sibling tools by naming them or contrasting the visualization use case with indexing/searching.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

No guidance is provided about when to use this tool versus alternatives such as astra_index_repo or astra_semantic_search. There is no explicit condition, prerequisite, or exclusions. The intended context is only vaguely implied by the tool name.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

  1. 5 tool updatesv0.1.0
    • First observedastra_get_callers
    • First observedastra_hybrid_context
    • First observedastra_index_repo
    • First observedastra_semantic_search
    • First observedastra_visualize

TDQS

B3.2/5.0

Scored across 5 tools

Disambiguation5/5

Each tool has a distinct purpose: indexing a repo, semantic search, exact callers, hybrid context, and visualization. No two tools overlap in functionality; agents can easily select the right one.

Naming Consistency5/5

All tools follow a consistent 'astra_' prefix with verb_noun naming: index_repo, semantic_search, get_callers, hybrid_context, visualize. The pattern is uniform and predictable.

Tool Count5/5

Five tools is an ideal scope for a code indexing and querying server. Each tool serves a core workflow without unnecessary bloat or missing essential operations.

Completeness4/5

The set covers the main lifecycle: indexing, searching, structural queries, combined retrieval, and visualization. Minor gaps exist (e.g., no delete index or update) but they are not critical for the primary use case.

Maintenance

ActivitySlowing
ResponsivenessNo issues

Related MCP Connectors

Related MCP Servers

  • F
    license
    Not graded
    quality
    D
    maintenance
    Enables AI agents to semantically search and navigate code repositories using natural language, with support for multiple repos, incremental indexing, and no local install needed.
    -
  • A
    license
    Not graded
    quality
    D
    maintenance
    Enables LLM agents to efficiently understand and navigate a codebase by providing semantic search over symbols and a reference graph, replacing expensive grep/glob calls with structured tools like definition lookup, caller/callee queries, and change-impact analysis.
    18 PyPI
    3
    MIT
  • F
    license
    A
    quality
    C
    maintenance
    Provides codebase indexing and retrieval tools that give AI agents token-efficient, query-relevant context packages (symbols, imports, and dependencies) instead of scanning entire repositories.
    6
    -