ContextStream MCP Server

oficial

Memoria persistente y búsqueda semántica para asistentes de codificación de IA entre sesiones

Documentación

Docs · Examinar secciones

01 · Asistente de configuración

Un comando, completamente configurado.

Ejecuta un comando para autenticarte (inicio de sesión en navegador/dispositivo), crear una clave API, generar reglas y escribir la configuración MCP correcta para tu herramienta (incluyendo el esquema servers de VS Code).

terminal · terminal · macOS / Linux

curl -fsSL https://contextstream.io/scripts/mcp.sh | bash

terminal · powershell · Windows

irm https://contextstream.io/scripts/mcp.ps1 | iex

¿Ya lo tienes instalado? Vuelve a ejecutar el asistente de configuración

terminal · terminal · volver a ejecutar

contextstream-mcp setup

Qué hace: escribe la configuración MCP (VS Code servers, Cursor/Cline/etc mcpServers), genera reglas (Estándar/Mejoradas) y puede vincular proyectos a un espacio de trabajo.

Conjunto de herramientas consolidado: El asistente configura ~11 herramientas de dominio consolidadas por defecto (~75% de reducción de tokens). Opcional: modo router (~2 meta-herramientas, el más compacto). Consulta el catálogo completo de herramientas.

Previsualiza los cambios sin escribir archivos: contextstream-mcp setup --dry-run

Flujos de trabajo en equipo

Memoria compartida, habilidades y contextualización.

Las cuentas de equipo obtienen más que proyectos compartidos. Durante contextstream-mcp setup, el asistente detecta la capacidad del equipo y muestra consejos sobre el espacio de trabajo. En tu editor, cada llamada a session(action="context") puede incluir recomendaciones del equipo, pautas de gobernanza, señales de prioridad y artefactos vinculados.

Elige el espacio de trabajo compartido

Vincula cada repositorio al espacio de trabajo del equipo durante la configuración para que la indexación, las decisiones y los tickets permanezcan alineados.

Comparte habilidades del equipo

skill(action="share", scope="team") publica flujos de trabajo reutilizables que los compañeros de equipo asocian automáticamente en session(action="context").

Cambia el ámbito de ejecución

Las cuentas de contexto dual usan --account-mode=team|personal|auto o session set_account_mode en MCP.

Haz seguimiento del trabajo con entidades

Los tickets, traspasos, incidencias y lanzamientos usan referencias indexadas — duraderas a través de sesiones y compañeros de equipo.

El remoto alojado es la opción por defecto. El binario MCP local es solo para recuperación — establece CONTEXTSTREAM_ALLOW_LOCAL_MCP=1 cuando se necesite explícitamente. Consulta configuración de equipo para invitaciones/roles y la lista de verificación post-inicio de sesión.

Atajos de CLI

Comandos no interactivos (CI y actualización).

Ejecútalos sin el asistente interactivo — ideales después de actualizaciones, incorporación de equipos, rotación de credenciales o cambios en el espacio de trabajo. También se muestran en contextstream-mcp --help.

ComandoCuándo usarlo
contextstream-mcp update-hooks --scope=globalDespués de una actualización o al unirse a un espacio de trabajo de equipo — actualiza los hooks PreToolUse/UserPromptSubmit.
contextstream-mcp update-rules --scope=allRegenera .cursorrules / CLAUDE.md / AGENTS.md con la guía de flujo de trabajo del equipo más reciente.
contextstream-mcp update-configs --scope=globalReescribe las configuraciones MCP después de cambios en la clave API o el espacio de trabajo.
contextstream-mcp migrate-remote --scope=allConvierte configuraciones locales stdio heredadas al transporte remoto alojado.
contextstream-mcp detect-editors --format=jsonScript para ver qué editores están instalados (arranque/CI).
contextstream-mcp generate-configs --transport=remote --preauthEmite cargas de configuración JSON sin escribir archivos.
contextstream-mcp configure --transcripts=on --scope=allEstablece los valores predeterminados de captura de transcripciones de forma no interactiva.

terminal · modo cuenta · equipo vs personal

# Default: follow account (auto)
contextstream-mcp --account-mode=auto

# Force team-scoped reads/writes
contextstream-mcp --account-mode=team

# Or set once in shell profile:
export CONTEXTSTREAM_ACCOUNT_MODE=team

02 · Configuración manual

Configuraciones por cliente.

Usa el formato correcto para cada cliente (VS Code usa servers; muchos otros clientes usan mcpServers).

Conjunto de herramientas consolidado: Por defecto, el servidor expone ~11 herramientas de dominio consolidadas (~75% de reducción de tokens frente a herramientas granulares heredadas). Para aún menos herramientas, añade "CONTEXTSTREAM_PROGRESSIVE_MODE": "true" al bloque env para ~2 meta-herramientas de enrutador. Consulta el catálogo completo de herramientas.

Salta a tu herramienta

Cursor / VS CodeWindsurfCodex CLIOpenCode CLIClaude CodeClaude DesktopClineKilo CodeRoo CodeAntigravity

¿Qué es MCP?

Un protocolo abierto para IA.

El Protocolo de Contexto de Modelo (MCP) es un estándar abierto que permite a los asistentes de IA conectarse a herramientas y fuentes de datos externas. Con el servidor MCP de ContextStream, tus herramientas de IA pueden:

  • Recordar conversaciones y decisiones a través de sesiones
  • Buscar en tu base de código y documentación semánticamente
  • Construir y consultar grafos de conocimiento
  • Compartir contexto entre diferentes herramientas de IA

Lenguaje natural

Solo pregunta. La IA maneja las herramientas.

No necesitas memorizar nombres de herramientas ni llamarlas directamente. Solo describe lo que quieres en lenguaje natural y tu asistente de IA usará las herramientas adecuadas automáticamente.

Solo pregunta de forma natural

  • · "resumen de sesión"
  • · "¿qué decidimos sobre la autenticación?"
  • · "recuerda que estamos usando PostgreSQL"
  • · "busca código de pago"

La IA se encarga del resto

  • · Encuentra contexto relevante automáticamente
  • · Recuerda decisiones pasadas cuando es necesario
  • · Guarda información importante en la memoria
  • · Busca en código y documentación

Ejemplo · "resumen de sesión"

Natural language example: typing 'session summary' and the AI automatically uses context_smart

La IA entiende tu intención y llama a las herramientas de ContextStream apropiadas en segundo plano.

Prerrequisitos

Lo que necesitas.

  • Una cuenta de ContextStream (el asistente de configuración puede crear una clave API mediante inicio de sesión en el navegador).

Enriquecer contexto

Integraciones de GitHub + Slack

MCP le da a tu IA memoria persistente. Conectar GitHub y Slack enriquece mucho esa memoria — tu IA puede hacer referencia automáticamente a PRs, issues y discusiones de equipo al responder preguntas.

Enriquecimiento automático de contexto

Cuando llamas a context_smart o session_smart_search, los issues de GitHub, PRs y discusiones de Slack relevantes se incluyen automáticamente. No se necesitan herramientas adicionales.

GitHubSincroniza issues, PRs, lanzamientos y comentarios. Las decisiones se extraen automáticamente de las discusiones.SlackSincroniza canales e hilos. Las conversaciones de alto compromiso se puntúan y priorizan.

Ejemplos de prompts

  • · "¿Qué decidimos sobre la autenticación?" — encuentra decisiones de issues de GitHub + hilos de Slack
  • · "Muéstrame la actividad reciente en el sistema de pagos" — muestra PRs, issues y discusiones de equipo
  • · "¿Qué lecciones aprendimos de la última interrupción?" — recupera información de Slack y GitHub
  • · "Dame un resumen semanal de la actividad de GitHub" — usa integration(provider="github", action="summary", ...)
  • · "Busca en todas las integraciones discusiones sobre migración de base de datos" — usa integration(provider="all", action="search", ...)
  • · "Dame un resumen semanal del equipo de todas las fuentes" — usa integration(provider="all", action="summary", ...)

Referencia rápida de acciones de herramientas de integración

Usa integration(provider="github|slack|all", action="...")

GitHub (provider="github")

  • action="stats" — Estadísticas y estado de sincronización
  • action="search" — Buscar con filtros de estado/periodo de tiempo
  • action="activity" — Feed de actividad (filtro de días)
  • action="knowledge" — Decisiones/lecciones extraídas
  • action="summary" — Resumen semanal/mensual
  • action="repos" — Listar repositorios sincronizados
  • action="issues" — Listar issues/PRs

Slack (provider="slack")

  • action="stats" — Estadísticas y estado de sincronización
  • action="search" — Buscar con filtros de canal/periodo de tiempo
  • action="discussions" — Hilos de alto compromiso
  • action="knowledge" — Decisiones/lecciones extraídas
  • action="summary" — Resumen semanal/mensual
  • action="channels" — Listar canales sincronizados

Fuente cruzada (provider="all")

  • action="status" — Verificar estado de sincronización y salud de todas las integraciones conectadas
  • action="search" — Buscar en todas las integraciones conectadas en una sola consulta
  • action="summary" — Resumen de actividad unificado de todas las fuentes (filtro de días)
  • action="knowledge" — Obtener decisiones, lecciones e información de todas las fuentes

Cliente · Cursor / VS Code

Cursor / VS Code

Cursor y VS Code usan diferentes esquemas de configuración MCP. Cursor todavía usa un proceso MCP local, pero VS Code/Copilot ahora puede usar el MCP alojado de ContextStream directamente a través de HTTP.

terminal · .cursor/mcp.json (proyecto) o ~/.cursor/mcp.json (global)

{
  "mcpServers": {
    "contextstream": {
      "command": "contextstream-mcp",
      "env": {
        "CONTEXTSTREAM_API_URL": "https://api.contextstream.io",
        "CONTEXTSTREAM_API_KEY": "your_api_key"
      }
    }
  }
}

Recomendado para VS Code / Copilot: instalación remota con un clic

Instala el MCP alojado de ContextStream y deja que VS Code maneje OAuth en el primer uso. No es necesario que ninguna clave API o binario local resida en .vscode/mcp.json.

Instalar en VS Code Documentación de MCP de VS Code

terminal · .vscode/mcp.json (MCP nativo de VS Code, remoto)

{
  "servers": {
    "contextstream": {
      "type": "http",
      "url": "https://mcp.contextstream.io/mcp?default_context_mode=fast"
    }
  }
}

¿Prefieres la línea de comandos? Añade el servidor remoto con code --add-mcp

terminal · terminal

code --add-mcp '{"name":"contextstream","type":"http","url":"https://mcp.contextstream.io/mcp?default_context_mode=fast"}'

En el primer uso, VS Code debería solicitar autorización para ContextStream y luego finalizar la configuración automáticamente.

¿Autoalojado? Apunta la misma configuración remota a la URL de tu propio gateway MCP en lugar de https://mcp.contextstream.io/mcp?default_context_mode=fast.

Cliente · OpenCode CLI

OpenCode CLI

Para usar ContextStream con OpenCode CLI, añade la configuración del servidor MCP a tu archivo ~/.config/opencode/opencode.json (o opencode.json en la raíz de tu proyecto):

terminal · ~/.config/opencode/opencode.json

{
  "$schema": "https://opencode.ai/config.json",
  "mcp": {
    "contextstream": {
      "type": "local",
      "command": ["contextstream-mcp"],
      "enabled": true,
      "environment": {
        "CONTEXTSTREAM_API_URL": "https://api.contextstream.io",
        "CONTEXTSTREAM_API_KEY": "your_api_key"
      }
    }
  }
}

Después de editar la configuración, reinicia OpenCode para que pueda cargar el servidor MCP de ContextStream.

Cliente · Codex CLI

Codex CLI

Para usar ContextStream con Codex CLI, añade la configuración del servidor MCP a tu archivo ~/.codex/config.toml:

terminal · ~/.codex/config.toml

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

