ContextStream MCP Server

oficial

Memória persistente e busca semântica para assistentes de codificação de IA entre sessões

Documentação

Docs · Navegar pelas seções

01 · Assistente de configuração

Um comando, totalmente configurado.

Execute um comando para autenticar (login via navegador/dispositivo), criar uma chave de API, gerar regras e escrever a configuração MCP correta para sua ferramenta (incluindo o esquema servers do 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

Já instalou? Execute novamente o assistente de configuração

terminal · terminal · reexecutar

contextstream-mcp setup

O que faz: escreve a configuração MCP (VS Code servers, Cursor/Cline/etc mcpServers), gera regras (Padrão/Aprimorado) e pode vincular projetos a um espaço de trabalho.

Conjunto de ferramentas consolidado: O assistente configura ~11 ferramentas de domínio consolidadas por padrão (~75% de redução de tokens). Opcional: modo router (~2 meta-ferramentas, o mais compacto). Veja o catálogo completo de ferramentas.

Visualize as alterações sem escrever arquivos: contextstream-mcp setup --dry-run

Fluxos de trabalho em equipe

Memória, habilidades e contexto compartilhados.

Contas de equipe obtêm mais do que projetos compartilhados. Durante contextstream-mcp setup, o assistente detecta a capacidade da equipe e exibe dicas do espaço de trabalho. No seu editor, cada chamada session(action="context") pode incluir recomendações da equipe, dicas de governança, sinais de prioridade e artefatos vinculados.

Escolha o espaço de trabalho compartilhado

Vincule cada repositório ao espaço de trabalho da equipe durante a configuração para que a indexação, decisões e tickets permaneçam alinhados.

Compartilhe habilidades da equipe

skill(action="share", scope="team") publica fluxos de trabalho reutilizáveis que os colegas correspondem automaticamente em session(action="context").

Alterne o escopo de execução

Contas de contexto duplo usam --account-mode=team|personal|auto ou session set_account_mode no MCP.

Acompanhe o trabalho com entidades

Tickets, transferências, incidentes e releases usam referências indexadas — duráveis entre sessões e colegas de equipe.

O remoto hospedado é o padrão. O binário MCP local é apenas para recuperação — defina CONTEXTSTREAM_ALLOW_LOCAL_MCP=1 quando explicitamente necessário. Veja configuração de equipe para convites/funções e a lista de verificação pós-login.

Atalhos da CLI

Comandos não interativos (CI e atualização).

Execute-os sem o assistente interativo — ideal após atualizações, integração da equipe, rotação de credenciais ou alterações no espaço de trabalho. Também exibidos em contextstream-mcp --help.

ComandoQuando usar
contextstream-mcp update-hooks --scope=globalApós atualização ou ao ingressar em um espaço de trabalho da equipe — atualiza os hooks PreToolUse/UserPromptSubmit.
contextstream-mcp update-rules --scope=allRegenera .cursorrules / CLAUDE.md / AGENTS.md com as orientações mais recentes do fluxo de trabalho da equipe.
contextstream-mcp update-configs --scope=globalReescreve as configurações MCP após alterações de chave de API ou espaço de trabalho.
contextstream-mcp migrate-remote --scope=allConverte configurações stdio locais legadas para transporte remoto hospedado.
contextstream-mcp detect-editors --format=jsonScript que detecta quais editores estão instalados (inicialização/CI).
contextstream-mcp generate-configs --transport=remote --preauthEmite payloads de configuração JSON sem escrever arquivos.
contextstream-mcp configure --transcripts=on --scope=allDefine os padrões de captura de transcrição de forma não interativa.

terminal · modo conta · equipe vs pessoal

# 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 · Configuração manual

Configurações por cliente.

Use o formato correto para cada cliente (VS Code usa servers; muitos outros clientes usam mcpServers).

Conjunto de ferramentas consolidado: Por padrão, o servidor expõe ~11 ferramentas de domínio consolidadas (~75% de redução de tokens vs ferramentas granulares legadas). Para ainda menos ferramentas, adicione "CONTEXTSTREAM_PROGRESSIVE_MODE": "true" ao bloco env para ~2 meta-ferramentas roteadoras. Veja o catálogo completo de ferramentas.

Vá para sua ferramenta

Cursor / VS CodeWindsurfCodex CLIOpenCode CLIClaude CodeClaude DesktopClineKilo CodeRoo CodeAntigravity

O que é MCP?

Um protocolo aberto para IA.

O Model Context Protocol (MCP) é um padrão aberto que permite que assistentes de IA se conectem a ferramentas e fontes de dados externas. Com o servidor MCP do ContextStream, suas ferramentas de IA podem:

  • Lembrar conversas e decisões entre sessões
  • Pesquisar sua base de código e documentação semanticamente
  • Construir e consultar grafos de conhecimento
  • Compartilhar contexto entre diferentes ferramentas de IA

Linguagem natural

Apenas pergunte. A IA cuida das ferramentas.

Você não precisa memorizar nomes de ferramentas ou chamá-las diretamente. Apenas descreva o que deseja em linguagem natural e seu assistente de IA usará as ferramentas certas automaticamente.

Apenas pergunte naturalmente

  • · "resumo da sessão"
  • · "o que decidimos sobre autenticação?"
  • · "lembre-se de que estamos usando PostgreSQL"
  • · "pesquise por código de pagamento"

A IA cuida do resto

  • · Encontra contexto relevante automaticamente
  • · Recorda decisões passadas quando necessário
  • · Salva informações importantes na memória
  • · Pesquisa código e documentação

Exemplo · "resumo da sessão"

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

A IA entende sua intenção e chama as ferramentas apropriadas do ContextStream nos bastidores.

Pré-requisitos

O que você precisa.

  • Uma conta ContextStream (o assistente de configuração pode criar uma chave de API via login no navegador).

Enriqueça o contexto

Integrações GitHub + Slack

O MCP fornece à sua IA memória persistente. Conectar o GitHub e o Slack torna essa memória muito mais rica — sua IA pode referenciar automaticamente PRs, issues e discussões da equipe ao responder perguntas.

Enriquecimento automático de contexto

Quando você chama context_smart ou session_smart_search, issues, PRs e discussões relevantes do GitHub e Slack são incluídos automaticamente. Nenhuma ferramenta extra necessária.

GitHubSincroniza issues, PRs, releases e comentários. Decisões são extraídas automaticamente das discussões.SlackSincroniza canais e threads. Conversas de alto engajamento são pontuadas e priorizadas.

Exemplos de prompts

  • · "O que decidimos sobre autenticação?" — encontra decisões de issues do GitHub + threads do Slack
  • · "Mostre-me a atividade recente no sistema de pagamento" — exibe PRs, issues e discussões da equipe
  • · "Que lições aprendemos com a última interrupção?" — recupera insights do Slack e GitHub
  • · "Dê-me um resumo semanal da atividade do GitHub" — usa integration(provider="github", action="summary", ...)
  • · "Pesquise em todas as integrações por discussões sobre migração de banco de dados" — usa integration(provider="all", action="search", ...)
  • · "Dê-me um resumo semanal da equipe de todas as fontes" — usa integration(provider="all", action="summary", ...)

Referência rápida de ações das ferramentas de integração

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

GitHub (provider="github")

  • action="stats" — Estatísticas e status de sincronização
  • action="search" — Pesquisar com filtros de estado/período
  • action="activity" — Feed de atividades (filtro de dias)
  • action="knowledge" — Decisões/lições extraídas
  • action="summary" — Resumo semanal/mensal
  • action="repos" — Listar repositórios sincronizados
  • action="issues" — Listar issues/PRs

Slack (provider="slack")

  • action="stats" — Estatísticas e status de sincronização
  • action="search" — Pesquisar com filtros de canal/período
  • action="discussions" — Threads de alto engajamento
  • action="knowledge" — Decisões/lições extraídas
  • action="summary" — Resumo semanal/mensal
  • action="channels" — Listar canais sincronizados

Entre fontes (provider="all")

  • action="status" — Verificar status de sincronização e saúde de todas as integrações conectadas
  • action="search" — Pesquisar em todas as integrações conectadas em uma única consulta
  • action="summary" — Resumo unificado de atividades de todas as fontes (filtro de dias)
  • action="knowledge" — Obter decisões, lições e insights de todas as fontes

Cliente · Cursor / VS Code

Cursor / VS Code

Cursor e VS Code usam esquemas de configuração MCP diferentes. O Cursor ainda usa um processo MCP local, mas o VS Code/Copilot agora pode usar o MCP hospedado do ContextStream diretamente via HTTP.

terminal · .cursor/mcp.json (projeto) ou ~/.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: instalação remota com um clique

Instale o MCP hospedado do ContextStream e deixe o VS Code lidar com o OAuth no primeiro uso. Nenhum binário local ou chave de API precisa residir em .vscode/mcp.json.

Instalar no VS Code Documentação do MCP do VS Code

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

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

Prefere linha de comando? Adicione o servidor remoto com code --add-mcp

terminal · terminal

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

No primeiro uso, o VS Code deve solicitar a autorização do ContextStream e, em seguida, concluir a configuração automaticamente.

Auto-hospedado? Aponte a mesma configuração remota para a URL do seu próprio gateway MCP em vez de https://mcp.contextstream.io/mcp?default_context_mode=fast.

Cliente · OpenCode CLI

OpenCode CLI

Para usar o ContextStream com o OpenCode CLI, adicione a configuração do servidor MCP ao seu arquivo ~/.config/opencode/opencode.json (ou opencode.json na raiz do seu projeto):

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"
      }
    }
  }
}

