Releases: Nefrols/NTS_MCP_FS
v1.7.4 — Java Development Suite, Sub-Tasks, Semantic Refactoring
Release v1.7.4 — Java Development Suite, Sub-Tasks, Semantic Refactoring
What's New
Java Development Suite
NTS now provides extended Java support beyond the general 12-language tree-sitter capabilities. Java gets dedicated high-level tools designed for maximum agent productivity with minimum cognitive load.
Profiler: High-Level API (nts_java_profiler)
Completely redesigned from 7-action lifecycle to 6 high-level actions:
- discover — List attachable JVMs with PIDs, names, Java versions
- profile — One call: attach → record → stop → parse → Markdown report
- trace — Method-level timing/tracing with methodFilter (JDK 25+)
- analyze — Re-analyze existing recording with different focus (saves tokens)
- compare — Delta report between two recordings (before/after)
- kill — Terminate a JVM process
Focus areas: cpu, cpu-time (JDK 25+), memory, contention, gc, io, or all.
Enhanced contention analysis:
- JavaMonitorEnter — lock blocking (synchronized)
- JavaMonitorWait — Object.wait() (notify-waiting)
- ThreadPark — LockSupport.park (j.u.c.)
- Contention call sites — where blocking actually occurs
- Most blocked threads — ranked by total blocked time
Smart hints: NIO servers with empty IO data get NIO-specific guidance. ZGC with minimal pauses gets a pauseless collector note with memory tool suggestions.
Memory Analyzer (nts_java_memory)
New dedicated tool for heap and allocation analysis:
- discover — List JVMs (independent from profiler)
- snapshot — Instant class histogram via
jcmd(milliseconds, no recording) - compare — Delta between two snapshots with auto leak verdict
- alloc — JFR allocation recording — top types by rate with call sites
Leak detection workflow: snapshot → exercise code → snapshot → compare. Growth in compare = potential leak candidates.
Gradle Build Integration (nts_gradle_task)
- Smart backend switching: gradlew → system gradle → auto-generate wrapper
- Project initialization:
task='init', initType='java-application' - Parsed output: compilation errors with
file:line, test results with pass/fail/skip - Async builds with
nts_processmonitoring
Extended Java AST
- Enum constants extracted as
CONSTANTsymbols in navigation - Constructor-aware rename — class rename automatically renames all constructors
- Overload disambiguation via structured AST parameter matching
- Symbol filtering:
symbols(kind='method', brief=true)for compact output
Sub-Tasks for Parallel Agents
nts_init now supports sub-tasks for multiple agents working on the same codebase:
- Parent calls
nts_init()→ receives parentTaskId - Sub-agent calls
nts_init(parentTaskId=...)→ isolated undo/redo stack - On success:
nts_init(action='merge')→ all edits become one grouped undo entry in parent - On failure:
nts_init(action='rollback')→ all edits reverted
Sub-tasks inherit workingDirectory/roots but have own tokens, TODO plans, and undo stack. CRC tokens prevent conflicts on same file regions.
Semantic Refactoring Overhaul
All 10 refactoring operations migrated to semantic resolution with SymbolHandle and ResolutionResult:
- Rename: Byte-span rewrite (UTF-8 safe), overload-aware matching, constructor auto-rename for class renames, field scope guard against unrelated parameters
- Extract Variable: Smart expression isolation from statements (variable declarations, return, if/while conditions, throw, yield)
- Inline: Local variable fallback via AST scan when standard resolver doesn't index method-local vars
- Delete: Default scope
projectwhenhandleReferences='comment'|'remove'(wasfile) - Wrap:
throw new RuntimeException(e)instead ofe.printStackTrace()when wrapping return statements - Generate:
options.overwrite=trueto regenerate existing equals/hashCode/toString/builder - Change Signature: AST-rewrite of declarations and all call sites with automatic overload disambiguation
13 bug fixes across refactoring operations, verified by automated audit.
Code Navigation Improvements
- Class vs constructor auto-resolution: References on Java classes no longer return "Ambiguous" error
- Symbol filtering:
kindparameter filters by symbol type (method, field, class, etc.) - Brief mode:
brief=trueoutputs name + line only — reduces output on large files by 70%+ - Strict mode:
strict=truerejects fallback cursor resolution for safe autonomous edits - Structured contract:
resolutionStatus,usedFallback,safeForAutonomousEdit,candidateCount
Schema & Hints Audit
Complete schema audit across all 21 tools:
- nts_edit_file:
operations[]/edits[]sub-schemas expanded with 4+ missing params each.pathno longer incorrectly required. - nts_code_refactor: +6 missing params (
codePattern,accessModifier,returnType,targetClass,position,continueOnError). FixedcatchType→exceptionType.whatenum completed. - nts_init: Added
descriptionparam for merge action - nts_file_read: Added
forceto bulk item schema - nts_git: Added
initto command description - nts_batch_tools: Removed unsupported
affectedFiles[0]interpolation from docs - ContextTool: Phantom
nts_worker_finishreference replaced with validnts_todo(action='close') - EditFileTool:
autoIndentpropagates from top-level tooperations[] - BatchToolsTool:
$LAST/$PREV_ENDwork afternts_file_manage(create)
Agent Context Memory (nts_context)
New tool for structured, task-scoped agent memory:
- HUD notes (
kind='hud_note') — always-visible reminders in every tool response - Context notes (
kind='note') — durable findings for recovery after compression - Snapshot recovery — full task picture in one call (TODO, files, journal, notes)
- CRUD API — add, read, update, delete, list
- Cross-tool integration — other tools nudge agent to save durable findings via TIPs
Infrastructure
- nts_context — structured task memory with HUD integration
- SymbolResolver — semantic resolution with SymbolHandle and ResolutionResult
- CodeNavigateTool — strict mode and structured confidence metadata
- PathSanitizer — symlink protection, dynamic roots, infrastructure file unblocking
- McpIntegrator — Codex CLI (TOML) and OpenCode support
- GradleTool/VerifyTool — structured build error diagnostics
- JsonUtils — shared ObjectMapper + NtsErrorCode structured errors
- TaskContext — sub-task API (createSubTask, mergeSubTask, rollbackSubTask)
- README — restructured (Quick Start at top, languages separated, Java Suite section)
Stats
- 20 commits, 125 files changed, +22,296 / -2,520 lines
- 33 new files (production + tests)
- 21 MCP tools (was 19): added
nts_java_memory,nts_context - 13 refactoring bug fixes, verified by automated audit
- Schema fixes across all 21 tools
Что нового (RU)
Комплект инструментов Java-разработки
NTS теперь предоставляет расширенную поддержку Java поверх общих возможностей tree-sitter для 12 языков. Java получает выделенные высокоуровневые инструменты, рассчитанные на максимальную продуктивность агента при минимальной когнитивной нагрузке.
Профайлер: высокоуровневый API (nts_java_profiler)
Полная переработка с 7-action lifecycle на 6 высокоуровневых действий:
- discover — Список подключаемых JVM с PID, именами, версиями Java
- profile — Один вызов: attach → запись → stop → парсинг → Markdown-отчёт
- trace — Трассировка методов с фильтром (JDK 25+)
- analyze — Повторный анализ записи с другим фокусом (экономия токенов)
- compare — Дельта-отчёт между двумя записями (до/после)
- kill — Завершение JVM-процесса
Области фокуса: cpu, cpu-time (JDK 25+), memory, contention, gc, io, all.
Усиленный contention-анализ:
- JavaMonitorEnter — блокировка на мониторах (synchronized)
- JavaMonitorWait — Object.wait() (ожидание notify)
- ThreadPark — LockSupport.park (j.u.c.)
- Call sites блокировок — конкретные места в стеке
- Самые блокируемые потоки — ранжирование по суммарному времени
Умные хинты: NIO-серверы с пустым IO получают NIO-подсказку. ZGC с минимальными паузами — подсказку о pauseless-коллекторе с рекомендациями memory-инструмента.
Анализатор памяти (nts_java_memory)
Новый инструмент для анализа кучи и аллокаций:
- discover — Список JVM (независим от профайлера)
- snapshot — Мгновенная гистограмма классов через
jcmd(миллисекунды, без записи) - compare — Дельта между снапшотами с автоматическим вердиктом утечки
- alloc — JFR-запись аллокаций — top типов по скорости с call sites
Workflow обнаружения утечек: snapshot → нагрузить код → snapshot → compare. Рост = кандидаты на утечку.
Gradle Build Integration (nts_gradle_task)
- Умное переключение бэкенда: gradlew → system gradle → автогенерация wrapper
- Инициализация проекта:
task='init', initType='java-application' - Парсинг вывода: ошибки компиляции с
file:line, результаты тестов с pass/fail/skip - Асинхронные сборки с мониторингом через
nts_process
Расширенный Java AST
- Enum constants извлекаются как символы
CONSTANTв навигации - Constructor-aware rename — переименование класса автоматически переименовывает конструкторы
- Disambiguация перегрузок через структурированные AST-параметры
- Фильтрация символов:
symbols(kind='method', brief=true)для компактного вывода
Под-задачи для параллельных агентов
`nts_in...
v1.5.1 — H2 & Verification Pipeline(breaking change!)
Release Notes
What's New
Session → Task: Concept Rename (Breaking API Change)
The entire API has been migrated from "session" to "task" terminology across 84 files:
| Before | After |
|---|---|
SessionContext |
TaskContext |
SessionTransactionManager |
TaskTransactionManager |
SessionLineAccessTracker |
TaskLineAccessTracker |
SessionSearchTracker |
TaskSearchTracker |
SessionTool (session package) |
TaskTool (task package) |
TaskTool (system package) |
ProcessTool (system package) |
nts_session |
nts_task |
sessionId |
taskId |
Why: "Task" better reflects the isolated unit of work with its own undo history, checkpoints, and token registry.
H2 Database Persistence
Transaction journal storage migrated from JSON files to embedded H2 database:
JournalDatabase— connection pool and schema managementJournalRepository— CRUD operations for journal entries- Survives server restarts with full transaction history
- Eliminates JSON serialization overhead and file corruption risks
SmartUndoEngine: In-Memory Snapshots
Undo engine migrated from file-based backups (Map<Path,Path>) to in-memory byte[] snapshots (Map<Path,byte[]>):
- Faster undo/redo operations (no disk I/O for snapshots)
- Reduced temporary file clutter
- File lineage tracking preserved for move/rename recovery
New Tool: nts_verify — Multi-Level Validation
Verification tool with three levels of code correctness checking:
| Action | Description |
|---|---|
syntax |
Fast tree-sitter AST check (no build needed) |
compile |
Run gradlew build -x test for compilation |
test |
Run gradlew test for full test validation |
Powered by SyntaxChecker — tree-sitter based AST parsing for instant syntax validation.
New Tool: nts_workspace_status — Context Recovery
Compact workspace summary for agent re-orientation after context compression:
- Current task ID and stats
- TODO progress (if active)
- Recently modified files
- Recent journal entries (last 5 operations)
- Suggested next action
New Tool: nts_process — Background Process Management
Monitor and control long-running background processes:
| Action | Description |
|---|---|
log |
Retrieve output from async process |
kill |
Terminate running process |
Works with nts_gradle_task and nts_git async operations.
EditFileTool: Auto Syntax Verification
After every edit, the tool automatically runs tree-sitter syntax check on the modified file. If syntax errors are detected, the response includes a warning with error details — agent catches mistakes immediately without a separate verification step.
LineAccessTracker: File CRC Token Invalidation
Tokens now track file CRC (fileCrc) in addition to range CRC:
registerAccess()requires mandatoryfileCrcparameter- External file changes invalidate tokens even if the edited range hasn't changed
- Per-symbol tokens in
CodeNavigateToolfor precise invalidation
EncodingUtils: ICU4J Multi-Level Detection
Encoding detection migrated from basic charset detection to ICU4J with multi-level strategy:
- BOM detection (UTF-8/16/32)
- ICU4J
CharsetDetectorwith confidence scoring - Fallback to system default
Handles CRLF normalization, Unicode BOM stripping, and charset-aware text comparison.
TodoTool Enhancements
- New actions:
itemsandall_itemsfor structured JSON responses - FOCUS hint — reminds agent of the current active task
- Verify reminder — prompts to verify after completing edits
- Role-aware suggestions — different tips for different agent roles
GradleTool: Project Initialization
initaction — generate Gradle wrapper for new projects- System Gradle fallback when wrapper not present
- Improved error messages with actionable suggestions
TipFilter: Role-Aware Filtering
Smart contextual tips now filtered based on agent role via ntsAllowedTools:
- Workers see execution-focused tips
- Architects see planning tips
- Scouts see exploration tips
API Consistency Improvements
isInternal()method onMcpTool— marks tools hidden from externaltools/listincludeInternalparameter inlistTools— allows orchestrator to see all toolsntsAllowedToolsmetadata — restricts which tools are visible per agent role- Lazy Root Refresh in
PathSanitizer— retries root resolution on access denial ObjectMapper→JsonMapper.builder()inMcpIntegrator
NtsErrorCode: Placeholder Interpolation
Error messages now support %placeholder% interpolation:
TOKEN_EXPIRED: "Token expired for %path%. File was modified externally."
Placeholders are resolved at error creation time with actual values.
Search Improvements
- BOM-aware text search — handles files with byte order marks
- CRLF-normalized comparison — consistent matching across line endings
- Unicode Boyer-Moore-Horspool — optimized for multi-byte characters
- Encoding-aware
containsText— correct matching regardless of file encoding
PathSanitizer: Lazy Root Refresh
When a path access is denied, the sanitizer now retries with refreshed roots before failing — handles cases where roots are updated after server startup.
FileReadTool: Directory Validation
executeRead and executeInfo now validate that the path is a file, not a directory, before attempting to read — prevents confusing error messages.
BatchToolsTool: Copy Path Fix
Fixed path resolution for copy action in nts_file_manage — the destination path is now correctly resolved in batch variable interpolation.
Documentation Updates
README.md
Both English and Russian sections updated:
- Tool count badge: 15 → 17
- Server name:
NTS-FileSystem→NTS-FileSystem-MCPin all config examples - New tools documented:
nts_verify,nts_workspace_status,nts_process - Refactoring operations: 6 → 10 (added Extract Variable, Wrap, Move, Delete, Batch)
- Client integrations: 7 clients (Gemini CLI, Claude Code, Qwen CLI, Cursor, LM Studio, Antigravity, Copilot VS Code)
- Session → Task terminology migration
- H2 Database persistence documentation
- In-memory snapshots for undo engine
MCP_LOG_FILEenvironment variable for Docker- Discipline loop diagrams updated with Verify and Workspace Status
Breaking Changes
API Migration: Session → Task
| Change | Impact |
|---|---|
sessionId → taskId |
All nts_init calls must use taskId parameter |
nts_session → nts_task |
Tool name changed |
SessionTool → TaskTool |
Package moved from session to task |
TaskTool (old, system) → ProcessTool |
Background process tool renamed to avoid collision |
Migration: Replace sessionId with taskId in all client configurations and API calls.
H2 Database Replaces JSON Journal
- Old
journal.jsonfiles are not auto-migrated - New tasks use H2 storage automatically
- Existing task directories with
journal.jsonwill start with clean journal state
Upgrade Notes
- Update client integrations to use
taskIdinstead ofsessionId - The server name in MCP configs is now
NTS-FileSystem-MCP - Old JSON journal files can be safely deleted after upgrading
- No changes to Docker configuration required
Stats
| Metric | Value |
|---|---|
| Commits in release | 19 |
| Files changed | 89 |
| Lines added | +7,148 |
| Lines removed | -3,007 |
| Net change | +4,141 |
Примечания к релизу (RU)
Новые возможности
Session → Task: Переименование концепции (Ломающее изменение API)
Весь API мигрирован с терминологии «сессия» на «задача» в 84 файлах:
| Было | Стало |
|---|---|
SessionContext |
TaskContext |
SessionTransactionManager |
TaskTransactionManager |
SessionLineAccessTracker |
TaskLineAccessTracker |
SessionSearchTracker |
TaskSearchTracker |
SessionTool (пакет session) |
TaskTool (пакет task) |
TaskTool (пакет system) |
ProcessTool (пакет system) |
nts_session |
nts_task |
sessionId |
taskId |
Зачем: «Задача» точнее отражает изолированную единицу работы с собственной историей undo, чекпоинтами и реестром токенов.
Персистентность на H2 Database
Хранилище журнала транзакций мигрировано с JSON-файлов на встроенную H2 базу данных:
JournalDatabase— пул соединений и управление схемойJournalRepository— CRUD-операции для записей журнала- Переживает перезапуски сервера с полной историей транзакций
- Устраняет накладные расходы JSON-сериализации и риски повреждения файлов
SmartUndoEngine: In-Memory снапшоты
Движок отката мигрирован с файловых бэкапов (Map<Path,Path>) на in-memory byte[] снапшоты (Map<Path,byte[]>):
- Быстрые операции undo/redo (без дискового I/O для снапшотов)
- Меньше временных файлов
- Отслеживание родословной файлов для восстановления после move/rename сохранено
Новый инструмент: nts_verify — Многоуровневая валидация
Инструмент верификации с тремя уровнями проверки корректности кода:
| Действие | Описание |
|---|---|
syntax |
Быстрая проверка AST через tree-sitter (без сборки) |
compile |
Запуск gradlew build -x test для проверки компиляции |
test |
Запуск gradlew test для полной проверки тестами |
Работает на основе SyntaxChecker — парсинг AST через tree-sitter для мгновенной валидации синтаксиса.
Новый инструмент: nts_workspace_status — Восстановление контекста
Компактная сводка рабочего пространства для переориентации агента после...
v1.2.2 — Transaction Journal Persistence & Smart TIPS
Release Notes
What's New
Transaction Journal Persistence
Undo/redo history is now persisted to disk in JSON format, ensuring no data loss on server restarts:
{
"version": 1,
"sessionId": "713a6834-c90a-4645-b441-f25f97a75457",
"counters": { "totalEdits": 5, "totalUndos": 2 },
"undoStack": [
{
"type": "TRANSACTION",
"timestamp": "2026-01-15T19:09:25",
"description": "Edit file: src/main/java/com/test/User.java",
"instruction": "Add @Entity annotation",
"status": "COMMITTED",
"snapshots": [{ "original": "src/main/java/com/test/User.java", "backup": "uuid.bak" }]
}
],
"redoStack": []
}Key improvements:
- Synchronous saving after every commit/undo/redo — fixes async thread race condition on JVM shutdown
- Relative paths for file references — portable across different machines
- Snapshot filenames only (
uuid.bak) — session directory implicit, no redundant paths
Automatic Session Reactivation
Sessions now automatically restore from disk when the server restarts:
// SessionContext.getOrCreate() now checks disk first:
if (existsOnDisk(sessionId)) {
ctx = new SessionContext(sessionId, meta.createdAt());
ctx.transactionManager.loadJournal(); // Restore undo/redo stacks
return ctx;
}Reactivation via nts_init:
{ "sessionId": "your-previous-uuid" }This restores:
- Full undo/redo history from
journal.json - Active TODO plan reference
- Session metadata (creation time, last activity)
Note: File access tokens start fresh (re-read files before editing).
Enhanced TodoTool
New actions for complete task management workflow:
| Action | Description |
|---|---|
create |
Start new plan with title and checklist |
read |
View current plan (alias: status) |
update |
Mark task done/failed or edit task text |
add |
Append new task to current plan |
close |
Archive completed plan (removes from HUD) |
list |
Show all plans (active and archived) |
reopen |
Reactivate an archived plan |
New task text editing:
{ "action": "update", "id": 3, "text": "Updated task description" }Synchronous Metadata Saving
Session metadata (session.meta) now saved synchronously, eliminating the saveMetadataAsync() virtual thread race condition.
Previous Release
LAT (Line Access Tracker) Improvements
Enhanced range overlap handling:
- Complex overlapping range cases now handled correctly
- Prevents CRC comparison errors in edge cases where multiple edits affect adjacent lines
Smart Tips for Tools
Added contextual tips to tool descriptions to guide LLM agents:
- Optimal workflow suggestions
- Common mistake prevention
- Best practices for tool chaining
Bug Fixes
Journal Not Restoring After Reactivation (Critical)
Problem: After server restart, nts_init(sessionId="...") returned empty undo/redo stacks despite journal.json existing on disk.
Root cause: SessionContext.getOrCreate() didn't check disk for existing sessions. After JVM restart, the in-memory sessions map is empty, so it created a NEW empty context instead of reactivating from disk.
Fix: getOrCreate() now calls existsOnDisk() and loadJournal() when session directory exists.
Async Save Race Condition (Critical)
Problem: journal.json sometimes not created despite successful edits.
Root cause: saveJournalAsync() used Thread.startVirtualThread() which didn't complete before JVM shutdown.
Fix: All journal saves are now synchronous. Same fix applied to saveMetadata().
Documentation Updates
README.md
Both English and Russian sections updated with:
- Session reactivation documentation
nts_init(sessionId="...")usage example- Explanation of what persists vs. what starts fresh
Breaking Changes
None. All changes are backward compatible.
Upgrade Notes
No action required. Existing sessions on disk will be automatically reactivated when accessed.
Примечания к релизу (RU)
Новые возможности
Персистентность журнала транзакций
История undo/redo теперь сохраняется на диск в формате JSON, гарантируя сохранность данных при перезапусках сервера:
{
"version": 1,
"sessionId": "713a6834-c90a-4645-b441-f25f97a75457",
"counters": { "totalEdits": 5, "totalUndos": 2 },
"undoStack": [
{
"type": "TRANSACTION",
"timestamp": "2026-01-15T19:09:25",
"description": "Edit file: src/main/java/com/test/User.java",
"instruction": "Добавление аннотации @Entity",
"status": "COMMITTED",
"snapshots": [{ "original": "src/main/java/com/test/User.java", "backup": "uuid.bak" }]
}
],
"redoStack": []
}Ключевые улучшения:
- Синхронное сохранение после каждого commit/undo/redo — исправляет гонку асинхронных потоков при завершении JVM
- Относительные пути для файлов — портируемость между машинами
- Только имена снапшотов (
uuid.bak) — директория сессии подразумевается, без избыточных путей
Автоматическая реактивация сессий
Сессии автоматически восстанавливаются с диска при перезапуске сервера:
// SessionContext.getOrCreate() теперь сначала проверяет диск:
if (existsOnDisk(sessionId)) {
ctx = new SessionContext(sessionId, meta.createdAt());
ctx.transactionManager.loadJournal(); // Восстановление стеков undo/redo
return ctx;
}Реактивация через nts_init:
{ "sessionId": "ваш-предыдущий-uuid" }Восстанавливается:
- Полная история undo/redo из
journal.json - Ссылка на активный TODO-план
- Метаданные сессии (время создания, последняя активность)
Примечание: Токены доступа к файлам начинаются с чистого листа (перечитайте файлы перед редактированием).
Расширенный TodoTool
Новые действия для полного цикла управления задачами:
| Действие | Описание |
|---|---|
create |
Создать план с заголовком и чек-листом |
read |
Просмотр текущего плана (алиас: status) |
update |
Отметить задачу выполненной/проваленной или изменить текст |
add |
Добавить новую задачу в текущий план |
close |
Архивировать завершённый план (убирает из HUD) |
list |
Показать все планы (активные и архивные) |
reopen |
Реактивировать архивный план |
Новое редактирование текста задачи:
{ "action": "update", "id": 3, "text": "Обновлённое описание задачи" }Синхронное сохранение метаданных
Метаданные сессии (session.meta) теперь сохраняются синхронно, устраняя гонку виртуальных потоков saveMetadataAsync().
Предыдущий релиз
Улучшения LAT (Line Access Tracker)
Улучшенная обработка перекрывающихся диапазонов:
- Сложные случаи перекрытия диапазонов теперь обрабатываются корректно
- Предотвращает ошибки сравнения CRC в краевых случаях, когда несколько правок затрагивают соседние строки
Smart Tips для инструментов
Добавлены контекстные подсказки в описания инструментов для направления LLM-агентов:
- Рекомендации по оптимальному workflow
- Предотвращение типичных ошибок
- Лучшие практики связывания инструментов
Исправления ошибок
Журнал не восстанавливается после реактивации (Критично)
Проблема: После перезапуска сервера nts_init(sessionId="...") возвращал пустые стеки undo/redo, хотя journal.json существовал на диске.
Причина: SessionContext.getOrCreate() не проверял диск на существование сессий. После перезапуска JVM in-memory карта sessions пуста, поэтому создавался НОВЫЙ пустой контекст вместо реактивации с диска.
Решение: getOrCreate() теперь вызывает existsOnDisk() и loadJournal() при наличии директории сессии.
Гонка асинхронного сохранения (Критично)
Проблема: journal.json иногда не создавался, несмотря на успешные правки.
Причина: saveJournalAsync() использовал Thread.startVirtualThread(), который не успевал завершиться до выхода JVM.
Решение: Все сохранения журнала теперь синхронные. Аналогичное исправление применено к saveMetadata().
Обновления документации
README.md
Обе версии (EN и RU) обновлены:
- Документация реактивации сессий
- Пример использования
nts_init(sessionId="...") - Объяснение что сохраняется vs. что начинается с чистого листа
Критические изменения
Нет. Все изменения обратно совместимы.
Примечания по обновлению
Действий не требуется. Существующие сессии на диске будут автоматически реактивированы при обращении.
v1.2.0 — AST Support
Release Notes
What's New
Batch Integration for nts_code_refactor
Refactoring operations now return access tokens for all modified files, enabling seamless chaining with other tools in nts_batch_tools:
{
"affectedFiles": [
{ "path": "src/User.java", "accessToken": "LAT:...", "crc32c": "A1B2C3D4", "lineCount": 50 },
{ "path": "src/UserService.java", "accessToken": "LAT:...", "crc32c": "E5F6G7H8", "lineCount": 120 }
],
"token": "LAT:..." // shortcut when single file affected
}Batch example:
{
"actions": [
{"id": "ref", "tool": "nts_code_refactor", "params": {"action": "rename", "path": "User.java", "symbol": "getName", "newName": "getFullName"}},
{"tool": "nts_edit_file", "params": {"path": "{{ref.affectedFiles[0].path}}", "accessToken": "{{ref.affectedFiles[0].accessToken}}", ...}}
]
}Path Aliasing for Token Persistence
Tokens now remain valid after move/rename operations through transitive path resolution:
A.java → B.java → C.java
↓
Token from A.java still valid for C.java!
This eliminates the need to re-read files after renaming them within or outside of batch transactions.
Change Signature Refactoring
New change_signature action for modifying method parameters with automatic call site updates:
{
"action": "change_signature",
"path": "UserService.java",
"symbol": "createUser",
"params": [
{"name": "email", "type": "String", "action": "add", "defaultValue": "null"},
{"name": "oldParam", "action": "remove"},
{"name": "name", "newName": "fullName", "action": "rename"},
{"name": "age", "type": "long", "action": "retype"}
]
}Symbol Extraction Architecture
Decomposed SymbolExtractor into 12 language-specific extractors:
- Java, Kotlin, Python, JavaScript/TypeScript/TSX
- Go, Rust, C/C++, C#, PHP, HTML
New utilities in SymbolExtractorUtils:
extractMethodParameters()- parameter extraction with varargs, defaults, annotationsextractMethodCalls()- call site analysis with argument positionsextractVariableReferences()- variable usage analysisextractMethodBody()- body extraction for inline/extract operations
SymbolIndex for Fast Lookup
New SymbolIndex class for project-wide symbol indexing:
- Incremental updates on file changes
- Cross-file symbol resolution
- O(1) definition lookup
Bug Fixes
CRC Mismatch in Batch Operations (Critical)
Problem: Tokens from nts_code_refactor failed validation in subsequent nts_edit_file calls with CRC mismatch errors.
Root cause: Inconsistent CRC calculation - FileReadTool/EditFileTool included line numbers in content, while refactoring used raw content.
Fix: Unified CRC calculation using raw content (without line numbers) across all tools.
Off-by-One Error in Single Line Delete
Problem: nts_edit_file delete operation failed when deleting a single line with error "endLine (6) must be >= startLine (7)".
Root cause: SessionLineAccessTracker.updateAfterEdit() calculated newEditEnd = editEnd + lineDelta, resulting in invalid range for single-line deletes.
Fix: Math.max(editStart, editEnd + lineDelta) ensures valid range.
Session Cache Synchronization
Problem: After refactoring, subsequent tools saw stale file metadata causing validation failures.
Fix: All refactoring operations now call SessionContext.externalChanges().updateSnapshot() after writing files.
Documentation & Schema Updates
Tool Descriptions for LLM
Updated getDescription() in tools to document new features:
- CodeRefactorTool:
CHANGE_SIGNATUREusage,BATCH INTEGRATIONwithaffectedFiles - FileManageTool: Path aliasing with transitive chain example
- BatchToolsTool:
REFACTOR INTEGRATIONsection with interpolation examples
Input Schema
Added params array schema for change_signature:
params[]: {name, type, newName, defaultValue, action: add|remove|rename|retype|reorder}
README.md
Both English and Russian sections updated with:
- Batch integration examples with JSON responses
- Path aliasing documentation
- Change signature operation description
Test Coverage
+20 new tests, +6000 lines
ChangeSignatureComprehensiveTest- 18 scenarios for all parameter modificationsLineAccessTokenPathAliasTest- path aliasing unit testsPathAliasIntegrationTest- move + token integrationParameterExtractionTest- AST-based parameter extractionSymbolIndexTest- symbol indexing- Reorganized test packages to mirror main code structure
Breaking Changes
None. All changes are backward compatible.
Upgrade Notes
No action required. Existing tokens remain valid. New features are opt-in.
Примечания к релизу (RU)
Новые возможности
Интеграция nts_code_refactor с batch-операциями
Операции рефакторинга теперь возвращают токены доступа для всех изменённых файлов, что позволяет бесшовно связывать их с другими инструментами в nts_batch_tools:
{
"affectedFiles": [
{ "path": "src/User.java", "accessToken": "LAT:...", "crc32c": "A1B2C3D4", "lineCount": 50 },
{ "path": "src/UserService.java", "accessToken": "LAT:...", "crc32c": "E5F6G7H8", "lineCount": 120 }
],
"token": "LAT:..." // сокращение при изменении одного файла
}Пример batch-цепочки:
{
"actions": [
{"id": "ref", "tool": "nts_code_refactor", "params": {"action": "rename", "path": "User.java", "symbol": "getName", "newName": "getFullName"}},
{"tool": "nts_edit_file", "params": {"path": "{{ref.affectedFiles[0].path}}", "accessToken": "{{ref.affectedFiles[0].accessToken}}", ...}}
]
}Алиасинг путей для сохранения токенов
Токены остаются валидными после операций move/rename благодаря транзитивному разрешению путей:
A.java → B.java → C.java
↓
Токен от A.java работает для C.java!
Это устраняет необходимость повторного чтения файлов после их переименования.
Рефакторинг Change Signature
Новая операция change_signature для изменения параметров методов с автоматическим обновлением всех мест вызова:
{
"action": "change_signature",
"path": "UserService.java",
"symbol": "createUser",
"params": [
{"name": "email", "type": "String", "action": "add", "defaultValue": "null"},
{"name": "oldParam", "action": "remove"},
{"name": "name", "newName": "fullName", "action": "rename"},
{"name": "age", "type": "long", "action": "retype"}
]
}Архитектура извлечения символов
SymbolExtractor декомпозирован на 12 языковых экстракторов:
- Java, Kotlin, Python, JavaScript/TypeScript/TSX
- Go, Rust, C/C++, C#, PHP, HTML
Новые утилиты в SymbolExtractorUtils:
extractMethodParameters()- извлечение параметров с varargs, значениями по умолчанию, аннотациямиextractMethodCalls()- анализ мест вызова с позициями аргументовextractVariableReferences()- анализ использования переменныхextractMethodBody()- извлечение тела метода для inline/extract операций
SymbolIndex для быстрого поиска
Новый класс SymbolIndex для индексации символов проекта:
- Инкрементальные обновления при изменении файлов
- Разрешение символов между файлами
- O(1) поиск определений
Исправления ошибок
Несовпадение CRC в batch-операциях (Критично)
Проблема: Токены от nts_code_refactor не проходили валидацию в последующих вызовах nts_edit_file с ошибкой несовпадения CRC.
Причина: Несогласованность вычисления CRC - FileReadTool/EditFileTool включали номера строк в контент, а рефакторинг использовал чистый контент.
Решение: Унифицировано вычисление CRC с использованием чистого контента (без номеров строк) во всех инструментах.
Ошибка Off-by-One при удалении одной строки
Проблема: Операция delete в nts_edit_file падала при удалении одной строки с ошибкой "endLine (6) must be >= startLine (7)".
Причина: SessionLineAccessTracker.updateAfterEdit() вычислял newEditEnd = editEnd + lineDelta, что давало невалидный диапазон для удаления одной строки.
Решение: Math.max(editStart, editEnd + lineDelta) гарантирует валидный диапазон.
Синхронизация кеша сессии
Проблема: После рефакторинга последующие инструменты видели устаревшие метаданные файлов, что вызывало ошибки валидации.
Решение: Все операции рефакторинга теперь вызывают SessionContext.externalChanges().updateSnapshot() после записи файлов.
Обновления документации и схем
Описания инструментов для LLM
Обновлены getDescription() в инструментах для документирования новых возможностей:
- CodeRefactorTool: использование
CHANGE_SIGNATURE,BATCH INTEGRATIONсaffectedFiles - FileManageTool: алиасинг путей с примером транзитивной цепочки
- BatchToolsTool: раздел
REFACTOR INTEGRATIONс примерами интерполяции
Входная схема
Добавлена схема массива params для change_signature:
params[]: {name, type, newName, defaultValue, action: add|remove|rename|retype|reorder}
README.md
Обе версии (EN и RU) обновлены:
- Примеры batch-интеграции с JSON-ответами
- Документация алиасинга путей
- Описание операции change signature
Покрытие тестами
+20 новых тестов, +6000 строк
ChangeSignatureComprehensiveTest- 18 сценариев для всех модификаций параметровLineAccessTokenPathAliasTest- unit-тесты алиасинга путейPathAliasIntegrationTest- интеграция move + токеныParameterExtractionTest- извлечение параметров на основе ASTSymbolIndexTest-...
v1.1.0 — Docker Support
Что нового
Docker-поддержка
- Dockerfile с multi-stage сборкой (eclipse-temurin:25-jdk/jre-alpine)
- GitHub Actions для автоматической публикации образа в ghcr.io
- docker-compose.yml для локальной разработки
NTS_DOCKER_ROOTS
Новая переменная окружения для явного указания корневых директорий в Docker-режиме. Переопределяет roots от MCP-клиента, так как пути хост-системы недоступны внутри контейнера.
docker run -i --rm \
-v /home/user/project:/mnt/project \
-e NTS_DOCKER_ROOTS=/mnt/project \
ghcr.io/nefrols/nts-mcp-fs:latestНесколько проектов
docker run -i --rm \
-v /project1:/mnt/p1 \
-v /project2:/mnt/p2 \
-e NTS_DOCKER_ROOTS=/mnt/p1:/mnt/p2 \
ghcr.io/nefrols/nts-mcp-fs:latestУстановка
Docker (рекомендуется):
docker pull ghcr.io/nefrols/nts-mcp-fs:1.1.0Java 25+:
java -jar app-all.jarКонфигурация MCP-клиента
{
"mcpServers": {
"NTS-FileSystem": {
"command": "docker",
"args": [
"run", "-i", "--rm",
"-v", "/path/to/project:/mnt/project",
"-e", "NTS_DOCKER_ROOTS=/mnt/project",
"ghcr.io/nefrols/nts-mcp-fs:1.1.0"
]
}
}
}