[mcp_servers.contextstream.env]
CONTEXTSTREAM_API_URL = "https://api.contextstream.io"
CONTEXTSTREAM_API_KEY = "your_api_key"

Después de editar la configuración, reinicia Codex para que pueda cargar el servidor MCP de ContextStream.

Cliente · Claude Code

Claude Code (CLI)

Añade ContextStream a Claude Code ejecutando este comando desde el directorio de tu proyecto:

terminal · terminal

claude mcp add --transport stdio contextstream --env CONTEXTSTREAM_API_URL=https://api.contextstream.io --env CONTEXTSTREAM_API_KEY=your_api_key -- contextstream-mcp

Advertencia para Windows (Windows nativo, no WSL): usa cmd /c contextstream-mcp después de --.

Alternativa: add-json (stdio)

terminal · terminal · add-json

claude mcp add-json contextstream \
'{"type":"stdio","command":"contextstream-mcp","args":[],"env":{"CONTEXTSTREAM_API_URL":"https://api.contextstream.io","CONTEXTSTREAM_API_KEY":"your_api_key"}}'

Consejo: para configuraciones de equipo, prefiere un archivo .mcp.json confirmado (ámbito de proyecto) en lugar de incrustar claves en el historial del shell.

Esto añade ContextStream a ~/.claude.json bajo la ruta de tu proyecto, haciéndolo disponible cuando trabajes en ese directorio.

Opciones de ámbito MCP

  • · Local (por defecto): Privado para ti, solo proyecto actual → almacenado en ~/.claude.json bajo la ruta del proyecto.
  • · Usuario (--scope user): Privado para ti, todos los proyectos → almacenado en ~/.claude.json globalmente.
  • · Proyecto (--scope project): Compartido con el equipo → almacenado en .mcp.json en la raíz del proyecto (confirmar en git).

Para compartir en equipo, usa el ámbito de proyecto para crear un archivo .mcp.json que pueda ser confirmado en git:

terminal · .mcp.json (ámbito de proyecto)

{
  "mcpServers": {
    "contextstream": {
      "command": "contextstream-mcp",
      "env": {
        "CONTEXTSTREAM_API_URL": "https://api.contextstream.io",
        "CONTEXTSTREAM_API_KEY": "your_api_key"
      }
    }
  }
}

Después de añadir el servidor MCP, reinicia Claude Code para que los cambios surtan efecto. Verifica que el servidor esté cargado con claude mcp list. Para servidores con ámbito de proyecto desde .mcp.json, Claude Code pedirá aprobación en el primer uso.

Cliente · Claude Desktop

Claude Desktop (aplicación de escritorio)

Añade ContextStream a la aplicación Claude Desktop:

macOS: ~/Library/Application Support/Claude/claude_desktop_config.json

Windows: %APPDATA%\Claude\claude_desktop_config.json

terminal · claude_desktop_config.json

{
  "mcpServers": {
    "contextstream": {
      "command": "contextstream-mcp",
      "env": {
        "CONTEXTSTREAM_API_URL": "https://api.contextstream.io",
        "CONTEXTSTREAM_API_KEY": "your_api_key"
      }
    }
  }
}

Después de editar la configuración, cierra y reinicia Claude Desktop para que los cambios surtan efecto.

Cliente · Windsurf

Windsurf

Añade ContextStream a Windsurf editando el archivo de configuración MCP global:

Configuración: ~/.codeium/windsurf/mcp_config.json

terminal · ~/.codeium/windsurf/mcp_config.json

{
  "mcpServers": {
    "contextstream": {
      "command": "contextstream-mcp",
      "env": {
        "CONTEXTSTREAM_API_URL": "https://api.contextstream.io",
        "CONTEXTSTREAM_API_KEY": "your_api_key"
      }
    }
  }
}

Archivos de reglas

  • · Global: ~/.codeium/windsurf/memories/global_rules.md
  • · Proyecto: .windsurf/rules/contextstream.md

Windsurf soporta hooks para la aplicación automática de las reglas de ContextStream. Después de editar la configuración, reinicia Windsurf para que los cambios surtan efecto.

Cliente · Cline

Cline

Añade ContextStream a tu configuración MCP de Cline. Haz clic en el icono de Servidores MCP en Cline, selecciona la pestaña "Configurar", luego haz clic en "Configurar Servidores MCP" para editar:

terminal · cline_mcp_settings.json

{
  "mcpServers": {
    "contextstream": {
      "command": "contextstream-mcp",
      "env": {
        "CONTEXTSTREAM_API_URL": "https://api.contextstream.io",
        "CONTEXTSTREAM_API_KEY": "your_api_key"
      }
    }
  }
}

Después de editar la configuración, reinicia Cline para que los cambios surtan efecto. También puedes usar alwaysAllow para aprobar automáticamente herramientas específicas.

Cliente · Kilo Code

Kilo Code

Añade ContextStream a tu configuración MCP de Kilo Code. Puedes configurar servidores MCP globalmente o por proyecto:

Global: Haz clic en Configuración → Servidores MCP → Instalados → Editar MCP Global para abrir mcp_settings.json

Proyecto: .kilocode/mcp.json en la raíz de tu proyecto

terminal · .kilocode/mcp.json (o mcp_settings.json)

{
  "mcpServers": {
    "contextstream": {
      "command": "contextstream-mcp",
      "env": {
        "CONTEXTSTREAM_API_URL": "https://api.contextstream.io",
        "CONTEXTSTREAM_API_KEY": "your_api_key"
      }
    }
  }
}

Las configuraciones a nivel de proyecto tienen prioridad sobre las globales. Reinicia Kilo Code después de editar.

Cliente · Roo Code

Roo Code

Añade ContextStream a tu configuración MCP de Roo Code. Puedes configurar servidores MCP globalmente o por proyecto:

Global: Haz clic en el icono de configuración → Editar MCP Global para abrir mcp_settings.json

Proyecto: .roo/mcp.json en la raíz de tu proyecto

terminal · .roo/mcp.json (o mcp_settings.json)

{
  "mcpServers": {
    "contextstream": {
      "command": "contextstream-mcp",
      "env": {
        "CONTEXTSTREAM_API_URL": "https://api.contextstream.io",
        "CONTEXTSTREAM_API_KEY": "your_api_key"
      }
    }
  }
}

Las configuraciones a nivel de proyecto tienen prioridad sobre las globales. Reinicia Roo Code después de editar.

Cliente · Antigravity

Antigravity (Google)

Antigravity usa archivos .mcp.json con ámbito de proyecto con el mismo formato que Cursor/Claude Desktop:

terminal · .mcp.json (raíz del proyecto)

{
  "mcpServers": {
    "contextstream": {
      "command": "contextstream-mcp",
      "env": {
        "CONTEXTSTREAM_API_URL": "https://api.contextstream.io",
        "CONTEXTSTREAM_API_KEY": "your_api_key"
      }
    }
  }
}

Usuarios de Windows: usa el envoltorio cmd

terminal · .mcp.json (Windows)

{
  "mcpServers": {
    "contextstream": {
      "command": "cmd",
      "args": ["/c", "contextstream-mcp"],
      "env": {
        "CONTEXTSTREAM_API_URL": "https://api.contextstream.io",
        "CONTEXTSTREAM_API_KEY": "your_api_key"
      }
    }
  }
}

Archivos de reglas

  • · Global: ~/.gemini/GEMINI.md
  • · Espacio de trabajo: .agent/rules/contextstream.md

Accede a través del menú "..." → "Servidores MCP" → "Ver configuración en bruto" para verificar tu configuración. Reinicia Antigravity después de editar.

Reglas del editor

Mejorar el uso automático de ContextStream

Recomendado

La función de contexto automático de ContextStream carga el contexto del espacio de trabajo automáticamente cuando usas cualquier herramienta de ContextStream. Sin embargo, los asistentes de IA pueden no siempre guardar decisiones de forma proactiva o recordar el contexto pasado. Añadir reglas de IA del editor mejora la consistencia y asegura que la IA capture automáticamente decisiones, preferencias y contexto importante a lo largo de tus conversaciones.

Crítico: Convenciones de nomenclatura de herramientas MCP

Diferentes herramientas de IA usan diferentes convenciones de nomenclatura para las herramientas MCP. Usar el formato incorrecto hará que las herramientas no se encuentren.

Herramienta de IAFormatoEjemplo
Claude Codemcp____mcp__contextstream__session_init
Codex CLI / OpenCode CLI (nombre en bruto)session_init
Cursor / Windsurf / Cline (nombre en bruto)session_init
Kilo Code / Roo Code (nombre en bruto)session_init

Resumen: Solo Claude Code usa el prefijo mcp__contextstream__. Todas las demás herramientas usan nombres de herramientas en bruto.

Puedes añadir reglas de ContextStream en dos niveles: Global (se aplica a todos los proyectos) o Proyecto (se aplica a un proyecto).

Reglas globales (todos los proyectos)

Añádelas una vez y se aplicarán a cada proyecto automáticamente:

EditorUbicación de reglas globales
CursorConfiguración → General → Reglas para IA
Windsurf~/.codeium/windsurf/memories/global_rules.md
Cline~/Documents/Cline/Rules/
Kilo Code~/.kilocode/rules/
Roo Code~/.roo/rules/
Claude Code~/.claude/CLAUDE.md
Codex CLI~/.codex/AGENTS.md (global) o carpeta padre (ej. ~/dev/AGENTS.md)
OpenCode CLI~/.config/opencode/AGENTS.md

Reglas de proyecto (un solo proyecto)

Añádelas a un proyecto específico. Para las reglas basadas en carpetas de Cursor, establece el modo de activación en "Siempre activo" para que las reglas estén siempre activas.