Após editar a configuração, reinicie o OpenCode para que ele possa carregar o servidor MCP do ContextStream.

Cliente · Codex CLI

Codex CLI

Para usar o ContextStream com o Codex CLI, adicione a configuração do servidor MCP ao seu arquivo ~/.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"

Após editar a configuração, reinicie o Codex para que ele possa carregar o servidor MCP do ContextStream.

Cliente · Claude Code

Claude Code (CLI)

Adicione o ContextStream ao Claude Code executando este comando no diretório do seu projeto:

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

Ressalva para Windows (Windows nativo, não WSL): use cmd /c contextstream-mcp após --.

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"}}'

Dica: para configurações de equipe, prefira um arquivo .mcp.json versionado (escopo do projeto) em vez de incorporar chaves no histórico do shell.

Isso adiciona o ContextStream ao ~/.claude.json no caminho do seu projeto, tornando-o disponível ao trabalhar nesse diretório.

Opções de escopo do MCP

  • · Local (padrão): Privado para você, apenas projeto atual → armazenado em ~/.claude.json no caminho do projeto.
  • · Usuário (--scope user): Privado para você, todos os projetos → armazenado em ~/.claude.json globalmente.
  • · Projeto (--scope project): Compartilhado com a equipe → armazenado em .mcp.json na raiz do projeto (versionar com git).

