ncm-fast-writer
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@ncm-fast-writerwrite a one-line docstring for this function: def add(a, b): return a + b"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
NCM Code Documentation Server
Servidor MCP (Model Context Protocol) local para generación rápida de documentación y docstrings técnicos en código fuente, basado en la arquitectura Next-Concept Modeling (NCM) desarrollada por Stanford Hazy Research.
El modelo opera de manera no autorregresiva (NAR) mediante un espacio latente jerárquico (VQ-VAE de 9 niveles). A diferencia de los LLMs tradicionales autorregresivos que generan texto token a token, NCM decodifica la representación conceptual en paralelo, permitiendo generar resúmenes técnicos en ~50–100 ms sobre GPU local y reduciendo el consumo de tokens en llamadas a modelos frontera (Claude, Gemini, GPT-4).
Características
Inferencia no autorregresiva: Decodificación en paralelo a través de 9 niveles jerárquicos de cuantización vectorial.
Rendimiento local: Diseñado para ejecutarse en GPUs de consumo (e.g. NVIDIA RTX 2060 de 6 GB VRAM) con baja sobrecarga de memoria (~2.5 GB en inferencia).
Alcance de salida: Hasta 48 tokens por pasada (límite del decodificador jerárquico VQ-VAE). Especializado en docstrings de una línea, firmas y resúmenes funcionales concisos.
Protocolo MCP estándar: Conexión vía stdio compatible con Antigravity IDE, Claude Desktop y clientes compatibles con el SDK de MCP.
Posprocesamiento de código: Limpieza de n-gramas repetidos generados por decodificación NAR y reconstrucción de subtokens BPE.
Related MCP server: ansible-know-mcp
Instalación
Requisitos previos
Python 3.10 o superior
PyTorch con soporte CUDA (GPU con mínimo 4–6 GB VRAM recomendada)
Git
1. Clonar el repositorio
git clone https://github.com/artapaher-max/ncm-code-doc.git
cd ncm-code-doc2. Crear entorno virtual e instalar dependencias
python -m venv .venv
source .venv/bin/activate # En Windows: .venv\Scripts\activate
pip install -e .3. Descargar los pesos del modelo
Los pesos adaptados para código están alojados en Hugging Face en el repositorio r2d2aparicio/ncm-code-doc.
Para descargarlos en la ruta requerida (artifacts/ncm_code_doc/):
python -c "from huggingface_hub import snapshot_download; snapshot_download(repo_id='r2d2aparicio/ncm-code-doc', local_dir='artifacts/ncm_code_doc')"El directorio de artefactos debe contener:
generator.pt(~354 MB)tokenizer.pt(~299 MB)
Configuración MCP
Antigravity IDE / Claude Desktop
Agrega la definición del servidor a la configuración de servidores MCP (mcpServers):
{
"mcpServers": {
"ncm-fast-writer": {
"command": "/ruta/absoluta/a/ncm-code-doc/.venv/bin/python",
"args": [
"-u",
"/ruta/absoluta/a/ncm-code-doc/ncm_doc_server.py"
],
"env": {
"PYTHONUNBUFFERED": "1"
}
}
}
}(En Windows, sustituye las rutas por la ubicación de python.exe y ncm_doc_server.py utilizando barras inclinadas o barras invertidas dobles).
Herramienta expuesta
fast_ncm_redaction: Genera un borrador o resumen conciso de documentación técnica a partir de un fragmento de código o contexto.Parámetros:
context_or_code(string): Código fuente o fragmento técnico de entrada.
Salida: Texto conciso en lenguaje natural con la descripción funcional del bloque.
Dataset y Entrenamiento (Fine-Tuning)
Descarga y Preparación de Datos
El repositorio ya incluye data_train.jsonl con 5,000 pares curados extraídos de CodeSearchNet. Si deseas regenerar o ampliar el dataset, puedes ejecutar:
pip install datasetspython -c "
import json
from datasets import load_dataset
print('-> Descargando 5,000 muestras multi-lenguaje (Python, JS, Web)...')
ds = load_dataset('code_search_net', 'all', split='train', streaming=True, trust_remote_code=True)
count = 0
TARGET_SAMPLES = 5000
with open('data_train.jsonl', 'w', encoding='utf-8') as f:
for item in ds:
code = item.get('func_code_string', '').strip()
doc = item.get('func_documentation_string', '').strip()
# Filtro estricto para encajar en la ventana de 512 tokens de código y 48 de resumen
if code and doc and len(code) < 900 and len(doc) < 350:
row = {
'prompt': code,
'target': doc
}
f.write(json.dumps(row, ensure_ascii=False) + '\n')
count += 1
if count % 1000 == 0:
print(f' -> {count} / {TARGET_SAMPLES} procesadas...')
if count >= TARGET_SAMPLES:
break
print(f'-> Completado: {count} muestras guardadas en data_train.jsonl.')
"Ejecución del Entrenamiento
Para entrenar o adaptar el modelo con nuevos datos:
PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True python finetune_ncm.pyParámetros clave configurados en finetune_ncm.py:
Longitud de prefijo (código): 512 tokens.
Longitud objetivo (resumen): 48 tokens.
Optimización de memoria: Precisión mixta FP16 y acumulación de gradiente (batch efectivo 4) para adaptarse a GPUs de 6 GB VRAM.
Descongelamiento selectivo del decodificador VQ-VAE para vocabulario técnico de programación.
Estructura del Proyecto
ncm-code-doc/
├── ncm_doc_server.py # Punto de entrada del servidor MCP (stdio)
├── finetune_ncm.py # Script de fine-tuning adaptado a pares de código
├── data_train.jsonl # Dataset de entrenamiento (CodeSearchNet)
├── pyproject.toml # Empaquetado y dependencias del proyecto
├── models/ # Arquitectura NCM y VQ-VAE jerárquico
├── tokenization/ # Tokenizador BPE y mapeos de vocabulario
├── config/ # Configuraciones Hydra / PyTorch
└── artifacts/ # Checkpoints locales (ignorado en Git)Especificaciones de Hardware Utilizado
Este proyecto fue entrenado, evaluado y desplegado sobre hardware de consumo doméstico, demostrando la viabilidad de adaptar y ejecutar arquitecturas no autorregresivas (NAR) sin infraestructura empresarial de cómputo en la nube:
Componente | Especificación / Valor de Referencia |
GPU | NVIDIA GeForce RTX 2060 (6 GB VRAM GDDR6) |
Consumo VRAM en Entrenamiento | ~2.9 GB VRAM (FP16 AMP, Batch Size 1, Grad Accum 4) |
Consumo VRAM en Inferencia | ~2.5 GB VRAM |
Latencia de Inferencia | ~50–100 ms por bloque de código (NAR) |
Sistema Operativo | Linux (x86_64) |
Entorno Python | Python 3.12 / PyTorch 2.2+ (CUDA 12.x) |
Referencias y Créditos
Este trabajo adapta y extiende la arquitectura de:
Next-Concept Modeling: Scalable Non-Autoregressive Generation via Hierarchical Latent Space
Stanford University (Hazy Research)
Repositorio original: HazyResearch/ncm
Available Tools
1 toolfast_ncm_redactionC
Genera documentación técnica de código de forma paralela coarse-to-fine sin gastar tokens de LLM.
Args: context_or_code: Código fuente o función que se desea resumir/documentar. instruction: Directriz o tipo de documentación solicitada.
| Name | Required | Description | Default |
|---|---|---|---|
| instruction | No | Document technical summary | |
| context_or_code | Yes |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations are provided, so the description carries the full behavioral burden and largely drops it. It advertises 'sin gastar tokens de LLM' (no LLM token cost) and a parallel strategy, but does not explain what the tool actually executes, whether it is read-only, latency/cost expectations, or limits on input size. The token claim is intriguing but unverifiable and potentially misleading.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The purpose sentence is front-loaded and the Args block is terse; nothing is padded. The parameter lines repeat names already in the schema, but that repetition earns its place given zero schema description coverage.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
An output schema exists, so return values need not be described, and with only two simple string parameters the surface area is small. Still, key operational facts are missing: what 'parallel coarse-to-fine' entails, input size limits, and whether the 'no LLM tokens' claim implies a local or deterministic pipeline.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
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, and it does define both parameters: context_or_code as the source code/function to document and instruction as the requested documentation guideline. However, it omits the 'instruction' default value ('Document technical summary') and gives no guidance on expected format or length for either argument.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
States a specific verb+resource: generates technical documentation from source code, with an unusual method note ('paralela coarse-to-fine sin gastar tokens de LLM'). The purpose is distinguishable and concrete, though the 'parallel coarse-to-fine' mechanism is not explained enough to be actionable. No siblings exist, so no differentiation is required.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
There is no statement of when to use this tool, when not to, or what alternatives exist for documenting code. The Args block describes what each parameter is, not the situations that call for this tool. An agent must infer usage entirely from the one-line purpose sentence.
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 tool update
v1.0.0- First observed
fast_ncm_redaction
TDQS
Scored across 1 tool
There is only one tool, so there is no possibility of confusing it with another operation. Its purpose—generating technical documentation from code—is clearly distinct within this server.
The tool name uses consistent snake_case and is readable, but it is a noun phrase rather than a verb_noun action pattern, and the 'ncm' abbreviation is opaque. With only one tool there is no broader pattern to evaluate, so it is mostly acceptable.
A single tool is very thin for a documentation-writing server, which would typically need retrieval, export, or configuration operations. The server appears to expose only one core operation, making the surface feel under-scoped.
The only operation generates documentation, but there is no way to retrieve, save, update, or inspect generated documentation. For the stated documentation-writing domain, this leaves significant lifecycle gaps that could force agents to work around missing operations.
Maintenance
Related MCP Connectors
Provide your AI coding tools with token-efficient access to up-to-date technical documentation for…
Compress coding-agent context ~64%. Hosted Neural Keep MCP for Cursor/Claude/Codex.
A paid remote MCP for OpenAI Codex context compressor, built to return verdicts, receipts, usage log
Deterministic context layer for your codebase: change impact, blast radius, answers with receipts.
Related MCP Servers
- FlicenseNot gradedqualityDmaintenanceAllows LLM tools like Claude Desktop and Cursor AI to access and summarize code files through a Model Context Protocol server, providing structured access to codebase content without manual copying.5-
- AlicenseAqualityAmaintenanceModule discovery, documentation search, and skill generation for AI agents via the Model Context Protocol.2291 PyPI6GPL 3.0
- -licenseNot gradedqualityCmaintenanceEnables efficient search through Model Context Protocol documentation, supporting clients like Cursor and Claude Desktop.2-
- AlicenseAqualityDmaintenanceLocal-first context retrieval engine that serves precise documentation chunks to coding agents via MCP, ensuring high-confidence context for code generation.3MIT