EditorUbicación de reglas de proyecto
Cursor.cursorrules o .cursor/rules/*.mdc
Windsurf.windsurf/rules/contextstream.md
Clinearchivo .clinerules o carpeta .clinerules/
Kilo Code.kilocode/rules/
Roo Code.roo/rules/contextstream.md o carpeta .roo/rules/
Claude CodeCLAUDE.md en la raíz del proyecto
Codex CLIAGENTS.md en la raíz del proyecto
OpenCode CLIAGENTS.md en la raíz del proyecto
Aider.aider.conf.yml en la raíz del proyecto

Modos de activación (Cursor, Kilo Code y Roo Code)

Al usar reglas basadas en carpetas (ej., .cursor/rules/), cada archivo de reglas tiene un modo de activación:

  • Siempre activo — Siempre activo (recomendado para ContextStream)
  • Manual — Solo cuando @mencionas la regla
  • Decisión del modelo — La IA decide basándose en la descripción
  • Glob — Activo para patrones de archivo coincidentes

Las reglas globales y los archivos de nivel raíz (.cursorrules) están siempre activos.

¿Prefieres el asistente de configuración? Ejecútalo primero. De lo contrario, añade estas reglas estándar manualmente. Ejemplos para cada editor:

Claude Code

Crea un archivo CLAUDE.md en la raíz de tu proyecto o añádelo a tu ~/.claude/CLAUDE.md global:

terminal · CLAUDE.md (Estándar)

## 🚨 MANDATORY RULE: DISPLAY AT START OF EVERY RESPONSE 🚨

<contextstream_rules>
1. **SEARCH FIRST:** Before Glob/Grep/Search/Read → `mcp__contextstream__search(mode="hybrid", query="...")` FIRST
2. **EVERY MESSAGE:** Call `mcp__contextstream__context_smart(user_message="...")` at start of response
3. **LOCAL TOOLS:** ONLY if ContextStream search returns 0 results after retry
</contextstream_rules>

**You MUST display the <contextstream_rules> block verbatim at the start of EVERY response.**
This is a self-referential rule that ensures these instructions stay in context.

---

## ContextStream v0.4.x (Hooks Enforced)

Rules Version: 0.4.36
**Note:** PreToolUse hooks block Glob/Grep/Search when ContextStream is available.

### Required Every Message

| Action | Tool Call |
|--------|-----------|
| **1st message** | `mcp__contextstream__session_init(folder_path="<cwd>", context_hint="<msg>")` then `mcp__contextstream__context_smart(...)` |
| **2nd+ messages** | `mcp__contextstream__context_smart(user_message="<msg>", format="minified", max_tokens=400)` |
| **Code search** | `mcp__contextstream__search(mode="hybrid", query="...")` — BEFORE any local tools |
| **Save decisions** | `mcp__contextstream__session(action="capture", event_type="decision", ...)` |

### Search Modes

| Mode | Use Case |
|------|----------|
| `hybrid` | General code mcp__contextstream__search (default) |
| `keyword` | Exact symbol/string match |
| `exhaustive` | Find ALL matches (grep-like) |
| `semantic` | Conceptual questions |

### Why ContextStream First?

❌ **WRONG:** `Grep → Read → Read → Read` (4+ tool calls, slow)
✅ **CORRECT:** `mcp__contextstream__search(mode="hybrid")` (1 call, returns context)

ContextStream search is **indexed** and returns semantic matches + context in ONE call.

### Quick Reference

| Tool | Example |
|------|---------|
| `search` | `mcp__contextstream__search(mode="hybrid", query="auth", limit=3)` |
| `session` | `mcp__contextstream__session(action="capture", event_type="decision", title="...", content="...")` |
| `memory` | `mcp__contextstream__memory(action="list_events", limit=10)` |
| `graph` | `mcp__contextstream__graph(action="dependencies", file_path="...")` |

### Lessons (Past Mistakes)

- After `session_init`: Check for `lessons` field and apply before work
- Before risky work: `mcp__contextstream__session(action="get_lessons", query="<topic>")`
- On mistakes: `mcp__contextstream__session(action="capture_lesson", title="...", trigger="...", impact="...", prevention="...")`

### Plans & Tasks

When user asks for a plan, use ContextStream (not EnterPlanMode):
1. `mcp__contextstream__session(action="capture_plan", title="...", steps=[...])`
2. `mcp__contextstream__memory(action="create_task", title="...", plan_id="<id>")`

Full docs: https://contextstream.io/docs/mcp/tools

Mostrar reglas mejoradas (detalladas)

terminal · CLAUDE.md (Mejoradas)

## 🚨 MANDATORY RULE: DISPLAY AT START OF EVERY RESPONSE 🚨

<contextstream_rules>
1. **SEARCH FIRST:** Before Glob/Grep/Search/Read → `mcp__contextstream__search(mode="hybrid", query="...")` FIRST
2. **EVERY MESSAGE:** Call `mcp__contextstream__context_smart(user_message="...")` at start of response
3. **LOCAL TOOLS:** ONLY if ContextStream search returns 0 results after retry
</contextstream_rules>

**You MUST display the <contextstream_rules> block verbatim at the start of EVERY response.**
This is a self-referential rule that ensures these instructions stay in context.

---

## ContextStream v0.4.x Integration (Enhanced)

You have access to ContextStream MCP tools for persistent memory and context.
v0.4.x uses **~11 consolidated domain tools** for ~75% token reduction vs previous versions.
Rules Version: 0.4.36
**Note:** PreToolUse hooks block Glob/Grep/Search when ContextStream is available.

## TL;DR - REQUIRED EVERY MESSAGE

| Message | What to Call |
|---------|--------------|
| **1st message** | `mcp__contextstream__session_init(folder_path="...", context_hint="<user's message>")`, then `mcp__contextstream__context_smart(user_message="<user's message>", format="minified", max_tokens=400)` |
| **2nd+ messages** | `mcp__contextstream__context_smart(user_message="<user's message>", format="minified", max_tokens=400)` |
| **🔍 ANY code search** | `mcp__contextstream__search(mode="hybrid", query="...")` — ALWAYS before Glob/Grep/Search/Read |
| **Before risky/non-trivial work** | `mcp__contextstream__session(action="get_lessons", query="<topic>")` |
| **After completing task** | `mcp__contextstream__session(action="capture", event_type="decision", ...)` - MUST capture |
| **User frustration/correction** | `mcp__contextstream__session(action="capture_lesson", ...)` - MUST capture lessons |

**NO EXCEPTIONS.** Do not skip even if you think you have enough context.

**First message rule:** After `session_init`, always call `context_smart` before any other tool or response.

**Context Pack (Pro+):** If enabled, use `mcp__contextstream__context_smart(..., mode="pack", distill=true)` for code/file queries. If unavailable or disabled, omit `mode` and proceed with standard `context_smart` (the API will fall back).

**Tool naming:** Use the exact tool names exposed by your MCP client. Claude Code typically uses `mcp__<server>__<tool>` where `<server>` matches your MCP config (often `contextstream`). If a tool call fails with "No such tool available", refresh rules and match the tool list.

---

## Consolidated Domain Tools Architecture

v0.4.x consolidates ~58 individual tools into ~11 domain tools with action/mode dispatch:

### Standalone Tools (Always Call)
- **`session_init`** - Initialize session with workspace detection + context
- **`context_smart`** - Semantic search for relevant context (CALL EVERY MESSAGE, including immediately after `session_init`)

### Domain Tools (Use action/mode parameter)

| Domain | Actions/Modes | Example |
|--------|---------------|---------|
| **`search`** | mode: semantic, hybrid, keyword, pattern, exhaustive, refactor | `mcp__contextstream__search(mode="hybrid", query="auth implementation", limit=3)` |
| **`session`** | action: capture, capture_lesson, get_lessons, recall, remember, user_context, summary, compress, delta, smart_search, decision_trace | `mcp__contextstream__session(action="capture", event_type="decision", title="Use JWT", content="...")` |
| **`memory`** | action: create_event, get_event, update_event, delete_event, list_events, distill_event, create_node, get_node, update_node, delete_node, list_nodes, supersede_node, search, decisions, timeline, summary | `mcp__contextstream__memory(action="list_events", limit=10)` |
| **`graph`** | action: dependencies, impact, call_path, related, path, decisions, ingest, circular_dependencies, unused_code, contradictions | `mcp__contextstream__graph(action="impact", symbol_name="AuthService")` |
| **`project`** | action: list, get, create, update, index, overview, statistics, files, index_status, ingest_local | `mcp__contextstream__project(action="statistics")` |
| **`workspace`** | action: list, get, associate, bootstrap | `mcp__contextstream__workspace(action="list")` |
| **`reminder`** | action: list, active, create, snooze, complete, dismiss | `mcp__contextstream__reminder(action="active")` |
| **`integration`** | provider: slack/github/all; action: status, search, stats, activity, contributors, knowledge, summary, channels, discussions, sync_users, repos, issues | `mcp__contextstream__integration(provider="github", action="search", query="...")` |
| **`help`** | action: tools, auth, version, editor_rules, enable_bundle | `mcp__contextstream__help(action="tools")` |

---

### Why context_smart is Required (Even After session_init)

**Common mistake:** "session_init already gave me context, I don't need context_smart"

**This is WRONG. Here's why:**
- `session_init` returns the last ~10 items **BY TIME** (chronological)
- `context_smart` **SEARCHES** for items **RELEVANT to THIS message** (semantic)

**Example failure:**
- User asks: "how should I implement authentication?"
- Auth decisions were made 20 conversations ago
- `session_init` won't have it (too old, not in recent 10)
- `context_smart` FINDS it via semantic search

**Without context_smart, you WILL miss relevant older context.**

---

### Search & Code Intelligence (ContextStream-first)

⚠️ **STOP: Before using Search/Glob/Grep/Read/Explore** → Call `mcp__contextstream__search(mode="hybrid")` FIRST. Use local tools ONLY if ContextStream returns 0 results.

**❌ WRONG workflow (wastes tokens, slow):**

Grep "function" → Leer archivo1.ts → Leer archivo2.ts → Leer archivo3.ts → finalmente entender


**✅ CORRECT workflow (fast, complete):**

mcp__contextstream__search(mode="hybrid", query="implementación de función") → hecho (los resultados incluyen contexto)


**Why?** ContextStream search returns semantic matches + context + file locations in ONE call. Local tools require multiple round-trips.

**Search Mode Selection:**

| Need | Mode | Example |
|------|------|---------|
| Find code by meaning | `hybrid` | "authentication logic", "error handling" |
| Exact string/symbol | `keyword` | "UserAuthService", "API_KEY" |
| File patterns | `pattern` | "*.sql", "test_*.py" |
| ALL matches (grep-like) | `exhaustive` | "TODO", "FIXME" (find all occurrences) |
| Symbol renaming | `refactor` | "oldFunctionName" (word-boundary matching) |
| Conceptual search | `semantic` | "how does caching work" |

**Token Efficiency:** Use `output_format` to reduce response size:
- `full` (default): Full content for understanding code
- `paths`: File paths only (80% token savings) - use for file listings
- `minimal`: Compact format (60% savings) - use for refactoring
- `count`: Match counts only (90% savings) - use for quick checks

---

### Lessons (Past Mistakes)

- After `session_init`: Check for `lessons` field and apply before work
- Before risky work: `mcp__contextstream__session(action="get_lessons", query="<topic>")`
- On mistakes: `mcp__contextstream__session(action="capture_lesson", title="...", trigger="...", impact="...", prevention="...")`

---

### Plans & Tasks

When user asks to create a plan or implementation roadmap:
1. Create plan: `mcp__contextstream__session(action="capture_plan", title="Plan Title", description="...", goals=["goal1", "goal2"], steps=[{id: "1", title: "Step 1", order: 1}, ...])`
2. Get plan_id from response, then create tasks: `mcp__contextstream__memory(action="create_task", title="Task Title", plan_id="<plan_id>", priority="high|medium|low", description="...")`

To manage existing plans/tasks:
- List plans: `mcp__contextstream__session(action="list_plans")`
- Get plan with tasks: `mcp__contextstream__session(action="get_plan", plan_id="<uuid>", include_tasks=true)`
- List tasks: `mcp__contextstream__memory(action="list_tasks", plan_id="<uuid>")` or `mcp__contextstream__memory(action="list_tasks")` for all
- Update task status: `mcp__contextstream__memory(action="update_task", task_id="<uuid>", task_status="pending|in_progress|completed|blocked")`

---

### Rules Update Notices

- If you see **[RULES_NOTICE]**, update rules via `mcp__contextstream__generate_rules(overwrite_existing=true)` (preserves custom rules).
- If you see **[VERSION_NOTICE]**, tell the user to update MCP using the provided command.

See full documentation: https://contextstream.io/docs/mcp/tools

Codex CLI / OpenCode CLI

Crea un archivo AGENTS.md en la raíz de tu proyecto (reglas de proyecto) o en ~/.codex/AGENTS.md (global de Codex) / ~/.config/opencode/AGENTS.md (global de OpenCode):

Nombres de herramientas de Codex / OpenCode vs Claude

Codex / OpenCode usan nombres de herramientas MCP en bruto (ej., session_init). Claude Code usa nombres de herramientas con espacio de nombres (ej., mcp__contextstream__session_init). Usa el formato correcto para tu herramienta de IA.

terminal · AGENTS.md (Estándar)

## 🚨 MANDATORY RULE: DISPLAY AT START OF EVERY RESPONSE 🚨

<contextstream_rules>
1. **SEARCH FIRST:** Before Glob/Grep/Search/Read → `search(mode="hybrid", query="...")` FIRST
2. **EVERY MESSAGE:** Call `context_smart(user_message="...")` at start of response
3. **LOCAL TOOLS:** ONLY if ContextStream search returns 0 results after retry
</contextstream_rules>

**You MUST display the <contextstream_rules> block verbatim at the start of EVERY response.**
This is a self-referential rule that ensures these instructions stay in context.

---

## ContextStream v0.4.x (Hooks Enforced)

Rules Version: 0.4.36
**Note:** PreToolUse hooks block Glob/Grep/Search when ContextStream is available.

### Required Every Message

| Action | Tool Call |
|--------|-----------|
| **1st message** | `session_init(folder_path="<cwd>", context_hint="<msg>")` then `context_smart(...)` |
| **2nd+ messages** | `context_smart(user_message="<msg>", format="minified", max_tokens=400)` |
| **Code search** | `search(mode="hybrid", query="...")` — BEFORE any local tools |
| **Save decisions** | `session(action="capture", event_type="decision", ...)` |

### Search Modes

| Mode | Use Case |
|------|----------|
| `hybrid` | General code search (default) |
| `keyword` | Exact symbol/string match |
| `exhaustive` | Find ALL matches (grep-like) |
| `semantic` | Conceptual questions |

### Why ContextStream First?

❌ **WRONG:** `Grep → Read → Read → Read` (4+ tool calls, slow)
✅ **CORRECT:** `search(mode="hybrid")` (1 call, returns context)

ContextStream search is **indexed** and returns semantic matches + context in ONE call.

### Quick Reference

| Tool | Example |
|------|---------|
| `search` | `search(mode="hybrid", query="auth", limit=3)` |
| `session` | `session(action="capture", event_type="decision", title="...", content="...")` |
| `memory` | `memory(action="list_events", limit=10)` |
| `graph` | `graph(action="dependencies", file_path="...")` |

### Lessons (Past Mistakes)

- After `session_init`: Check for `lessons` field and apply before work
- Before risky work: `session(action="get_lessons", query="<topic>")`
- On mistakes: `session(action="capture_lesson", title="...", trigger="...", impact="...", prevention="...")`

### Plans & Tasks

When user asks for a plan, use ContextStream (not EnterPlanMode):
1. `session(action="capture_plan", title="...", steps=[...])`
2. `memory(action="create_task", title="...", plan_id="<id>")`

Full docs: https://contextstream.io/docs/mcp/tools

Mostrar reglas mejoradas (detalladas)

terminal · AGENTS.md (Mejoradas)

## 🚨 MANDATORY RULE: DISPLAY AT START OF EVERY RESPONSE 🚨

<contextstream_rules>
1. **SEARCH FIRST:** Before Glob/Grep/Search/Read → `search(mode="hybrid", query="...")` FIRST
2. **EVERY MESSAGE:** Call `context_smart(user_message="...")` at start of response
3. **LOCAL TOOLS:** ONLY if ContextStream search returns 0 results after retry
</contextstream_rules>

**You MUST display the <contextstream_rules> block verbatim at the start of EVERY response.**
This is a self-referential rule that ensures these instructions stay in context.

---

## ContextStream v0.4.x Integration (Enhanced)

You have access to ContextStream MCP tools for persistent memory and context.
v0.4.x uses **~11 consolidated domain tools** for ~75% token reduction vs previous versions.
Rules Version: 0.4.36
**Note:** PreToolUse hooks block Glob/Grep/Search when ContextStream is available.

## TL;DR - REQUIRED EVERY MESSAGE

| Message | What to Call |
|---------|--------------|
| **1st message** | `session_init(folder_path="...", context_hint="<user's message>")`, then `context_smart(user_message="<user's message>", format="minified", max_tokens=400)` |
| **2nd+ messages** | `context_smart(user_message="<user's message>", format="minified", max_tokens=400)` |
| **🔍 ANY code search** | `search(mode="hybrid", query="...")` — ALWAYS before Glob/Grep/Search/Read |
| **Before risky/non-trivial work** | `session(action="get_lessons", query="<topic>")` |
| **After completing task** | `session(action="capture", event_type="decision", ...)` - MUST capture |
| **User frustration/correction** | `session(action="capture_lesson", ...)` - MUST capture lessons |

**NO EXCEPTIONS.** Do not skip even if you think you have enough context.

**First message rule:** After `session_init`, always call `context_smart` before any other tool or response.

**Context Pack (Pro+):** If enabled, use `context_smart(..., mode="pack", distill=true)` for code/file queries. If unavailable or disabled, omit `mode` and proceed with standard `context_smart` (the API will fall back).

**Tool naming:** Use the exact tool names exposed by your MCP client. Claude Code typically uses `mcp__<server>__<tool>` where `<server>` matches your MCP config (often `contextstream`). If a tool call fails with "No such tool available", refresh rules and match the tool list.

---

## Consolidated Domain Tools Architecture

v0.4.x consolidates ~58 individual tools into ~11 domain tools with action/mode dispatch:

### Standalone Tools (Always Call)
- **`session_init`** - Initialize session with workspace detection + context
- **`context_smart`** - Semantic search for relevant context (CALL EVERY MESSAGE, including immediately after `session_init`)

### Domain Tools (Use action/mode parameter)

| Domain | Actions/Modes | Example |
|--------|---------------|---------|
| **`search`** | mode: semantic, hybrid, keyword, pattern, exhaustive, refactor | `search(mode="hybrid", query="auth implementation", limit=3)` |
| **`session`** | action: capture, capture_lesson, get_lessons, recall, remember, user_context, summary, compress, delta, smart_search, decision_trace | `session(action="capture", event_type="decision", title="Use JWT", content="...")` |
| **`memory`** | action: create_event, get_event, update_event, delete_event, list_events, distill_event, create_node, get_node, update_node, delete_node, list_nodes, supersede_node, search, decisions, timeline, summary | `memory(action="list_events", limit=10)` |
| **`graph`** | action: dependencies, impact, call_path, related, path, decisions, ingest, circular_dependencies, unused_code, contradictions | `graph(action="impact", symbol_name="AuthService")` |
| **`project`** | action: list, get, create, update, index, overview, statistics, files, index_status, ingest_local | `project(action="statistics")` |
| **`workspace`** | action: list, get, associate, bootstrap | `workspace(action="list")` |
| **`reminder`** | action: list, active, create, snooze, complete, dismiss | `reminder(action="active")` |
| **`integration`** | provider: slack/github/all; action: status, search, stats, activity, contributors, knowledge, summary, channels, discussions, sync_users, repos, issues | `integration(provider="github", action="search", query="...")` |
| **`help`** | action: tools, auth, version, editor_rules, enable_bundle | `help(action="tools")` |

---

### Why context_smart is Required (Even After session_init)

**Common mistake:** "session_init already gave me context, I don't need context_smart"

**This is WRONG. Here's why:**
- `session_init` returns the last ~10 items **BY TIME** (chronological)
- `context_smart` **SEARCHES** for items **RELEVANT to THIS message** (semantic)

**Example failure:**
- User asks: "how should I implement authentication?"
- Auth decisions were made 20 conversations ago
- `session_init` won't have it (too old, not in recent 10)
- `context_smart` FINDS it via semantic search

**Without context_smart, you WILL miss relevant older context.**

---

### Search & Code Intelligence (ContextStream-first)

⚠️ **STOP: Before using Search/Glob/Grep/Read/Explore** → Call `search(mode="hybrid")` FIRST. Use local tools ONLY if ContextStream returns 0 results.

**❌ WRONG workflow (wastes tokens, slow):**

Grep "function" → Leer archivo1.ts → Leer archivo2.ts → Leer archivo3.ts → finalmente entender


**✅ CORRECT workflow (fast, complete):**

search(mode="hybrid", query="implementación de función") → hecho (los resultados incluyen contexto)


**Why?** ContextStream search returns semantic matches + context + file locations in ONE call. Local tools require multiple round-trips.

**Search Mode Selection:**

| Need | Mode | Example |
|------|------|---------|
| Find code by meaning | `hybrid` | "authentication logic", "error handling" |
| Exact string/symbol | `keyword` | "UserAuthService", "API_KEY" |
| File patterns | `pattern` | "*.sql", "test_*.py" |
| ALL matches (grep-like) | `exhaustive` | "TODO", "FIXME" (find all occurrences) |
| Symbol renaming | `refactor` | "oldFunctionName" (word-boundary matching) |
| Conceptual search | `semantic` | "how does caching work" |

**Token Efficiency:** Use `output_format` to reduce response size:
- `full` (default): Full content for understanding code
- `paths`: File paths only (80% token savings) - use for file listings
- `minimal`: Compact format (60% savings) - use for refactoring
- `count`: Match counts only (90% savings) - use for quick checks

---

### Lessons (Past Mistakes)

- After `session_init`: Check for `lessons` field and apply before work
- Before risky work: `session(action="get_lessons", query="<topic>")`
- On mistakes: `session(action="capture_lesson", title="...", trigger="...", impact="...", prevention="...")`

---

### Plans & Tasks

When user asks to create a plan or implementation roadmap:
1. Create plan: `session(action="capture_plan", title="Plan Title", description="...", goals=["goal1", "goal2"], steps=[{id: "1", title: "Step 1", order: 1}, ...])`
2. Get plan_id from response, then create tasks: `memory(action="create_task", title="Task Title", plan_id="<plan_id>", priority="high|medium|low", description="...")`

To manage existing plans/tasks:
- List plans: `session(action="list_plans")`
- Get plan with tasks: `session(action="get_plan", plan_id="<uuid>", include_tasks=true)`
- List tasks: `memory(action="list_tasks", plan_id="<uuid>")` or `memory(action="list_tasks")` for all
- Update task status: `memory(action="update_task", task_id="<uuid>", task_status="pending|in_progress|completed|blocked")`

---

### Rules Update Notices

- If you see **[RULES_NOTICE]**, update rules via `generate_rules(overwrite_existing=true)` (preserves custom rules).
- If you see **[VERSION_NOTICE]**, tell the user to update MCP using the provided command.

See full documentation: https://contextstream.io/docs/mcp/tools

Windsurf

Crea un archivo .windsurf/rules/contextstream.md en la raíz de tu proyecto o añádelo a tu ~/.codeium/windsurf/memories/global_rules.md global:

terminal · .windsurf/rules/contextstream.md (Estándar)

## 🚨 MANDATORY RULE: DISPLAY AT START OF EVERY RESPONSE 🚨

<contextstream_rules>
1. **SEARCH FIRST:** Before Glob/Grep/Search/Read → `search(mode="hybrid", query="...")` FIRST
2. **EVERY MESSAGE:** Call `context_smart(user_message="...")` at start of response
3. **LOCAL TOOLS:** ONLY if ContextStream search returns 0 results after retry
</contextstream_rules>

**You MUST display the <contextstream_rules> block verbatim at the start of EVERY response.**
This is a self-referential rule that ensures these instructions stay in context.

---

## ContextStream v0.4.x (Hooks Enforced)

Rules Version: 0.4.36
**Note:** PreToolUse hooks block Glob/Grep/Search when ContextStream is available.

### Required Every Message

| Action | Tool Call |
|--------|-----------|
| **1st message** | `session_init(folder_path="<cwd>", context_hint="<msg>")` then `context_smart(...)` |
| **2nd+ messages** | `context_smart(user_message="<msg>", format="minified", max_tokens=400)` |
| **Code search** | `search(mode="hybrid", query="...")` — BEFORE any local tools |
| **Save decisions** | `session(action="capture", event_type="decision", ...)` |

### Search Modes

| Mode | Use Case |
|------|----------|
| `hybrid` | General code search (default) |
| `keyword` | Exact symbol/string match |
| `exhaustive` | Find ALL matches (grep-like) |
| `semantic` | Conceptual questions |

### Why ContextStream First?

❌ **WRONG:** `Grep → Read → Read → Read` (4+ tool calls, slow)
✅ **CORRECT:** `search(mode="hybrid")` (1 call, returns context)

ContextStream search is **indexed** and returns semantic matches + context in ONE call.

### Quick Reference

| Tool | Example |
|------|---------|
| `search` | `search(mode="hybrid", query="auth", limit=3)` |
| `session` | `session(action="capture", event_type="decision", title="...", content="...")` |
| `memory` | `memory(action="list_events", limit=10)` |
| `graph` | `graph(action="dependencies", file_path="...")` |

### Lessons (Past Mistakes)

- After `session_init`: Check for `lessons` field and apply before work
- Before risky work: `session(action="get_lessons", query="<topic>")`
- On mistakes: `session(action="capture_lesson", title="...", trigger="...", impact="...", prevention="...")`

### Plans & Tasks

When user asks for a plan, use ContextStream (not EnterPlanMode):
1. `session(action="capture_plan", title="...", steps=[...])`
2. `memory(action="create_task", title="...", plan_id="<id>")`

Full docs: https://contextstream.io/docs/mcp/tools

Mostrar reglas mejoradas (detalladas)

terminal · .windsurf/rules/contextstream.md (Mejoradas)

## 🚨 MANDATORY RULE: DISPLAY AT START OF EVERY RESPONSE 🚨

<contextstream_rules>
1. **SEARCH FIRST:** Before Glob/Grep/Search/Read → `search(mode="hybrid", query="...")` FIRST
2. **EVERY MESSAGE:** Call `context_smart(user_message="...")` at start of response
3. **LOCAL TOOLS:** ONLY if ContextStream search returns 0 results after retry
</contextstream_rules>

**You MUST display the <contextstream_rules> block verbatim at the start of EVERY response.**
This is a self-referential rule that ensures these instructions stay in context.

---

## ContextStream v0.4.x Integration (Enhanced)

You have access to ContextStream MCP tools for persistent memory and context.
v0.4.x uses **~11 consolidated domain tools** for ~75% token reduction vs previous versions.
Rules Version: 0.4.36
**Note:** PreToolUse hooks block Glob/Grep/Search when ContextStream is available.

## TL;DR - REQUIRED EVERY MESSAGE

| Message | What to Call |
|---------|--------------|
| **1st message** | `session_init(folder_path="...", context_hint="<user's message>")`, then `context_smart(user_message="<user's message>", format="minified", max_tokens=400)` |
| **2nd+ messages** | `context_smart(user_message="<user's message>", format="minified", max_tokens=400)` |
| **🔍 ANY code search** | `search(mode="hybrid", query="...")` — ALWAYS before Glob/Grep/Search/Read |
| **Before risky/non-trivial work** | `session(action="get_lessons", query="<topic>")` |
| **After completing task** | `session(action="capture", event_type="decision", ...)` - MUST capture |
| **User frustration/correction** | `session(action="capture_lesson", ...)` - MUST capture lessons |

**NO EXCEPTIONS.** Do not skip even if you think you have enough context.

**First message rule:** After `session_init`, always call `context_smart` before any other tool or response.

**Context Pack (Pro+):** If enabled, use `context_smart(..., mode="pack", distill=true)` for code/file queries. If unavailable or disabled, omit `mode` and proceed with standard `context_smart` (the API will fall back).

**Tool naming:** Use the exact tool names exposed by your MCP client. Claude Code typically uses `mcp__<server>__<tool>` where `<server>` matches your MCP config (often `contextstream`). If a tool call fails with "No such tool available", refresh rules and match the tool list.

---

## Consolidated Domain Tools Architecture

v0.4.x consolidates ~58 individual tools into ~11 domain tools with action/mode dispatch:

### Standalone Tools (Always Call)
- **`session_init`** - Initialize session with workspace detection + context
- **`context_smart`** - Semantic search for relevant context (CALL EVERY MESSAGE, including immediately after `session_init`)

### Domain Tools (Use action/mode parameter)

| Domain | Actions/Modes | Example |
|--------|---------------|---------|
| **`search`** | mode: semantic, hybrid, keyword, pattern, exhaustive, refactor | `search(mode="hybrid", query="auth implementation", limit=3)` |
| **`session`** | action: capture, capture_lesson, get_lessons, recall, remember, user_context, summary, compress, delta, smart_search, decision_trace | `session(action="capture", event_type="decision", title="Use JWT", content="...")` |
| **`memory`** | action: create_event, get_event, update_event, delete_event, list_events, distill_event, create_node, get_node, update_node, delete_node, list_nodes, supersede_node, search, decisions, timeline, summary | `memory(action="list_events", limit=10)` |
| **`graph`** | action: dependencies, impact, call_path, related, path, decisions, ingest, circular_dependencies, unused_code, contradictions | `graph(action="impact", symbol_name="AuthService")` |
| **`project`** | action: list, get, create, update, index, overview, statistics, files, index_status, ingest_local | `project(action="statistics")` |
| **`workspace`** | action: list, get, associate, bootstrap | `workspace(action="list")` |
| **`reminder`** | action: list, active, create, snooze, complete, dismiss | `reminder(action="active")` |
| **`integration`** | provider: slack/github/all; action: status, search, stats, activity, contributors, knowledge, summary, channels, discussions, sync_users, repos, issues | `integration(provider="github", action="search", query="...")` |
| **`help`** | action: tools, auth, version, editor_rules, enable_bundle | `help(action="tools")` |

---

### Why context_smart is Required (Even After session_init)

**Common mistake:** "session_init already gave me context, I don't need context_smart"

**This is WRONG. Here's why:**
- `session_init` returns the last ~10 items **BY TIME** (chronological)
- `context_smart` **SEARCHES** for items **RELEVANT to THIS message** (semantic)

**Example failure:**
- User asks: "how should I implement authentication?"
- Auth decisions were made 20 conversations ago
- `session_init` won't have it (too old, not in recent 10)
- `context_smart` FINDS it via semantic search

**Without context_smart, you WILL miss relevant older context.**

---

### Search & Code Intelligence (ContextStream-first)

⚠️ **STOP: Before using Search/Glob/Grep/Read/Explore** → Call `search(mode="hybrid")` FIRST. Use local tools ONLY if ContextStream returns 0 results.

**❌ WRONG workflow (wastes tokens, slow):**

Grep "function" → Leer archivo1.ts → Leer archivo2.ts → Leer archivo3.ts → finalmente entender


**✅ CORRECT workflow (fast, complete):**

search(mode="hybrid", query="implementación de función") → hecho (los resultados incluyen contexto)


**Why?** ContextStream search returns semantic matches + context + file locations in ONE call. Local tools require multiple round-trips.

**Search Mode Selection:**

| Need | Mode | Example |
|------|------|---------|
| Find code by meaning | `hybrid` | "authentication logic", "error handling" |
| Exact string/symbol | `keyword` | "UserAuthService", "API_KEY" |
| File patterns | `pattern` | "*.sql", "test_*.py" |
| ALL matches (grep-like) | `exhaustive` | "TODO", "FIXME" (find all occurrences) |
| Symbol renaming | `refactor` | "oldFunctionName" (word-boundary matching) |
| Conceptual search | `semantic` | "how does caching work" |

**Token Efficiency:** Use `output_format` to reduce response size:
- `full` (default): Full content for understanding code
- `paths`: File paths only (80% token savings) - use for file listings
- `minimal`: Compact format (60% savings) - use for refactoring
- `count`: Match counts only (90% savings) - use for quick checks

---

### Lessons (Past Mistakes)

- After `session_init`: Check for `lessons` field and apply before work
- Before risky work: `session(action="get_lessons", query="<topic>")`
- On mistakes: `session(action="capture_lesson", title="...", trigger="...", impact="...", prevention="...")`

---

### Plans & Tasks

When user asks to create a plan or implementation roadmap:
1. Create plan: `session(action="capture_plan", title="Plan Title", description="...", goals=["goal1", "goal2"], steps=[{id: "1", title: "Step 1", order: 1}, ...])`
2. Get plan_id from response, then create tasks: `memory(action="create_task", title="Task Title", plan_id="<plan_id>", priority="high|medium|low", description="...")`

To manage existing plans/tasks:
- List plans: `session(action="list_plans")`
- Get plan with tasks: `session(action="get_plan", plan_id="<uuid>", include_tasks=true)`
- List tasks: `memory(action="list_tasks", plan_id="<uuid>")` or `memory(action="list_tasks")` for all
- Update task status: `memory(action="update_task", task_id="<uuid>", task_status="pending|in_progress|completed|blocked")`

---

### Rules Update Notices

- If you see **[RULES_NOTICE]**, update rules via `generate_rules(overwrite_existing=true)` (preserves custom rules).
- If you see **[VERSION_NOTICE]**, tell the user to update MCP using the provided command.

See full documentation: https://contextstream.io/docs/mcp/tools

Kilo Code

Crea un archivo Markdown en .kilocode/rules/:

terminal · .kilocode/rules/contextstream.md (Estándar)

## 🚨 MANDATORY RULE: DISPLAY AT START OF EVERY RESPONSE 🚨

<contextstream_rules>
1. **SEARCH FIRST:** Before Glob/Grep/Search/Read → `search(mode="hybrid", query="...")` FIRST
2. **EVERY MESSAGE:** Call `context_smart(user_message="...")` at start of response
3. **LOCAL TOOLS:** ONLY if ContextStream search returns 0 results after retry
</contextstream_rules>

**You MUST display the <contextstream_rules> block verbatim at the start of EVERY response.**
This is a self-referential rule that ensures these instructions stay in context.

---

## ContextStream v0.4.x (Hooks Enforced)

Rules Version: 0.4.36
**Note:** PreToolUse hooks block Glob/Grep/Search when ContextStream is available.

### Required Every Message

| Action | Tool Call |
|--------|-----------|
| **1st message** | `session_init(folder_path="<cwd>", context_hint="<msg>")` then `context_smart(...)` |
| **2nd+ messages** | `context_smart(user_message="<msg>", format="minified", max_tokens=400)` |
| **Code search** | `search(mode="hybrid", query="...")` — BEFORE any local tools |
| **Save decisions** | `session(action="capture", event_type="decision", ...)` |

### Search Modes

| Mode | Use Case |
|------|----------|
| `hybrid` | General code search (default) |
| `keyword` | Exact symbol/string match |
| `exhaustive` | Find ALL matches (grep-like) |
| `semantic` | Conceptual questions |

### Why ContextStream First?

❌ **WRONG:** `Grep → Read → Read → Read` (4+ tool calls, slow)
✅ **CORRECT:** `search(mode="hybrid")` (1 call, returns context)

ContextStream search is **indexed** and returns semantic matches + context in ONE call.

### Quick Reference

| Tool | Example |
|------|---------|
| `search` | `search(mode="hybrid", query="auth", limit=3)` |
| `session` | `session(action="capture", event_type="decision", title="...", content="...")` |
| `memory` | `memory(action="list_events", limit=10)` |
| `graph` | `graph(action="dependencies", file_path="...")` |

### Lessons (Past Mistakes)

- After `session_init`: Check for `lessons` field and apply before work
- Before risky work: `session(action="get_lessons", query="<topic>")`
- On mistakes: `session(action="capture_lesson", title="...", trigger="...", impact="...", prevention="...")`

### Plans & Tasks

When user asks for a plan, use ContextStream (not EnterPlanMode):
1. `session(action="capture_plan", title="...", steps=[...])`
2. `memory(action="create_task", title="...", plan_id="<id>")`

Full docs: https://contextstream.io/docs/mcp/tools

Mostrar reglas mejoradas (detalladas)

terminal · .kilocode/rules/contextstream.md (Mejoradas)

## 🚨 MANDATORY RULE: DISPLAY AT START OF EVERY RESPONSE 🚨

<contextstream_rules>
1. **SEARCH FIRST:** Before Glob/Grep/Search/Read → `search(mode="hybrid", query="...")` FIRST
2. **EVERY MESSAGE:** Call `context_smart(user_message="...")` at start of response
3. **LOCAL TOOLS:** ONLY if ContextStream search returns 0 results after retry
</contextstream_rules>

**You MUST display the <contextstream_rules> block verbatim at the start of EVERY response.**
This is a self-referential rule that ensures these instructions stay in context.

---

## ContextStream v0.4.x Integration (Enhanced)

You have access to ContextStream MCP tools for persistent memory and context.
v0.4.x uses **~11 consolidated domain tools** for ~75% token reduction vs previous versions.
Rules Version: 0.4.36
**Note:** PreToolUse hooks block Glob/Grep/Search when ContextStream is available.

## TL;DR - REQUIRED EVERY MESSAGE

| Message | What to Call |
|---------|--------------|
| **1st message** | `session_init(folder_path="...", context_hint="<user's message>")`, then `context_smart(user_message="<user's message>", format="minified", max_tokens=400)` |
| **2nd+ messages** | `context_smart(user_message="<user's message>", format="minified", max_tokens=400)` |
| **🔍 ANY code search** | `search(mode="hybrid", query="...")` — ALWAYS before Glob/Grep/Search/Read |
| **Before risky/non-trivial work** | `session(action="get_lessons", query="<topic>")` |
| **After completing task** | `session(action="capture", event_type="decision", ...)` - MUST capture |
| **User frustration/correction** | `session(action="capture_lesson", ...)` - MUST capture lessons |

**NO EXCEPTIONS.** Do not skip even if you think you have enough context.

**First message rule:** After `session_init`, always call `context_smart` before any other tool or response.

**Context Pack (Pro+):** If enabled, use `context_smart(..., mode="pack", distill=true)` for code/file queries. If unavailable or disabled, omit `mode` and proceed with standard `context_smart` (the API will fall back).

**Tool naming:** Use the exact tool names exposed by your MCP client. Claude Code typically uses `mcp__<server>__<tool>` where `<server>` matches your MCP config (often `contextstream`). If a tool call fails with "No such tool available", refresh rules and match the tool list.

---

## Consolidated Domain Tools Architecture

v0.4.x consolidates ~58 individual tools into ~11 domain tools with action/mode dispatch:

### Standalone Tools (Always Call)
- **`session_init`** - Initialize session with workspace detection + context
- **`context_smart`** - Semantic search for relevant context (CALL EVERY MESSAGE, including immediately after `session_init`)

### Domain Tools (Use action/mode parameter)

| Domain | Actions/Modes | Example |
|--------|---------------|---------|
| **`search`** | mode: semantic, hybrid, keyword, pattern, exhaustive, refactor | `search(mode="hybrid", query="auth implementation", limit=3)` |
| **`session`** | action: capture, capture_lesson, get_lessons, recall, remember, user_context, summary, compress, delta, smart_search, decision_trace | `session(action="capture", event_type="decision", title="Use JWT", content="...")` |
| **`memory`** | action: create_event, get_event, update_event, delete_event, list_events, distill_event, create_node, get_node, update_node, delete_node, list_nodes, supersede_node, search, decisions, timeline, summary | `memory(action="list_events", limit=10)` |
| **`graph`** | action: dependencies, impact, call_path, related, path, decisions, ingest, circular_dependencies, unused_code, contradictions | `graph(action="impact", symbol_name="AuthService")` |
| **`project`** | action: list, get, create, update, index, overview, statistics, files, index_status, ingest_local | `project(action="statistics")` |
| **`workspace`** | action: list, get, associate, bootstrap | `workspace(action="list")` |
| **`reminder`** | action: list, active, create, snooze, complete, dismiss | `reminder(action="active")` |
| **`integration`** | provider: slack/github/all; action: status, search, stats, activity, contributors, knowledge, summary, channels, discussions, sync_users, repos, issues | `integration(provider="github", action="search", query="...")` |
| **`help`** | action: tools, auth, version, editor_rules, enable_bundle | `help(action="tools")` |

---

### Why context_smart is Required (Even After session_init)

**Common mistake:** "session_init already gave me context, I don't need context_smart"

**This is WRONG. Here's why:**
- `session_init` returns the last ~10 items **BY TIME** (chronological)
- `context_smart` **SEARCHES** for items **RELEVANT to THIS message** (semantic)

**Example failure:**
- User asks: "how should I implement authentication?"
- Auth decisions were made 20 conversations ago
- `session_init` won't have it (too old, not in recent 10)
- `context_smart` FINDS it via semantic search

**Without context_smart, you WILL miss relevant older context.**

---

### Search & Code Intelligence (ContextStream-first)

⚠️ **STOP: Before using Search/Glob/Grep/Read/Explore** → Call `search(mode="hybrid")` FIRST. Use local tools ONLY if ContextStream returns 0 results.

**❌ WRONG workflow (wastes tokens, slow):**

Grep "function" → Leer archivo1.ts → Leer archivo2.ts → Leer archivo3.ts → finalmente entender


**✅ CORRECT workflow (fast, complete):**

search(mode="hybrid", query="implementación de función") → hecho (los resultados incluyen contexto)


**Why?** ContextStream search returns semantic matches + context + file locations in ONE call. Local tools require multiple round-trips.

**Search Mode Selection:**

| Need | Mode | Example |
|------|------|---------|
| Find code by meaning | `hybrid` | "authentication logic", "error handling" |
| Exact string/symbol | `keyword` | "UserAuthService", "API_KEY" |
| File patterns | `pattern` | "*.sql", "test_*.py" |
| ALL matches (grep-like) | `exhaustive` | "TODO", "FIXME" (find all occurrences) |
| Symbol renaming | `refactor` | "oldFunctionName" (word-boundary matching) |
| Conceptual search | `semantic` | "how does caching work" |

**Token Efficiency:** Use `output_format` to reduce response size:
- `full` (default): Full content for understanding code
- `paths`: File paths only (80% token savings) - use for file listings
- `minimal`: Compact format (60% savings) - use for refactoring
- `count`: Match counts only (90% savings) - use for quick checks

---

### Lessons (Past Mistakes)

- After `session_init`: Check for `lessons` field and apply before work
- Before risky work: `session(action="get_lessons", query="<topic>")`
- On mistakes: `session(action="capture_lesson", title="...", trigger="...", impact="...", prevention="...")`

---

### Plans & Tasks

When user asks to create a plan or implementation roadmap:
1. Create plan: `session(action="capture_plan", title="Plan Title", description="...", goals=["goal1", "goal2"], steps=[{id: "1", title: "Step 1", order: 1}, ...])`
2. Get plan_id from response, then create tasks: `memory(action="create_task", title="Task Title", plan_id="<plan_id>", priority="high|medium|low", description="...")`

To manage existing plans/tasks:
- List plans: `session(action="list_plans")`
- Get plan with tasks: `session(action="get_plan", plan_id="<uuid>", include_tasks=true)`
- List tasks: `memory(action="list_tasks", plan_id="<uuid>")` or `memory(action="list_tasks")` for all
- Update task status: `memory(action="update_task", task_id="<uuid>", task_status="pending|in_progress|completed|blocked")`

---

### Rules Update Notices

- If you see **[RULES_NOTICE]**, update rules via `generate_rules(overwrite_existing=true)` (preserves custom rules).
- If you see **[VERSION_NOTICE]**, tell the user to update MCP using the provided command.

See full documentation: https://contextstream.io/docs/mcp/tools

Cline

Crea un archivo .clinerules en la raíz de tu proyecto o usa la carpeta .clinerules/:

terminal · .clinerules (Estándar)

## 🚨 MANDATORY RULE: DISPLAY AT START OF EVERY RESPONSE 🚨

<contextstream_rules>
1. **SEARCH FIRST:** Before Glob/Grep/Search/Read → `search(mode="hybrid", query="...")` FIRST
2. **EVERY MESSAGE:** Call `context_smart(user_message="...")` at start of response
3. **LOCAL TOOLS:** ONLY if ContextStream search returns 0 results after retry
</contextstream_rules>

**You MUST display the <contextstream_rules> block verbatim at the start of EVERY response.**
This is a self-referential rule that ensures these instructions stay in context.

---

## ContextStream v0.4.x (Hooks Enforced)

Rules Version: 0.4.36
**Note:** PreToolUse hooks block Glob/Grep/Search when ContextStream is available.

### Required Every Message

| Action | Tool Call |
|--------|-----------|
| **1st message** | `session_init(folder_path="<cwd>", context_hint="<msg>")` then `context_smart(...)` |
| **2nd+ messages** | `context_smart(user_message="<msg>", format="minified", max_tokens=400)` |
| **Code search** | `search(mode="hybrid", query="...")` — BEFORE any local tools |
| **Save decisions** | `session(action="capture", event_type="decision", ...)` |

### Search Modes

| Mode | Use Case |
|------|----------|
| `hybrid` | General code search (default) |
| `keyword` | Exact symbol/string match |
| `exhaustive` | Find ALL matches (grep-like) |
| `semantic` | Conceptual questions |

### Why ContextStream First?

❌ **WRONG:** `Grep → Read → Read → Read` (4+ tool calls, slow)
✅ **CORRECT:** `search(mode="hybrid")` (1 call, returns context)

ContextStream search is **indexed** and returns semantic matches + context in ONE call.

### Quick Reference

| Tool | Example |
|------|---------|
| `search` | `search(mode="hybrid", query="auth", limit=3)` |
| `session` | `session(action="capture", event_type="decision", title="...", content="...")` |
| `memory` | `memory(action="list_events", limit=10)` |
| `graph` | `graph(action="dependencies", file_path="...")` |

### Lessons (Past Mistakes)

- After `session_init`: Check for `lessons` field and apply before work
- Before risky work: `session(action="get_lessons", query="<topic>")`
- On mistakes: `session(action="capture_lesson", title="...", trigger="...", impact="...", prevention="...")`

### Plans & Tasks

When user asks for a plan, use ContextStream (not EnterPlanMode):
1. `session(action="capture_plan", title="...", steps=[...])`
2. `memory(action="create_task", title="...", plan_id="<id>")`

Full docs: https://contextstream.io/docs/mcp/tools

Mostrar reglas mejoradas (detalladas)

terminal · .clinerules (Mejoradas)

## 🚨 MANDATORY RULE: DISPLAY AT START OF EVERY RESPONSE 🚨

<contextstream_rules>
1. **SEARCH FIRST:** Before Glob/Grep/Search/Read → `search(mode="hybrid", query="...")` FIRST
2. **EVERY MESSAGE:** Call `context_smart(user_message="...")` at start of response
3. **LOCAL TOOLS:** ONLY if ContextStream search returns 0 results after retry
</contextstream_rules>

**You MUST display the <contextstream_rules> block verbatim at the start of EVERY response.**
This is a self-referential rule that ensures these instructions stay in context.

---

## ContextStream v0.4.x Integration (Enhanced)

You have access to ContextStream MCP tools for persistent memory and context.
v0.4.x uses **~11 consolidated domain tools** for ~75% token reduction vs previous versions.
Rules Version: 0.4.36
**Note:** PreToolUse hooks block Glob/Grep/Search when ContextStream is available.

## TL;DR - REQUIRED EVERY MESSAGE

| Message | What to Call |
|---------|--------------|
| **1st message** | `session_init(folder_path="...", context_hint="<user's message>")`, then `context_smart(user_message="<user's message>", format="minified", max_tokens=400)` |
| **2nd+ messages** | `context_smart(user_message="<user's message>", format="minified", max_tokens=400)` |
| **🔍 ANY code search** | `search(mode="hybrid", query="...")` — ALWAYS before Glob/Grep/Search/Read |
| **Before risky/non-trivial work** | `session(action="get_lessons", query="<topic>")` |
| **After completing task** | `session(action="capture", event_type="decision", ...)` - MUST capture |
| **User frustration/correction** | `session(action="capture_lesson", ...)` - MUST capture lessons |

**NO EXCEPTIONS.** Do not skip even if you think you have enough context.

**First message rule:** After `session_init`, always call `context_smart` before any other tool or response.

**Context Pack (Pro+):** If enabled, use `context_smart(..., mode="pack", distill=true)` for code/file queries. If unavailable or disabled, omit `mode` and proceed with standard `context_smart` (the API will fall back).

**Tool naming:** Use the exact tool names exposed by your MCP client. Claude Code typically uses `mcp__<server>__<tool>` where `<server>` matches your MCP config (often `contextstream`). If a tool call fails with "No such tool available", refresh rules and match the tool list.

---

## Consolidated Domain Tools Architecture

v0.4.x consolidates ~58 individual tools into ~11 domain tools with action/mode dispatch:

### Standalone Tools (Always Call)
- **`session_init`** - Initialize session with workspace detection + context
- **`context_smart`** - Semantic search for relevant context (CALL EVERY MESSAGE, including immediately after `session_init`)

### Domain Tools (Use action/mode parameter)

| Domain | Actions/Modes | Example |
|--------|---------------|---------|
| **`search`** | mode: semantic, hybrid, keyword, pattern, exhaustive, refactor | `search(mode="hybrid", query="auth implementation", limit=3)` |
| **`session`** | action: capture, capture_lesson, get_lessons, recall, remember, user_context, summary, compress, delta, smart_search, decision_trace | `session(action="capture", event_type="decision", title="Use JWT", content="...")` |
| **`memory`** | action: create_event, get_event, update_event, delete_event, list_events, distill_event, create_node, get_node, update_node, delete_node, list_nodes, supersede_node, search, decisions, timeline, summary | `memory(action="list_events", limit=10)` |
| **`graph`** | action: dependencies, impact, call_path, related, path, decisions, ingest, circular_dependencies, unused_code, contradictions | `graph(action="impact", symbol_name="AuthService")` |
| **`project`** | action: list, get, create, update, index, overview, statistics, files, index_status, ingest_local | `project(action="statistics")` |
| **`workspace`** | action: list, get, associate, bootstrap | `workspace(action="list")` |
| **`reminder`** | action: list, active, create, snooze, complete, dismiss | `reminder(action="active")` |
| **`integration`** | provider: slack/github/all; action: status, search, stats, activity, contributors, knowledge, summary, channels, discussions, sync_users, repos, issues | `integration(provider="github", action="search", query="...")` |
| **`help`** | action: tools, auth, version, editor_rules, enable_bundle | `help(action="tools")` |

---

### Why context_smart is Required (Even After session_init)

**Common mistake:** "session_init already gave me context, I don't need context_smart"

**This is WRONG. Here's why:**
- `session_init` returns the last ~10 items **BY TIME** (chronological)
- `context_smart` **SEARCHES** for items **RELEVANT to THIS message** (semantic)

**Example failure:**
- User asks: "how should I implement authentication?"
- Auth decisions were made 20 conversations ago
- `session_init` won't have it (too old, not in recent 10)
- `context_smart` FINDS it via semantic search

**Without context_smart, you WILL miss relevant older context.**

---

### Search & Code Intelligence (ContextStream-first)

⚠️ **STOP: Before using Search/Glob/Grep/Read/Explore** → Call `search(mode="hybrid")` FIRST. Use local tools ONLY if ContextStream returns 0 results.

**❌ WRONG workflow (wastes tokens, slow):**

Grep "function" → Leer archivo1.ts → Leer archivo2.ts → Leer archivo3.ts → finalmente entender


**✅ CORRECT workflow (fast, complete):**

search(mode="hybrid", query="implementación de función") → hecho (los resultados incluyen contexto)


**Why?** ContextStream search returns semantic matches + context + file locations in ONE call. Local tools require multiple round-trips.

**Search Mode Selection:**

| Need | Mode | Example |
|------|------|---------|
| Find code by meaning | `hybrid` | "authentication logic", "error handling" |
| Exact string/symbol | `keyword` | "UserAuthService", "API_KEY" |
| File patterns | `pattern` | "*.sql", "test_*.py" |
| ALL matches (grep-like) | `exhaustive` | "TODO", "FIXME" (find all occurrences) |
| Symbol renaming | `refactor` | "oldFunctionName" (word-boundary matching) |
| Conceptual search | `semantic` | "how does caching work" |

**Token Efficiency:** Use `output_format` to reduce response size:
- `full` (default): Full content for understanding code
- `paths`: File paths only (80% token savings) - use for file listings
- `minimal`: Compact format (60% savings) - use for refactoring
- `count`: Match counts only (90% savings) - use for quick checks

---

### Lessons (Past Mistakes)

- After `session_init`: Check for `lessons` field and apply before work
- Before risky work: `session(action="get_lessons", query="<topic>")`
- On mistakes: `session(action="capture_lesson", title="...", trigger="...", impact="...", prevention="...")`

---

### Plans & Tasks

When user asks to create a plan or implementation roadmap:
1. Create plan: `session(action="capture_plan", title="Plan Title", description="...", goals=["goal1", "goal2"], steps=[{id: "1", title: "Step 1", order: 1}, ...])`
2. Get plan_id from response, then create tasks: `memory(action="create_task", title="Task Title", plan_id="<plan_id>", priority="high|medium|low", description="...")`

To manage existing plans/tasks:
- List plans: `session(action="list_plans")`
- Get plan with tasks: `session(action="get_plan", plan_id="<uuid>", include_tasks=true)`
- List tasks: `memory(action="list_tasks", plan_id="<uuid>")` or `memory(action="list_tasks")` for all
- Update task status: `memory(action="update_task", task_id="<uuid>", task_status="pending|in_progress|completed|blocked")`

---

### Rules Update Notices

- If you see **[RULES_NOTICE]**, update rules via `generate_rules(overwrite_existing=true)` (preserves custom rules).
- If you see **[VERSION_NOTICE]**, tell the user to update MCP using the provided command.

See full documentation: https://contextstream.io/docs/mcp/tools

Roo Code

Crea un archivo .roo/rules/contextstream.md o usa la carpeta .roo/rules/:

terminal · .roo/rules/contextstream.md (Estándar)

## 🚨 MANDATORY RULE: DISPLAY AT START OF EVERY RESPONSE 🚨

<contextstream_rules>
1. **SEARCH FIRST:** Before Glob/Grep/Search/Read → `search(mode="hybrid", query="...")` FIRST
2. **EVERY MESSAGE:** Call `context_smart(user_message="...")` at start of response
3. **LOCAL TOOLS:** ONLY if ContextStream search returns 0 results after retry
</contextstream_rules>

**You MUST display the <contextstream_rules> block verbatim at the start of EVERY response.**
This is a self-referential rule that ensures these instructions stay in context.

---

## ContextStream v0.4.x (Hooks Enforced)

Rules Version: 0.4.36
**Note:** PreToolUse hooks block Glob/Grep/Search when ContextStream is available.

### Required Every Message

| Action | Tool Call |
|--------|-----------|
| **1st message** | `session_init(folder_path="<cwd>", context_hint="<msg>")` then `context_smart(...)` |
| **2nd+ messages** | `context_smart(user_message="<msg>", format="minified", max_tokens=400)` |
| **Code search** | `search(mode="hybrid", query="...")` — BEFORE any local tools |
| **Save decisions** | `session(action="capture", event_type="decision", ...)` |

### Search Modes

| Mode | Use Case |
|------|----------|
| `hybrid` | General code search (default) |
| `keyword` | Exact symbol/string match |
| `exhaustive` | Find ALL matches (grep-like) |
| `semantic` | Conceptual questions |

### Why ContextStream First?

❌ **WRONG:** `Grep → Read → Read → Read` (4+ tool calls, slow)
✅ **CORRECT:** `search(mode="hybrid")` (1 call, returns context)

ContextStream search is **indexed** and returns semantic matches + context in ONE call.

### Quick Reference

| Tool | Example |
|------|---------|
| `search` | `search(mode="hybrid", query="auth", limit=3)` |
| `session` | `session(action="capture", event_type="decision", title="...", content="...")` |
| `memory` | `memory(action="list_events", limit=10)` |
| `graph` | `graph(action="dependencies", file_path="...")` |

### Lessons (Past Mistakes)

- After `session_init`: Check for `lessons` field and apply before work
- Before risky work: `session(action="get_lessons", query="<topic>")`
- On mistakes: `session(action="capture_lesson", title="...", trigger="...", impact="...", prevention="...")`

### Plans & Tasks

When user asks for a plan, use ContextStream (not EnterPlanMode):
1. `session(action="capture_plan", title="...", steps=[...])`
2. `memory(action="create_task", title="...", plan_id="<id>")`

Full docs: https://contextstream.io/docs/mcp/tools

Mostrar reglas mejoradas (detalladas)

terminal · .roo/rules/contextstream.md (Mejoradas)

## 🚨 MANDATORY RULE: DISPLAY AT START OF EVERY RESPONSE 🚨

<contextstream_rules>
1. **SEARCH FIRST:** Before Glob/Grep/Search/Read → `search(mode="hybrid", query="...")` FIRST
2. **EVERY MESSAGE:** Call `context_smart(user_message="...")` at start of response
3. **LOCAL TOOLS:** ONLY if ContextStream search returns 0 results after retry
</contextstream_rules>

**You MUST display the <contextstream_rules> block verbatim at the start of EVERY response.**
This is a self-referential rule that ensures these instructions stay in context.

---

## ContextStream v0.4.x Integration (Enhanced)

You have access to ContextStream MCP tools for persistent memory and context.
v0.4.x uses **~11 consolidated domain tools** for ~75% token reduction vs previous versions.
Rules Version: 0.4.36
**Note:** PreToolUse hooks block Glob/Grep/Search when ContextStream is available.

## TL;DR - REQUIRED EVERY MESSAGE

| Message | What to Call |
|---------|--------------|
| **1st message** | `session_init(folder_path="...", context_hint="<user's message>")`, then `context_smart(user_message="<user's message>", format="minified", max_tokens=400)` |
| **2nd+ messages** | `context_smart(user_message="<user's message>", format="minified", max_tokens=400)` |
| **🔍 ANY code search** | `search(mode="hybrid", query="...")` — ALWAYS before Glob/Grep/Search/Read |
| **Before risky/non-trivial work** | `session(action="get_lessons", query="<topic>")` |
| **After completing task** | `session(action="capture", event_type="decision", ...)` - MUST capture |
| **User frustration/correction** | `session(action="capture_lesson", ...)` - MUST capture lessons |

**NO EXCEPTIONS.** Do not skip even if you think you have enough context.

**First message rule:** After `session_init`, always call `context_smart` before any other tool or response.

**Context Pack (Pro+):** If enabled, use `context_smart(..., mode="pack", distill=true)` for code/file queries. If unavailable or disabled, omit `mode` and proceed with standard `context_smart` (the API will fall back).

**Tool naming:** Use the exact tool names exposed by your MCP client. Claude Code typically uses `mcp__<server>__<tool>` where `<server>` matches your MCP config (often `contextstream`). If a tool call fails with "No such tool available", refresh rules and match the tool list.

---

## Consolidated Domain Tools Architecture

v0.4.x consolidates ~58 individual tools into ~11 domain tools with action/mode dispatch:

### Standalone Tools (Always Call)
- **`session_init`** - Initialize session with workspace detection + context
- **`context_smart`** - Semantic search for relevant context (CALL EVERY MESSAGE, including immediately after `session_init`)

### Domain Tools (Use action/mode parameter)

| Domain | Actions/Modes | Example |
|--------|---------------|---------|
| **`search`** | mode: semantic, hybrid, keyword, pattern, exhaustive, refactor | `search(mode="hybrid", query="auth implementation", limit=3)` |
| **`session`** | action: capture, capture_lesson, get_lessons, recall, remember, user_context, summary, compress, delta, smart_search, decision_trace | `session(action="capture", event_type="decision", title="Use JWT", content="...")` |
| **`memory`** | action: create_event, get_event, update_event, delete_event, list_events, distill_event, create_node, get_node, update_node, delete_node, list_nodes, supersede_node, search, decisions, timeline, summary | `memory(action="list_events", limit=10)` |
| **`graph`** | action: dependencies, impact, call_path, related, path, decisions, ingest, circular_dependencies, unused_code, contradictions | `graph(action="impact", symbol_name="AuthService")` |
| **`project`** | action: list, get, create, update, index, overview, statistics, files, index_status, ingest_local | `project(action="statistics")` |
| **`workspace`** | action: list, get, associate, bootstrap | `workspace(action="list")` |
| **`reminder`** | action: list, active, create, snooze, complete, dismiss | `reminder(action="active")` |
| **`integration`** | provider: slack/github/all; action: status, search, stats, activity, contributors, knowledge, summary, channels, discussions, sync_users, repos, issues | `integration(provider="github", action="search", query="...")` |
| **`help`** | action: tools, auth, version, editor_rules, enable_bundle | `help(action="tools")` |

---

### Why context_smart is Required (Even After session_init)

**Common mistake:** "session_init already gave me context, I don't need context_smart"

**This is WRONG. Here's why:**
- `session_init` returns the last ~10 items **BY TIME** (chronological)
- `context_smart` **SEARCHES** for items **RELEVANT to THIS message** (semantic)

**Example failure:**
- User asks: "how should I implement authentication?"
- Auth decisions were made 20 conversations ago
- `session_init` won't have it (too old, not in recent 10)
- `context_smart` FINDS it via semantic search

**Without context_smart, you WILL miss relevant older context.**

---

### Search & Code Intelligence (ContextStream-first)

⚠️ **STOP: Before using Search/Glob/Grep/Read/Explore** → Call `search(mode="hybrid")` FIRST. Use local tools ONLY if ContextStream returns 0 results.

**❌ WRONG workflow (wastes tokens, slow):**

Grep "function" → Leer archivo1.ts → Leer archivo2.ts → Leer archivo3.ts → finalmente entender


**✅ CORRECT workflow (fast, complete):**

search(mode="hybrid", query="implementación de función") → hecho (los resultados incluyen contexto)


**Why?** ContextStream search returns semantic matches + context + file locations in ONE call. Local tools require multiple round-trips.

**Search Mode Selection:**

| Need | Mode | Example |
|------|------|---------|
| Find code by meaning | `hybrid` | "authentication logic", "error handling" |
| Exact string/symbol | `keyword` | "UserAuthService", "API_KEY" |
| File patterns | `pattern` | "*.sql", "test_*.py" |
| ALL matches (grep-like) | `exhaustive` | "TODO", "FIXME" (find all occurrences) |
| Symbol renaming | `refactor` | "oldFunctionName" (word-boundary matching) |
| Conceptual search | `semantic` | "how does caching work" |

**Token Efficiency:** Use `output_format` to reduce response size:
- `full` (default): Full content for understanding code
- `paths`: File paths only (80% token savings) - use for file listings
- `minimal`: Compact format (60% savings) - use for refactoring
- `count`: Match counts only (90% savings) - use for quick checks

---

### Lessons (Past Mistakes)

- After `session_init`: Check for `lessons` field and apply before work
- Before risky work: `session(action="get_lessons", query="<topic>")`
- On mistakes: `session(action="capture_lesson", title="...", trigger="...", impact="...", prevention="...")`

---

### Plans & Tasks

When user asks to create a plan or implementation roadmap:
1. Create plan: `session(action="capture_plan", title="Plan Title", description="...", goals=["goal1", "goal2"], steps=[{id: "1", title: "Step 1", order: 1}, ...])`
2. Get plan_id from response, then create tasks: `memory(action="create_task", title="Task Title", plan_id="<plan_id>", priority="high|medium|low", description="...")`

To manage existing plans/tasks:
- List plans: `session(action="list_plans")`
- Get plan with tasks: `session(action="get_plan", plan_id="<uuid>", include_tasks=true)`
- List tasks: `memory(action="list_tasks", plan_id="<uuid>")` or `memory(action="list_tasks")` for all
- Update task status: `memory(action="update_task", task_id="<uuid>", task_status="pending|in_progress|completed|blocked")`

---

### Rules Update Notices

- If you see **[RULES_NOTICE]**, update rules via `generate_rules(overwrite_existing=true)` (preserves custom rules).
- If you see **[VERSION_NOTICE]**, tell the user to update MCP using the provided command.

See full documentation: https://contextstream.io/docs/mcp/tools

Generar reglas automáticamente

También puedes pedirle a la IA que genere estas reglas automáticamente diciendo: "Usa generate_rules para crear reglas de ContextStream para este proyecto"

Sistema de lecciones

Sistema de lecciones aprendidas

Aprende de los errores — nunca los repitas

El Sistema de Lecciones captura errores, correcciones y frustraciones del usuario para que los asistentes de IA nunca repitan los mismos errores. Las lecciones se muestran automáticamente en las respuestas de session_init y context_smart cuando son relevantes.

Cuándo capturar lecciones

Las lecciones deben capturarse automáticamente cuando ocurra alguna de estas situaciones:

DesencadenanteEjemploGravedad
Problema en producción"El sitio está caído por ese cambio"crítica
Frustración del usuario"¡NO! ¡Te dije que NO hicieras eso!", "WTF", mayúsculasalta
Corrección"Eso está mal, deberías...", "Arregla esto"media
Cambio disruptivo"Esto rompió las pruebas", "La compilación falló"media/alta
Preferencia expresada"Lo prefiero así", "Siempre haz X en su lugar"baja

Campos de la lección explicados

CampoDescripciónEjemplo
títuloQué recordar (imperativo)"Verificar siempre los assets en git antes de hacer push"
gravedadcrítica, alta, media, baja"crítica" para problemas en producción
categoríaflujo de trabajo, calidad_código, verificación, comunicación, específica_proyecto"flujo de trabajo"
desencadenanteQué acción causó el problema"Hizo push de código referenciando imágenes sin commitearlas"
impactoQué salió mal"Errores 404 en producción - página de inicio rota"
prevenciónCómo prevenir en el futuro"Ejecutar git status para verificar archivos no rastreados antes de hacer push"
palabras clavePalabras clave para coincidir en contextos futuros["git", "imágenes", "assets", "push"]

Ejemplo completo

terminal · session_capture_lesson

// User says: "OH COME ON! You pushed the code but the images are missing
// and now the production site shows broken images!"

session_capture_lesson({
  title: "Always verify assets in git before pushing code references",
  severity: "critical",
  category: "workflow",
  trigger: "Pushed code referencing /screenshots/*.png without committing images",
  impact: "Production 404 errors - broken landing page with missing images",
  prevention: "Run 'git status' to check untracked files before pushing code that references static assets",
  keywords: ["git", "images", "assets", "push", "404", "static", "screenshots"]
})

Cómo se muestran las lecciones

Las lecciones capturadas se devuelven automáticamente en sesiones futuras cuando son relevantes:

session_init

Las lecciones de gravedad alta y crítica de este espacio de trabajo se incluyen en la inicialización de la sesión, advirtiendo a la IA antes de que pueda cometer el mismo error.

context_smart

Cuando la IA solicita contexto, se incluyen las lecciones que coinciden con las palabras clave de la consulta. Por ejemplo, preguntar sobre "git push" muestra lecciones con palabras clave "git" o "push".

Recuperar lecciones

Usa session_get_lessons para recuperar y filtrar lecciones:

terminal · ejemplos de session_get_lessons

// Get all critical lessons
session_get_lessons({ severity: "critical" })

// Get workflow lessons
session_get_lessons({ category: "workflow" })

// Search for relevant lessons
session_get_lessons({ query: "git push images" })

// Combine filters
session_get_lessons({
  category: "verification",
  severity: "high",
  limit: 5
})

Consejo profesional: Añade reglas a tu editor (consulta la sección Reglas de IA del Editor más arriba) para capturar automáticamente lecciones cuando los usuarios expresen frustración o correcciones. Esto construye una base de conocimiento que evita errores repetidos.

Catálogo de herramientas

Herramientas MCP.

Consulta la referencia completa de herramientas MCP (insignias PRO y ejemplos de uso común).

Ver referencia de herramientas MCPEl conjunto de herramientas consolidado utiliza ~11 herramientas de dominio para una reducción de tokens del ~75% en comparación con las herramientas granulares heredadas.Leer

Ejemplos de uso

Qué preguntar.

Una vez conectado, puedes preguntar a tu asistente de IA cosas como:

"Recuerda que decidimos usar PostgreSQL para la base de datos"

"¿Cuáles fueron nuestras decisiones anteriores sobre autenticación?"

"Busca en nuestro código cómo manejamos la limitación de tasa de API"

"Muéstrame contexto relacionado sobre el sistema de pagos"

Ejemplos de lecciones

La IA debería capturar lecciones automáticamente cuando expreses frustración o correcciones:

El usuario dice

"¡NO! ¡Hiciste push sin ejecutar las pruebas y ahora producción está roto!"

→ La IA captura la lección con severidad: crítica, categoría: verificación

El usuario dice

"Eso está mal. Siempre usa snake_case para las columnas de la base de datos, no camelCase."

→ La IA captura la lección con severidad: media, categoría: calidad_de_código

El usuario dice

"Prefiero el modo estricto de TypeScript. Por favor, actívalo siempre."

→ La IA captura la lección con severidad: baja, categoría: específica_del_proyecto

Estas lecciones se muestran automáticamente en futuras sesiones cuando se solicita contexto relevante.

Mantenimiento

Mantenerse al día.

Para obtener las últimas funciones, correcciones de errores y mejoras, actualiza el servidor MCP periódicamente:

terminal · terminal · macOS / Linux

curl -fsSL https://contextstream.io/scripts/mcp.sh | bash

terminal · powershell · Windows

irm https://contextstream.io/scripts/mcp.ps1 | iex

El servidor MCP te advertirá automáticamente cuando haya una versión más reciente disponible. Después de actualizar, reinicia tu herramienta de IA para usar la nueva versión.

Solución de problemas

Cuando algo no funciona.

El servidor MCP no inicia

Asegúrate de que contextstream-mcp esté instalado y disponible en tu PATH. Intenta ejecutar contextstream-mcp --version manualmente para comprobar errores.

Errores de autenticación

Verifica que tu clave API sea correcta y no haya expirado. Puedes generar una nueva clave desde tu panel de ContextStream.

Las herramientas no aparecen

Reinicia tu aplicación de IA después de modificar la configuración. Revisa los registros de la aplicación para ver errores de conexión MCP.

No se encuentra el espacio de trabajo (configuración inicial)

Si tu cuenta aún no tiene espacios de trabajo, ContextStream pedirá a tu asistente de IA que te solicite un nombre para el espacio de trabajo. La carpeta actual se creará como un proyecto. Consulta Herramientas MCP para workspace_bootstrap.

Próximos pasos

Continúa explorando.

Configuración de equipoInvita a miembros, comparte contexto.LeerLecciones aprendidasCaptura errores, nunca los repitas.LeerEventos de memoriaAprende sobre los tipos de memoria.LeerBúsqueda semánticaBusca por significado.Leer

{"@context":"https://schema.org","@type":"Organization","name":"ContextStream","url":"https://contextstream.io","logo":"https://contextstream.io/logo.png","description":"Give your AI applications infinite context. Unify code, documentation, and workspace history into a single, queryable intelligence layer with semantic search and knowledge graphs.","sameAs":["https://twitter.com/contextstream","https://github.com/contextstream"]}
{"@context":"https://schema.org","@type":"SoftwareApplication","name":"ContextStream","applicationCategory":"DeveloperApplication","operatingSystem":"Any","description":"Give your AI applications infinite context. Unify code, documentation, and workspace history into a single, queryable intelligence layer with semantic search and knowledge graphs.","offers":{"@type":"Offer","price":"20","priceCurrency":"USD","description":"Pro plan includes a 5-day free trial"},"aggregateRating":{"@type":"AggregateRating","ratingValue":"5","ratingCount":"10"}}