Para compartilhamento em equipe, use o escopo de projeto para criar um arquivo .mcp.json que pode ser versionado com git:

terminal · .mcp.json (escopo do projeto)

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

Após adicionar o servidor MCP, reinicie o Claude Code para que as alterações tenham efeito. Verifique se o servidor foi carregado com claude mcp list. Para servidores com escopo de projeto de .mcp.json, o Claude Code solicitará aprovação no primeiro uso.

Cliente · Claude Desktop

Claude Desktop (aplicativo GUI)

Adicione o ContextStream ao aplicativo 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"
      }
    }
  }
}

Após editar a configuração, saia e reinicie o Claude Desktop para que as alterações tenham efeito.

Cliente · Windsurf

Windsurf

Adicione o ContextStream ao Windsurf editando o arquivo de configuração MCP global:

Config: ~/.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"
      }
    }
  }
}

Arquivos de regras

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

O Windsurf suporta hooks para aplicação automática das regras do ContextStream. Após editar a configuração, reinicie o Windsurf para que as alterações tenham efeito.

Cliente · Cline

Cline

Adicione o ContextStream à sua configuração MCP do Cline. Clique no ícone de Servidores MCP no Cline, selecione a aba "Configurar" e clique em "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"
      }
    }
  }
}

Após editar a configuração, reinicie o Cline para que as alterações tenham efeito. Você também pode usar alwaysAllow para aprovar automaticamente ferramentas específicas.

Client · Kilo Code

Kilo Code

Adicione o ContextStream à sua configuração MCP do Kilo Code. Você pode configurar servidores MCP globalmente ou por projeto:

Global: Clique em Configurações → Servidores MCP → Instalado → Editar MCP Global para abrir mcp_settings.json

Projeto: .kilocode/mcp.json na raiz do seu projeto

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

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

As configurações em nível de projeto têm precedência sobre as configurações globais. Reinicie o Kilo Code após editar.

