Relace MCP Server
Неофициальный MCP-сервер Relace
Неофициальный — личный проект, не связанный с Relace.
Создан с помощью ИИ — разработан полностью при поддержке ИИ (Antigravity, Codex, Cursor, Github Copilot, Windsurf).
MCP-сервер, предоставляющий инструменты для редактирования кода с помощью ИИ и интеллектуального исследования кодовой базы.
Без него | С |
Ручной grep, пропуск связанных файлов | Естественный запрос, точное местоположение |
Правки ломают импорты в других местах | Отслеживание импортов и цепочек вызовов |
Полная переписка тратит токены | Описание изменений, без номеров строк |
Ошибки в номерах строк портят код | Слияние со скоростью 10 000+ токенов/сек |
Возможности
Fast Apply — применение правок кода со скоростью 10 000+ токенов/сек через API Relace
Agentic Search — агентское исследование кодовой базы с помощью запросов на естественном языке
Agentic Retrieval — гибридные семантические подсказки + исследование кода в реальном времени, с поддержкой устаревших подсказок и явным облачным обслуживанием (включите через
MCP_SEARCH_RETRIEVAL=1; выберите бэкенд черезMCP_RETRIEVAL_BACKEND)Cloud Search — семантический поиск по коду в облачных репозиториях
Related MCP server: code-context
Быстрый старт
Предварительные требования: uv, git, ripgrep (рекомендуется)
Используя бэкенд relace (по умолчанию): получите API-ключ в панели управления Relace, затем добавьте его в свой MCP-клиент:
~/.cursor/mcp.json
{
"mcpServers": {
"relace": {
"command": "uv",
"args": ["tool", "run", "relace-mcp"],
"env": {
"RELACE_API_KEY": "rlc-your-api-key",
"MCP_BASE_DIR": "/absolute/path/to/your/project"
}
}
}
}claude mcp add relace \
--env RELACE_API_KEY=rlc-your-api-key \
--env MCP_BASE_DIR=/absolute/path/to/your/project \
-- uv tool run relace-mcp~/.codeium/windsurf/mcp_config.json
{
"mcpServers": {
"relace": {
"command": "uv",
"args": ["tool", "run", "relace-mcp"],
"env": {
"RELACE_API_KEY": "rlc-your-api-key",
"MCP_BASE_DIR": "/absolute/path/to/your/project"
}
}
}
}.vscode/mcp.json
{
"mcp": {
"servers": {
"relace": {
"type": "stdio",
"command": "uv",
"args": ["tool", "run", "relace-mcp"],
"env": {
"RELACE_API_KEY": "rlc-your-api-key",
"MCP_BASE_DIR": "${workspaceFolder}"
}
}
}
}
}~/.codex/config.toml
[mcp_servers.relace]
command = "uv"
args = ["tool", "run", "relace-mcp"]
[mcp_servers.relace.env]
RELACE_API_KEY = "rlc-your-api-key"
MCP_BASE_DIR = "/absolute/path/to/your/project"Конфигурация
Переменная | Обязательно | Описание |
| ✅* | API-ключ из панели управления Relace; требуется для провайдеров Relace и облачных инструментов |
| ❌ | Установите |
| ❌ | Бэкенд семантического поиска: |
| ❌ | Политика подсказок поиска: |
| ❌ | Опциональный монитор периодического обновления локальных индексов; требует закрепленного |
| ❌ | Интервал монитора локального индекса в секундах (по умолчанию: |
| ❌ | Начальная задержка перед первой проверкой локального индекса в секундах (по умолчанию: |
| ❌ | Политика сообщений о статусе хода: |
| ❌ | Включить |
| ❌ | Включить поиск с поддержкой LSP: |
| ❌ | Переопределение корня проекта (автоматически определяется через MCP Roots → Git → хранилище рабочей области → CWD) |
| ❌ | Файловое логирование: |
| ❌ | Путь к файлу |
* Опционально, если оба условия верны: (1) APPLY_PROVIDER и SEARCH_PROVIDER не являются провайдерами Relace, и (2) MCP_RETRIEVAL_BACKEND имеет значение codanna, chunkhound или none.
Информацию об использовании .env, настройках кодировки, пользовательских LLM-провайдерах и многом другом см. в docs/advanced.md.
Инструменты
Всегда доступны: fast_apply, agentic_search. agentic_retrieval требует MCP_SEARCH_RETRIEVAL=1. Облачные инструменты доступны только при MCP_RETRIEVAL_BACKEND=relace. index_status доступен для relace, codanna и chunkhound, и скрыт, если MCP_RETRIEVAL_BACKEND=none.
Используйте встроенные механизмы обнаружения MCP: list_tools() для инструментов и list_resources() для ресурсов.
Подробные параметры см. в docs/tools.md.
Поддержка языков
Инструменты LSP используют внешние языковые серверы, установленные в вашей системе.
Язык | Языковой сервер | Команда установки |
Python | basedpyright | (в комплекте) |
TypeScript/JS | typescript-language-server |
|
Go | gopls |
|
Rust | rust-analyzer |
|
Панель управления
Терминальный интерфейс в реальном времени для мониторинга операций.
pip install relace-mcp[tools]
relogsПодробное использование см. в docs/dashboard.md.
Бенчмарк
Оцените производительность agentic_search с помощью набора данных для локализации кода Loc-Bench.
git clone https://github.com/possible055/relace-mcp.git
cd relace-mcp
uv sync --extra benchmark
# Build dataset from Hugging Face
uv run --extra benchmark python -m benchmark.cli.build_locbench --output artifacts/data/raw/locbench_v1.jsonl
# Run evaluation
uv run --extra benchmark python -m benchmark.cli.run --dataset artifacts/data/raw/locbench_v1.jsonl --limit 20Все артефакты бенчмарка записываются в benchmark/.data/.
Информацию о сеточном поиске, инструментах анализа и интерпретации метрик см. в docs/benchmark.md.
Поддержка платформ
Платформа | Статус | Примечания |
Linux | ✅ Полная поддержка | Основная платформа разработки |
macOS | ✅ Полная поддержка | Все функции доступны |
Windows | ⚠️ Частичная | Инструмент |
Устранение неполадок
Ошибка или сообщение | Решение |
| Установите |
| Добавьте 1-3 уникальные опорные строки рядом с целевым блоком |
| Убедитесь, что путь существует и находится внутри |
| Файл превышает 10 МБ; разбейте изменения на меньшие файлы или правки |
| Явно установите |
| Проверьте API-ключ и конфигурацию провайдера |
| Повторите попытку позже или уменьшите объем запросов |
| Проверьте сетевое подключение и повторите попытку |
| Добавьте более специфичные опорные строки или конкретные новые строки, чтобы слияние могло создать diff |
| Убедитесь, что маркеры-заполнители используются только как заполнители, а не как ожидаемый буквальный вывод |
| Разбейте крупные правки с большим количеством удалений или используйте явные директивы удаления |
| Разбейте изменение на более мелкие, локальные правки |
Разработка
git clone https://github.com/possible055/relace-mcp.git
cd relace-mcp
uv sync --extra dev --extra benchmark
uv run pytest
uv run --extra dev --extra benchmark pytest benchmark/tests -qЛицензия
MIT
Available Tools
7 toolsagentic_searchARead-onlyIdempotent
Search codebase for code locations matching a query.
Use when you know the name or structure you're looking for — function names, class names, modules, or how components connect. For conceptual/behavioral queries without known identifiers, use agentic_retrieval instead.
Returns file paths with line ranges and an explanation of findings. Keys: explanation (str), files (dict[path → {lines, snippet}]), turns_used (int).
Inputs: query (required). Returns: object
cloud_clearADestructive
Delete cloud repository and local sync state. IRREVERSIBLE.
Removes all indexed data from Relace Cloud. Use cloud_list to find repo IDs.
Inputs: confirm, repo_id. Returns: object
cloud_listARead-onlyIdempotent
[ADMIN] List all repositories in your Relace Cloud account.
Use to find repo_id for cloud_clear. Not needed for normal search/sync workflow. Returns repository IDs, names, and indexing status.
Inputs: no named parameters. Returns: object
cloud_searchARead-onlyIdempotent
Search for code by meaning using AI embeddings. Requires cloud_sync first.
Use for conceptual queries where you don't know the exact file, class, or function name. Prefer agentic_search when you know the exact identifier or symbol name.
Prerequisite: cloud_sync must have been run at least once. Fails if RELACE_API_KEY is not set or no sync state exists.
Returns: {results (list), result_count (int), warnings (list[str]), query (str), branch (str), repo_id (str)}. Check warnings[] for stale index alerts (e.g., uncommitted local changes).
Inputs: query (required), branch. Returns: object
cloud_syncAIdempotent
Upload or refresh codebase to Relace Cloud for semantic search.
Check index_status() first—skip this if cloud freshness is already 'fresh'. Syncs git-tracked files to enable cloud_search. Incremental by default.
Advanced (Relace-specific): force=True Re-upload all files; use after large refactors. force=True+mirror=True Delete cloud files absent locally; use after branch switch.
Returns: {sync_mode (str), files_created (int), files_updated (int), files_deleted (int), files_unchanged (int), warnings (list[str]), repo_id (str), repo_head (str)}. Check warnings[] for truncation or suppressed deletes. Fails if not in a git repo or RELACE_API_KEY is not set.
Inputs: force, mirror. Returns: object
fast_applyADestructive
Edit or create a file using intelligent merging.
For new files: writes content directly. For existing files: merges edit_snippet with current content using anchor lines. Anchor lines are verbatim lines copied from the existing file that help locate the exact edit target. Include 1-2 unique lines adjacent to the change. Truncation markers are recommended for larger scoped edits but not required. Markdown files keep fenced code blocks verbatim; outer fence stripping is skipped for .md/.mdx targets.
On error, the response includes a code field:
NEEDS_MORE_CONTEXT: merge model could not locate the target - add 1-2 unique anchor lines from immediately around the edit location.
APPLY_NOOP: merge returned an identical file even though the snippet contained explicit remove directives or concrete new lines not present in the original.
BLAST_RADIUS_EXCEEDED: edit scope too large - split into smaller edits.
MARKER_LEAKAGE: placeholder marker text leaked into merged output (treated as literal text).
TRUNCATION_DETECTED: merged output shrank drastically and no explicit remove directive was provided.
On success: {status: "ok", diff: str | None (unified diff, None for new files or no-op)}.
Do NOT use this tool to delete files or clear file contents. Use a dedicated file management tool for those operations.
Inputs: path (required), edit_snippet (required), instruction. Returns: object
index_statusARead-onlyIdempotent
Inspect the single active indexing backend in read-only mode.
Use this before retrieval when you need to know whether the active backend is fresh and
whether semantic hints are usable. Returns active_backend, a single backend status
object with freshness and hints_usable, and background_monitor (state, reason).
This tool never refreshes indexes; if active_backend is relace and
backend.status.needs_sync is true, run cloud_sync().
Inputs: no named parameters. Returns: trace_id, active_backend, base_dir, base_dir_source, +3 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 purpose with descriptions that explicitly differentiate similar tools (e.g., agentic_search vs cloud_search based on query type). There is no functional overlap.
Cloud operations use a consistent 'cloud_' prefix, but 'agentic_search', 'fast_apply', and 'index_status' break the pattern. Mix of verb_noun and adjective_noun styles reduces predictability.
Seven tools is well-scoped for a code search and editing server. Each tool addresses a specific need without redundancy or excessive complexity.
Covers search (local and cloud) and file editing, but lacks tools for reading full file content, deleting files, or managing local files beyond edits. Users may need to rely on external tools for basic operations.
Maintenance
Related MCP Connectors
Codebase intelligence for AI agents — dead code, blast radius, ownership.
Discover, compare, and monitor 1,400+ APIs directly from your AI coding agent.
Code intelligence for LLMs. Analyze, search, and retrieve code from any public git repository.
Code intelligence for coding agents: semantic, AST, graph, and full-text search. 279+ languages.
Related MCP Servers
- AlicenseNot gradedqualityFmaintenanceProvides AI-powered code intelligence for any codebase using local LLMs and vector search, enabling semantic code search, pattern analysis, and context-optimized code generation with 90% token savings.2MIT
- AlicenseNot gradedqualityDmaintenanceEnables AI coding assistants to automatically scan, store, and query API endpoints from codebases, providing instant lookup and semantic search to reduce context switching and token consumption.1MIT
- AlicenseNot gradedqualityNot gradedmaintenanceMake any LLM a codebase expert instantly. Provides deep code intelligence through semantic search, architecture mapping, security analysis, and smart context that fits perfectly in token windows.MIT
- AlicenseNot gradedqualityCmaintenanceProvides structured, token-efficient code context for AI assistants by indexing codebases with AST-level analysis, supporting 17+ languages, enabling semantic search, call-site tracking, and PR attribution.70 PyPI52MIT