Client · Roo Code

Roo Code

Adicione o ContextStream à sua configuração MCP do Roo Code. Você pode configurar servidores MCP globalmente ou por projeto:

Global: Clique no ícone de configurações → Editar MCP Global para abrir mcp_settings.json

Projeto: .roo/mcp.json na raiz do seu projeto

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

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

As configurações em nível de projeto têm precedência sobre as configurações globais. Reinicie o Roo Code após editar.

Client · Antigravity

Antigravity (Google)

O Antigravity usa arquivos .mcp.json com escopo de projeto, no mesmo formato do Cursor/Claude Desktop:

terminal · .mcp.json (raiz do projeto)

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

Usuários Windows: use o wrapper 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"
      }
    }
  }
}

Arquivos de regras

  • · Global: ~/.gemini/GEMINI.md
  • · Workspace: .agent/rules/contextstream.md

Acesse pelo menu "..." → "MCP Servers" → "View raw config" para verificar sua configuração. Reinicie o Antigravity após editar.

Regras do editor

Melhore o uso automático do ContextStream

Recomendado

O recurso de contexto automático do ContextStream carrega o contexto do espaço de trabalho automaticamente quando você usa qualquer ferramenta do ContextStream. No entanto, os assistentes de IA podem nem sempre salvar decisões ou recuperar contextos passados de forma proativa. Adicionar regras de IA do editor melhora a consistência e garante que a IA capture automaticamente decisões, preferências e contextos importantes ao longo de suas conversas.

Crítico: Convenções de nomenclatura de ferramentas MCP

Diferentes ferramentas de IA usam convenções de nomenclatura diferentes para ferramentas MCP. Usar o formato errado fará com que as ferramentas não sejam encontradas.

Ferramenta de IAFormatoExemplo
Claude Codemcp____mcp__contextstream__session_init
Codex CLI / OpenCode CLI (nome bruto)session_init
Cursor / Windsurf / Cline (nome bruto)session_init
Kilo Code / Roo Code (nome bruto)session_init

Resumo: Apenas o Claude Code usa o prefixo mcp__contextstream__. Todas as outras ferramentas usam nomes de ferramentas brutos.

Você pode adicionar regras do ContextStream em dois níveis: Global (aplica-se a todos os projetos) ou Projeto (aplica-se a um projeto).

Regras globais (todos os projetos)

Adicione-as uma vez e elas se aplicarão a todos os projetos automaticamente:

EditorLocalização das regras globais
CursorConfigurações → Geral → Regras 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) ou pasta pai (ex.: ~/dev/AGENTS.md)
OpenCode CLI~/.config/opencode/AGENTS.md

Regras de projeto (projeto único)

Adicione-as a um projeto específico. Para regras baseadas em pasta no Cursor, defina o modo de ativação como "Sempre Ativo" para que as regras estejam sempre ativas.

EditorLocalização das regras de projeto
Cursor.cursorrules ou .cursor/rules/*.mdc
Windsurf.windsurf/rules/contextstream.md
Clinearquivo .clinerules ou pasta .clinerules/
Kilo Code.kilocode/rules/
Roo Code.roo/rules/contextstream.md ou pasta .roo/rules/
Claude CodeCLAUDE.md na raiz do projeto
Codex CLIAGENTS.md na raiz do projeto
OpenCode CLIAGENTS.md na raiz do projeto
Aider.aider.conf.yml na raiz do projeto

Modos de ativação (Cursor, Kilo Code e Roo Code)

Ao usar regras baseadas em pasta (ex.: .cursor/rules/), cada arquivo de regra tem um modo de ativação:

  • Sempre Ativo — Sempre ativo (recomendado para ContextStream)
  • Manual — Somente quando você @menciona a regra
  • Decisão do Modelo — A IA decide com base na descrição
  • Glob — Ativo para padrões de arquivo correspondentes

Regras globais e arquivos no nível raiz (.cursorrules) estão sempre ativos.

Prefere o assistente de configuração? Execute-o primeiro. Caso contrário, adicione estas regras padrão manualmente. Exemplos para cada editor:

Claude Code

Crie um arquivo CLAUDE.md na raiz do seu projeto ou adicione ao seu ~/.claude/CLAUDE.md global:

terminal · CLAUDE.md (Padrão)

## 🚨 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 regras aprimoradas (detalhado)

terminal · CLAUDE.md (Aprimorado)

## 🚨 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" → Ler arquivo1.ts → Ler arquivo2.ts → Ler arquivo3.ts → finalmente entender


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

mcp__contextstream__search(mode="hybrid", query="implementação da função") → concluído (resultados incluem 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

Crie um arquivo AGENTS.md na raiz do seu projeto (regras de projeto) ou em ~/.codex/AGENTS.md (Codex global) / ~/.config/opencode/AGENTS.md (OpenCode global):

Nomes de ferramentas Codex / OpenCode vs Claude

Codex / OpenCode usam nomes de ferramentas MCP brutos (ex.: session_init). Claude Code usa nomes de ferramentas com namespace (ex.: mcp__contextstream__session_init). Use o formato correto para sua ferramenta de IA.

terminal · AGENTS.md (Padrão)

## 🚨 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 regras aprimoradas (detalhado)

terminal · AGENTS.md (Aprimorado)

## 🚨 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" → Ler arquivo1.ts → Ler arquivo2.ts → Ler arquivo3.ts → finalmente entender


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

search(mode="hybrid", query="implementação da função") → concluído (resultados incluem 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

Crie um arquivo .windsurf/rules/contextstream.md na raiz do seu projeto ou adicione ao seu ~/.codeium/windsurf/memories/global_rules.md global:

terminal · .windsurf/rules/contextstream.md (Padrão)

## 🚨 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 regras aprimoradas (detalhado)

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

## 🚨 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" → Ler arquivo1.ts → Ler arquivo2.ts → Ler arquivo3.ts → finalmente entender


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

search(mode="hybrid", query="implementação da função") → concluído (resultados incluem 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

Crie um arquivo Markdown em .kilocode/rules/:

terminal · .kilocode/rules/contextstream.md (Padrão)

## 🚨 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 regras aprimoradas (detalhado)

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

## 🚨 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" → Ler arquivo1.ts → Ler arquivo2.ts → Ler arquivo3.ts → finalmente entender


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

search(mode="hybrid", query="implementação da função") → concluído (resultados incluem 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

Crie um arquivo .clinerules na raiz do seu projeto ou use a pasta .clinerules/:

terminal · .clinerules (Padrão)

## 🚨 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 regras aprimoradas (detalhado)

terminal · .clinerules (Aprimorado)

## 🚨 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" → Ler arquivo1.ts → Ler arquivo2.ts → Ler arquivo3.ts → finalmente entender


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

search(mode="hybrid", query="implementação da função") → concluído (resultados incluem 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

Crie um arquivo .roo/rules/contextstream.md ou use a pasta .roo/rules/:

terminal · .roo/rules/contextstream.md (Padrão)

## 🚨 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 regras aprimoradas (detalhado)

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

## 🚨 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" → Ler arquivo1.ts → Ler arquivo2.ts → Ler arquivo3.ts → finalmente entender


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

search(mode="hybrid", query="implementação da função") → concluído (resultados incluem 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

Gerar regras automaticamente

Você também pode pedir à IA para gerar essas regras automaticamente dizendo: "Use generate_rules para criar regras do ContextStream para este projeto"

Sistema de lições

Sistema de lições aprendidas

Aprenda com os erros — nunca os repita

O Sistema de Lições captura erros, correções e frustrações do usuário para que os assistentes de IA nunca repitam os mesmos erros. As lições são exibidas automaticamente nas respostas de session_init e context_smart quando relevantes.

Quando capturar lições

As lições devem ser capturadas automaticamente quando qualquer uma destas situações ocorrer:

GatilhoExemploGravidade
Problema em produção"O site está fora do ar por causa dessa alteração"crítica
Frustração do usuário"NÃO! Eu te disse para NÃO fazer isso", "WTF", capsalta
Correção"Isso está errado, você deveria...", "Corrija isso"média
Alteração com quebra"Isso quebrou os testes", "O build falhou"média/alta
Preferência declarada"Eu prefiro assim", "Sempre faça X em vez disso"baixa

Campos da lição explicados

CampoDescriçãoExemplo
titleO que lembrar (imperativo)"Sempre verificar assets no git antes de fazer push"
severitycrítica, alta, média, baixa"crítica" para problemas em produção
categoryfluxo de trabalho, qualidade_código, verificação, comunicação, específico_projeto"fluxo de trabalho"
triggerQual ação causou o problema"Fez push de código referenciando imagens sem commitá-las"
impactO que deu errado"Erros 404 em produção - página de destino quebrada"
preventionComo prevenir no futuro"Executar git status para verificar arquivos não rastreados antes do push"
keywordsPalavras-chave para correspondência em contextos futuros["git", "imagens", "assets", "push"]

Exemplo 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"]
})

Como as lições são exibidas

As lições capturadas são retornadas automaticamente em sessões futuras quando relevantes:

session_init

Lições de gravidade alta e crítica deste espaço de trabalho são incluídas na inicialização da sessão, alertando a IA antes que ela possa cometer o mesmo erro.

context_smart

Quando a IA solicita contexto, as lições que correspondem às palavras-chave da consulta são incluídas. Ex.: perguntar sobre "git push" exibe lições com palavras-chave "git" ou "push".

Recuperando lições

Use session_get_lessons para recuperar e filtrar lições:

terminal · exemplos 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
})

Dica profissional: Adicione regras ao seu editor (veja a seção Regras de IA do Editor acima) para capturar automaticamente lições quando os usuários expressarem frustração ou correções. Isso constrói uma base de conhecimento que evita erros repetidos.

Catálogo de ferramentas

Ferramentas MCP.

Veja a referência completa de ferramentas MCP (emblemas PRO e exemplos comuns de uso).

Ver referência de Ferramentas MCPO conjunto de ferramentas consolidado usa ~11 ferramentas de domínio para ~75% de redução de tokens em relação às ferramentas granulares legadas.Ler

Exemplos de uso

O que perguntar.

Uma vez conectado, você pode perguntar ao seu assistente de IA coisas como:

"Lembre-se de que decidimos usar PostgreSQL para o banco de dados"

"Quais foram nossas decisões anteriores sobre autenticação?"

"Pesquise em nossa base de código como lidamos com limitação de taxa de API"

"Mostre-me o contexto relacionado ao sistema de pagamento"

Exemplos de lições

A IA deve capturar automaticamente lições quando você expressar frustração ou correções:

Usuário diz

"NÃO! Você fez push sem executar os testes e agora a produção está quebrada!"

→ IA captura lição com gravidade: crítica, categoria: verificação

Usuário diz

"Isso está errado. Sempre use snake_case para colunas de banco de dados, não camelCase."

→ IA captura lição com gravidade: média, categoria: qualidade_de_código

Usuário diz

"Prefiro o modo estrito do TypeScript. Por favor, sempre o habilite."

→ IA captura lição com gravidade: baixa, categoria: específica_do_projeto

Essas lições são automaticamente apresentadas em sessões futuras quando o contexto relevante for solicitado.

Manutenção

Mantendo-se atualizado.

Para obter os recursos mais recentes, correções de bugs e melhorias, atualize o servidor MCP periodicamente:

terminal · terminal · macOS / Linux

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

terminal · powershell · Windows

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

O servidor MCP avisará automaticamente quando uma versão mais recente estiver disponível. Após a atualização, reinicie sua ferramenta de IA para usar a nova versão.

Solução de problemas

Quando algo não funciona.

Servidor MCP não inicia

Certifique-se de que contextstream-mcp esteja instalado e disponível no seu PATH. Tente executar contextstream-mcp --version manualmente para verificar erros.

Erros de autenticação

Verifique se sua chave de API está correta e não expirou. Você pode gerar uma nova chave no seu painel do ContextStream.

Ferramentas não aparecem

Reinicie sua aplicação de IA após modificar a configuração. Verifique os logs da aplicação para erros de conexão MCP.

Nenhum espaço de trabalho encontrado (configuração inicial)

Se sua conta ainda não tiver espaços de trabalho, o ContextStream solicitará que seu assistente de IA peça um nome de espaço de trabalho. A pasta atual será criada como um projeto. Veja Ferramentas MCP para workspace_bootstrap.

Próximos passos

Continue explorando.

Configuração de EquipeConvide membros, compartilhe contexto.Ler Lições AprendidasCapture erros, nunca os repita.Ler Eventos de MemóriaAprenda sobre os tipos de memória.Ler Busca SemânticaPesquise por significado.Ler

{"@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"}}