ContextStream MCP Server

chính thức

Bộ nhớ liên tục và tìm kiếm ngữ nghĩa cho các trợ lý lập trình AI qua nhiều phiên làm việc

Tài liệu

Docs · Duyệt các phần

01 · Trình hướng dẫn thiết lập

Một lệnh, cấu hình đầy đủ.

Chạy một lệnh để xác thực (đăng nhập trình duyệt/thiết bị), tạo khóa API, sinh quy tắc và ghi cấu hình MCP chính xác cho công cụ của bạn (bao gồm schema servers của 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

Đã cài đặt? Chạy lại trình hướng dẫn thiết lập

terminal · terminal · chạy lại

contextstream-mcp setup

Chức năng: ghi cấu hình MCP (VS Code servers, Cursor/Cline/v.v mcpServers), sinh quy tắc (Tiêu chuẩn/Nâng cao) và có thể liên kết dự án với không gian làm việc.

Bộ công cụ hợp nhất: Trình hướng dẫn cấu hình ~11 công cụ miền hợp nhất theo mặc định (giảm ~75% token). Tùy chọn: chế độ router (~2 công cụ meta, gọn nhất). Xem danh mục công cụ đầy đủ.

Xem trước thay đổi mà không ghi tệp: contextstream-mcp setup --dry-run

Quy trình làm việc nhóm

Bộ nhớ, kỹ năng và hiển thị ngữ cảnh dùng chung.

Tài khoản nhóm nhận được nhiều hơn chỉ là dự án dùng chung. Trong contextstream-mcp setup, trình hướng dẫn phát hiện khả năng nhóm và hiển thị mẹo không gian làm việc. Trong trình soạn thảo của bạn, mỗi lệnh gọi session(action="context") có thể bao gồm đề xuất nhóm, tín hiệu quản trị, tín hiệu ưu tiên và các thành phần liên kết.

Chọn không gian làm việc dùng chung

Liên kết mỗi kho lưu trữ với không gian làm việc nhóm trong khi thiết lập để việc lập chỉ mục, quyết định và ticket luôn thống nhất.

Chia sẻ kỹ năng nhóm

skill(action="share", scope="team") xuất bản các quy trình làm việc có thể tái sử dụng mà đồng đội tự động khớp trong session(action="context").

Chuyển đổi phạm vi thực thi

Tài khoản ngữ cảnh kép sử dụng --account-mode=team|personal|auto hoặc session set_account_mode trong MCP.

Theo dõi công việc với thực thể

Ticket, bàn giao, sự cố và bản phát hành sử dụng tham chiếu được lập chỉ mục — bền vững qua các phiên và đồng đội.

Máy chủ từ xa là mặc định. MCP nhị phân cục bộ chỉ dùng để khôi phục — đặt CONTEXTSTREAM_ALLOW_LOCAL_MCP=1 khi thực sự cần. Xem thiết lập nhóm để biết mời/vai trò và danh sách kiểm tra sau đăng nhập.

Phím tắt CLI

Lệnh không tương tác (CI & làm mới).

Chạy các lệnh này mà không cần trình hướng dẫn tương tác — lý tưởng sau khi nâng cấp, giới thiệu thành viên nhóm, xoay vòng thông tin xác thực hoặc thay đổi không gian làm việc. Cũng hiển thị trong contextstream-mcp --help.

LệnhKhi nào sử dụng
contextstream-mcp update-hooks --scope=globalSau khi nâng cấp hoặc tham gia không gian làm việc nhóm — làm mới hook PreToolUse/UserPromptSubmit.
contextstream-mcp update-rules --scope=allTạo lại .cursorrules / CLAUDE.md / AGENTS.md với hướng dẫn quy trình làm việc nhóm mới nhất.
contextstream-mcp update-configs --scope=globalGhi lại cấu hình MCP sau khi thay đổi khóa API hoặc không gian làm việc.
contextstream-mcp migrate-remote --scope=allChuyển đổi cấu hình stdio cục bộ cũ sang vận chuyển từ xa được lưu trữ.
contextstream-mcp detect-editors --format=jsonKịch bản kiểm tra trình soạn thảo nào đã được cài đặt (khởi động/CI).
contextstream-mcp generate-configs --transport=remote --preauthXuất payload cấu hình JSON mà không ghi tệp.
contextstream-mcp configure --transcripts=on --scope=allĐặt mặc định ghi lại bản ghi không tương tác.

terminal · chế độ tài khoản · nhóm vs cá nhân

# 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 · Cấu hình thủ công

Cấu hình cho từng máy khách.

Sử dụng định dạng chính xác cho từng máy khách (VS Code dùng servers; nhiều máy khách khác dùng mcpServers).

Bộ công cụ hợp nhất: Theo mặc định, máy chủ hiển thị ~11 công cụ miền hợp nhất (giảm ~75% token so với công cụ chi tiết cũ). Để có ít công cụ hơn nữa, thêm "CONTEXTSTREAM_PROGRESSIVE_MODE": "true" vào khối env để có ~2 công cụ meta định tuyến. Xem danh mục công cụ đầy đủ.

Chuyển đến công cụ của bạn

Cursor / VS CodeWindsurfCodex CLIOpenCode CLIClaude CodeClaude DesktopClineKilo CodeRoo CodeAntigravity

MCP là gì?

Một giao thức mở cho AI.

Model Context Protocol (MCP) là một tiêu chuẩn mở cho phép trợ lý AI kết nối với các công cụ và nguồn dữ liệu bên ngoài. Với máy chủ MCP của ContextStream, các công cụ AI của bạn có thể:

  • Ghi nhớ hội thoại và quyết định qua các phiên
  • Tìm kiếm ngữ nghĩa trong cơ sở mã và tài liệu của bạn
  • Xây dựng và truy vấn đồ thị tri thức
  • Chia sẻ ngữ cảnh giữa các công cụ AI khác nhau

Ngôn ngữ tự nhiên

Chỉ cần yêu cầu. AI sẽ xử lý các công cụ.

Bạn không cần phải nhớ tên công cụ hay gọi chúng trực tiếp. Chỉ cần mô tả điều bạn muốn bằng tiếng Anh đơn giản và trợ lý AI của bạn sẽ tự động sử dụng đúng công cụ.

Chỉ cần yêu cầu tự nhiên

  • · "tóm tắt phiên"
  • · "chúng ta đã quyết định gì về xác thực?"
  • · "nhớ rằng chúng ta đang dùng PostgreSQL"
  • · "tìm kiếm mã thanh toán"

AI xử lý phần còn lại

  • · Tự động tìm ngữ cảnh liên quan
  • · Nhớ lại các quyết định trước đây khi cần
  • · Lưu thông tin quan trọng vào bộ nhớ
  • · Tìm kiếm mã và tài liệu

Ví dụ · "tóm tắt phiên"

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

AI hiểu ý định của bạn và gọi các công cụ ContextStream phù hợp ở phía sau.

Điều kiện tiên quyết

Những gì bạn cần.

  • Một tài khoản ContextStream (trình hướng dẫn thiết lập có thể tạo khóa API qua đăng nhập trình duyệt).

Làm giàu ngữ cảnh

Tích hợp GitHub + Slack

MCP cung cấp cho AI của bạn bộ nhớ bền vững. Kết nối GitHub và Slack làm cho bộ nhớ đó phong phú hơn nhiều — AI của bạn có thể tự động tham chiếu PR, issue và thảo luận nhóm khi trả lời câu hỏi.

Tự động làm giàu ngữ cảnh

Khi bạn gọi context_smart hoặc session_smart_search, các issue GitHub, PR và thảo luận Slack liên quan sẽ tự động được bao gồm. Không cần thêm công cụ nào.

GitHubSync issue, PR, bản phát hành và bình luận. Quyết định được tự động trích xuất từ thảo luận.SlackSync kênh và luồng. Các hội thoại có mức độ tương tác cao được chấm điểm và ưu tiên.

Ví dụ lời nhắc

  • · "Chúng ta đã quyết định gì về xác thực?" — tìm quyết định từ issue GitHub + luồng Slack
  • · "Cho tôi xem hoạt động gần đây trên hệ thống thanh toán" — hiển thị PR, issue và thảo luận nhóm
  • · "Chúng ta đã học được bài học gì từ lần ngừng hoạt động trước?" — truy xuất thông tin chi tiết từ Slack và GitHub
  • · "Cho tôi bản tóm tắt hoạt động GitHub hàng tuần" — sử dụng integration(provider="github", action="summary", ...)
  • · "Tìm kiếm tất cả tích hợp về thảo luận di chuyển cơ sở dữ liệu" — sử dụng integration(provider="all", action="search", ...)
  • · "Cho tôi bản tóm tắt nhóm hàng tuần trên tất cả nguồn" — sử dụng integration(provider="all", action="summary", ...)

Tham khảo nhanh hành động công cụ tích hợp

Sử dụng integration(provider="github|slack|all", action="...")

GitHub (provider="github")

  • action="stats" — Thống kê và trạng thái đồng bộ
  • action="search" — Tìm kiếm với bộ lọc trạng thái/khoảng thời gian
  • action="activity" — Nguồn cấp hoạt động (bộ lọc ngày)
  • action="knowledge" — Quyết định/bài học được trích xuất
  • action="summary" — Tóm tắt hàng tuần/hàng tháng
  • action="repos" — Liệt kê kho lưu trữ đã đồng bộ
  • action="issues" — Liệt kê issue/PR

Slack (provider="slack")

  • action="stats" — Thống kê và trạng thái đồng bộ
  • action="search" — Tìm kiếm với bộ lọc kênh/khoảng thời gian
  • action="discussions" — Luồng có mức độ tương tác cao
  • action="knowledge" — Quyết định/bài học được trích xuất
  • action="summary" — Tóm tắt hàng tuần/hàng tháng
  • action="channels" — Liệt kê kênh đã đồng bộ

Nguồn chéo (provider="all")

  • action="status" — Kiểm tra trạng thái đồng bộ và tình trạng của tất cả tích hợp đã kết nối
  • action="search" — Tìm kiếm trên tất cả tích hợp đã kết nối trong một truy vấn
  • action="summary" — Tóm tắt hoạt động hợp nhất trên tất cả nguồn (bộ lọc ngày)
  • action="knowledge" — Lấy quyết định, bài học và thông tin chi tiết từ tất cả nguồn

Máy khách · Cursor / VS Code

Cursor / VS Code

Cursor và VS Code sử dụng các schema cấu hình MCP khác nhau. Cursor vẫn dùng tiến trình MCP cục bộ, nhưng VS Code/Copilot hiện có thể sử dụng trực tiếp MCP ContextStream được lưu trữ qua HTTP.

terminal · .cursor/mcp.json (dự án) hoặc ~/.cursor/mcp.json (toàn cục)

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

Khuyến nghị cho VS Code / Copilot: cài đặt từ xa một cú nhấp

Cài đặt MCP ContextStream được lưu trữ và để VS Code xử lý OAuth trong lần sử dụng đầu tiên. Không cần nhị phân cục bộ hay khóa API trong .vscode/mcp.json.

Cài đặt trong VS Code Tài liệu MCP VS Code

terminal · .vscode/mcp.json (MCP gốc VS Code, từ xa)

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

Thích dòng lệnh hơn? Thêm máy chủ từ xa với code --add-mcp

terminal · terminal

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

Trong lần sử dụng đầu tiên, VS Code sẽ nhắc bạn ủy quyền ContextStream và sau đó tự động hoàn tất thiết lập.

Tự lưu trữ? Trỏ cùng cấu hình từ xa đến URL cổng MCP của riêng bạn thay vì https://mcp.contextstream.io/mcp?default_context_mode=fast.

Máy khách · OpenCode CLI

OpenCode CLI

Để sử dụng ContextStream với OpenCode CLI, thêm cấu hình máy chủ MCP vào tệp ~/.config/opencode/opencode.json của bạn (hoặc opencode.json trong thư mục gốc dự án):

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

Sau khi chỉnh sửa cấu hình, khởi động lại OpenCode để nó có thể tải máy chủ MCP ContextStream.

Máy khách · Codex CLI

Codex CLI

Để sử dụng ContextStream với Codex CLI, thêm cấu hình máy chủ MCP vào tệp ~/.codex/config.toml của bạn:

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"

Sau khi chỉnh sửa cấu hình, khởi động lại Codex để nó có thể tải máy chủ MCP ContextStream.

Máy khách · Claude Code

Claude Code (CLI)

Thêm ContextStream vào Claude Code bằng cách chạy lệnh này từ thư mục dự án của bạn:

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

Lưu ý cho Windows (Windows gốc, không phải WSL): sử dụng cmd /c contextstream-mcp sau --.

Thay thế: 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"}}'

Mẹo: đối với thiết lập nhóm, nên dùng tệp .mcp.json đã commit (phạm vi dự án) thay vì nhúng khóa vào lịch sử shell.

Thao tác này thêm ContextStream vào ~/.claude.json trong đường dẫn dự án của bạn, giúp nó khả dụng khi làm việc trong thư mục đó.

Tùy chọn phạm vi MCP

  • · Cục bộ (mặc định): Riêng tư cho bạn, chỉ dự án hiện tại → lưu trong ~/.claude.json trong đường dẫn dự án.
  • · Người dùng (--scope user): Riêng tư cho bạn, tất cả dự án → lưu trong ~/.claude.json toàn cục.
  • · Dự án (--scope project): Dùng chung với nhóm → lưu trong .mcp.json ở thư mục gốc dự án (commit lên git).

Để chia sẻ nhóm, sử dụng phạm vi dự án để tạo tệp .mcp.json có thể commit lên git:

terminal · .mcp.json (phạm vi dự án)

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

Sau khi thêm máy chủ MCP, khởi động lại Claude Code để thay đổi có hiệu lực. Xác minh máy chủ đã được tải với claude mcp list. Đối với máy chủ phạm vi dự án từ .mcp.json, Claude Code sẽ nhắc phê duyệt trong lần sử dụng đầu tiên.

Máy khách · Claude Desktop

Claude Desktop (ứng dụng GUI)

Thêm ContextStream vào ứng dụng 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"
      }
    }
  }
}

Sau khi chỉnh sửa cấu hình, thoát và khởi động lại Claude Desktop để thay đổi có hiệu lực.

Máy khách · Windsurf

Windsurf

Thêm ContextStream vào Windsurf bằng cách chỉnh sửa tệp cấu hình MCP toàn cục:

Cấu hình: ~/.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"
      }
    }
  }
}

Tệp quy tắc

  • · Toàn cục: ~/.codeium/windsurf/memories/global_rules.md
  • · Dự án: .windsurf/rules/contextstream.md

Windsurf hỗ trợ hook để tự động thực thi các quy tắc ContextStream. Sau khi chỉnh sửa cấu hình, khởi động lại Windsurf để thay đổi có hiệu lực.

Máy khách · Cline

Cline

Thêm ContextStream vào cấu hình MCP Cline của bạn. Nhấp vào biểu tượng MCP Servers trong Cline, chọn tab "Configure", sau đó nhấp "Configure MCP Servers" để chỉnh sửa:

terminal · cline_mcp_settings.json

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

Sau khi chỉnh sửa cấu hình, hãy khởi động lại Cline để các thay đổi có hiệu lực. Bạn cũng có thể sử dụng alwaysAllow để tự động phê duyệt các công cụ cụ thể.

Client · Kilo Code

Kilo Code

Thêm ContextStream vào cấu hình MCP của Kilo Code. Bạn có thể cấu hình máy chủ MCP toàn cục hoặc theo từng dự án:

Toàn cục: Nhấp vào Cài đặt → MCP Servers → Installed → Edit Global MCP để mở mcp_settings.json

Dự án: .kilocode/mcp.json trong thư mục gốc của dự án

terminal · .kilocode/mcp.json (hoặc mcp_settings.json)

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

Cấu hình cấp dự án được ưu tiên hơn cấu hình toàn cục. Khởi động lại Kilo Code sau khi chỉnh sửa.

Client · Roo Code

Roo Code

Thêm ContextStream vào cấu hình MCP của Roo Code. Bạn có thể cấu hình máy chủ MCP toàn cục hoặc theo từng dự án:

Toàn cục: Nhấp vào biểu tượng cài đặt → Edit Global MCP để mở mcp_settings.json

Dự án: .roo/mcp.json trong thư mục gốc của dự án

terminal · .roo/mcp.json (hoặc mcp_settings.json)

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

Cấu hình cấp dự án được ưu tiên hơn cấu hình toàn cục. Khởi động lại Roo Code sau khi chỉnh sửa.

Client · Antigravity

Antigravity (Google)

Antigravity sử dụng các tệp .mcp.json phạm vi dự án với định dạng giống như Cursor/Claude Desktop:

terminal · .mcp.json (thư mục gốc dự án)

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

Người dùng Windows: sử dụng trình bao bọc 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"
      }
    }
  }
}

Tệp quy tắc

  • · Toàn cục: ~/.gemini/GEMINI.md
  • · Không gian làm việc: .agent/rules/contextstream.md

Truy cập qua menu "..." → "MCP Servers" → "View raw config" để xác minh cấu hình của bạn. Khởi động lại Antigravity sau khi chỉnh sửa.

Quy tắc trình soạn thảo

Cải thiện việc sử dụng ContextStream tự động

Khuyến nghị

Tính năng tự động ngữ cảnh của ContextStream tự động tải ngữ cảnh không gian làm việc khi bạn sử dụng bất kỳ công cụ ContextStream nào. Tuy nhiên, các trợ lý AI có thể không phải lúc nào cũng chủ động lưu quyết định hoặc nhớ lại ngữ cảnh trước đó. Việc thêm quy tắc AI của trình soạn thảo sẽ cải thiện tính nhất quán và đảm bảo AI tự động nắm bắt các quyết định, tùy chọn và ngữ cảnh quan trọng trong suốt cuộc trò chuyện của bạn.

Quan trọng: Quy ước đặt tên công cụ MCP

Các công cụ AI khác nhau sử dụng quy ước đặt tên khác nhau cho các công cụ MCP. Sử dụng sai định dạng sẽ khiến không tìm thấy công cụ.

Công cụ AIĐịnh dạngVí dụ
Claude Codemcp____mcp__contextstream__session_init
Codex CLI / OpenCode CLI (tên thô)session_init
Cursor / Windsurf / Cline (tên thô)session_init
Kilo Code / Roo Code (tên thô)session_init

Tóm tắt: Chỉ Claude Code sử dụng tiền tố mcp__contextstream__. Tất cả các công cụ khác sử dụng tên công cụ thô.

Bạn có thể thêm quy tắc ContextStream ở hai cấp: Toàn cục (áp dụng cho tất cả dự án) hoặc Dự án (áp dụng cho một dự án).

Quy tắc toàn cục (tất cả dự án)

Thêm những quy tắc này một lần và chúng sẽ tự động áp dụng cho mọi dự án:

Trình soạn thảoVị trí quy tắc toàn cục
CursorCài đặt → Chung → Rules for AI
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 (toàn cục) hoặc thư mục cha (ví dụ: ~/dev/AGENTS.md)
OpenCode CLI~/.config/opencode/AGENTS.md

Quy tắc dự án (dự án đơn lẻ)

Thêm những quy tắc này vào một dự án cụ thể. Đối với quy tắc dựa trên thư mục của Cursor, hãy đặt chế độ kích hoạt thành "Always On" để các quy tắc luôn hoạt động.

Trình soạn thảoVị trí quy tắc dự án
Cursor.cursorrules hoặc .cursor/rules/*.mdc
Windsurf.windsurf/rules/contextstream.md
Clinetệp .clinerules hoặc thư mục .clinerules/
Kilo Code.kilocode/rules/
Roo Code.roo/rules/contextstream.md hoặc thư mục .roo/rules/
Claude CodeCLAUDE.md trong thư mục gốc dự án
Codex CLIAGENTS.md trong thư mục gốc dự án
OpenCode CLIAGENTS.md trong thư mục gốc dự án
Aider.aider.conf.yml trong thư mục gốc dự án

Chế độ kích hoạt (Cursor, Kilo Code & Roo Code)

Khi sử dụng quy tắc dựa trên thư mục (ví dụ: .cursor/rules/), mỗi tệp quy tắc có một chế độ kích hoạt:

  • Always On — Luôn hoạt động (khuyến nghị cho ContextStream)
  • Manual — Chỉ khi bạn @mention quy tắc
  • Model Decision — AI quyết định dựa trên mô tả
  • Glob — Hoạt động cho các mẫu tệp phù hợp

Quy tắc toàn cục và tệp cấp gốc (.cursorrules) luôn hoạt động.

Thích trình hướng dẫn thiết lập hơn? Chạy nó trước. Nếu không, hãy thêm các quy tắc tiêu chuẩn này theo cách thủ công. Ví dụ cho từng trình soạn thảo:

Claude Code

Tạo tệp CLAUDE.md trong thư mục gốc dự án hoặc thêm vào ~/.claude/CLAUDE.md toàn cục của bạn:

terminal · CLAUDE.md (Tiêu chuẩn)

## 🚨 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

Hiển thị quy tắc nâng cao (chi tiết)

terminal · CLAUDE.md (Nâng cao)

## 🚨 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" → Đọc file1.ts → Đọc file2.ts → Đọc file3.ts → cuối cùng mới hiểu


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

mcp__contextstream__search(mode="hybrid", query="function implementation") → xong (kết quả bao gồm ngữ cảnh)


**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

Tạo tệp AGENTS.md trong thư mục gốc dự án (quy tắc dự án) hoặc trong ~/.codex/AGENTS.md (Codex toàn cục) / ~/.config/opencode/AGENTS.md (OpenCode toàn cục):

Tên công cụ Codex / OpenCode so với Claude

Codex / OpenCode sử dụng tên công cụ MCP thô (ví dụ: session_init). Claude Code sử dụng tên công cụ có không gian tên (ví dụ: mcp__contextstream__session_init). Sử dụng định dạng chính xác cho công cụ AI của bạn.

terminal · AGENTS.md (Tiêu chuẩn)

## 🚨 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

Hiển thị quy tắc nâng cao (chi tiết)

terminal · AGENTS.md (Nâng cao)

## 🚨 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" → Đọc file1.ts → Đọc file2.ts → Đọc file3.ts → cuối cùng mới hiểu


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

search(mode="hybrid", query="function implementation") → xong (kết quả bao gồm ngữ cảnh)


**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

Tạo tệp .windsurf/rules/contextstream.md trong thư mục gốc dự án hoặc thêm vào ~/.codeium/windsurf/memories/global_rules.md toàn cục của bạn:

terminal · .windsurf/rules/contextstream.md (Tiêu chuẩn)

## 🚨 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

Hiển thị quy tắc nâng cao (chi tiết)

terminal · .windsurf/rules/contextstream.md (Nâng cao)

## 🚨 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" → Đọc file1.ts → Đọc file2.ts → Đọc file3.ts → cuối cùng mới hiểu


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

search(mode="hybrid", query="function implementation") → xong (kết quả bao gồm ngữ cảnh)


**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

Tạo tệp Markdown trong .kilocode/rules/:

terminal · .kilocode/rules/contextstream.md (Tiêu chuẩn)

## 🚨 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

Hiển thị quy tắc nâng cao (chi tiết)

terminal · .kilocode/rules/contextstream.md (Nâng cao)

## 🚨 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" → Đọc file1.ts → Đọc file2.ts → Đọc file3.ts → cuối cùng mới hiểu


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

search(mode="hybrid", query="function implementation") → xong (kết quả bao gồm ngữ cảnh)


**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

Tạo tệp .clinerules trong thư mục gốc dự án hoặc sử dụng thư mục .clinerules/:

terminal · .clinerules (Tiêu chuẩn)

## 🚨 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

Hiển thị quy tắc nâng cao (chi tiết)

terminal · .clinerules (Nâng cao)

## 🚨 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" → Đọc file1.ts → Đọc file2.ts → Đọc file3.ts → cuối cùng mới hiểu


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

search(mode="hybrid", query="function implementation") → xong (kết quả bao gồm ngữ cảnh)


**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

Tạo tệp .roo/rules/contextstream.md hoặc sử dụng thư mục .roo/rules/:

terminal · .roo/rules/contextstream.md (Tiêu chuẩn)

## 🚨 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

Hiển thị quy tắc nâng cao (chi tiết)

terminal · .roo/rules/contextstream.md (Nâng cao)

## 🚨 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" → Đọc file1.ts → Đọc file2.ts → Đọc file3.ts → cuối cùng mới hiểu


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

search(mode="hybrid", query="function implementation") → xong (kết quả bao gồm ngữ cảnh)


**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

Tự động tạo quy tắc

Bạn cũng có thể yêu cầu AI tạo các quy tắc này tự động bằng cách nói: "Sử dụng generate_rules để tạo quy tắc ContextStream cho dự án này"

Hệ thống bài học

Hệ thống bài học kinh nghiệm

Học từ sai lầm — không bao giờ lặp lại chúng

Hệ thống Bài học nắm bắt các sai lầm, sửa chữa và sự thất vọng của người dùng để các trợ lý AI không bao giờ lặp lại cùng một lỗi. Các bài học được tự động hiển thị trong phản hồi session_initcontext_smart khi có liên quan.

Khi nào nên nắm bắt bài học

Các bài học nên được tự động nắm bắt khi xảy ra bất kỳ tình huống nào sau đây:

Kích hoạtVí dụMức độ nghiêm trọng
Sự cố sản xuất"Trang web bị sập vì thay đổi đó"nghiêm trọng
Người dùng thất vọng"KHÔNG! Tôi đã bảo bạn ĐỪNG làm thế", "WTF", viết hoacao
Sửa chữa"Sai rồi, bạn nên...", "Sửa cái này"trung bình
Thay đổi gây hỏng"Điều này làm hỏng bài kiểm tra", "Bản dựng thất bại"trung bình/cao
Tùy chọn được nêu"Tôi thích cách này hơn", "Luôn làm X thay vì"thấp

Giải thích các trường bài học

TrườngMô tảVí dụ
titleĐiều cần nhớ (mệnh lệnh)"Luôn xác minh tài sản trong git trước khi đẩy"
severitynghiêm trọng, cao, trung bình, thấp"nghiêm trọng" cho các sự cố sản xuất
categoryquy trình làm việc, chất lượng mã, xác minh, giao tiếp, cụ thể dự án"quy trình làm việc"
triggerHành động nào gây ra vấn đề"Đẩy mã tham chiếu hình ảnh mà không commit chúng"
impactĐiều gì đã sai"Lỗi 404 sản xuất - trang đích bị hỏng"
preventionCách ngăn chặn trong tương lai"Chạy git status để kiểm tra tệp chưa được theo dõi trước khi đẩy"
keywordsTừ khóa để khớp trong ngữ cảnh tương lai["git", "hình ảnh", "tài sản", "đẩy"]

Ví dụ đầy đủ

terminal · session_capture_lesson

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

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

Cách các bài học được hiển thị

Các bài học đã nắm bắt được tự động trả về trong các phiên làm việc tương lai khi có liên quan:

session_init

Các bài học có mức độ nghiêm trọng cao và nghiêm trọng từ không gian làm việc này được bao gồm trong khởi tạo phiên, cảnh báo AI trước khi nó có thể mắc cùng một sai lầm.

context_smart

Khi AI yêu cầu ngữ cảnh, các bài học khớp với từ khóa truy vấn sẽ được bao gồm. Ví dụ: hỏi về "git push" sẽ hiển thị các bài học có từ khóa "git" hoặc "push".

Truy xuất bài học

Sử dụng session_get_lessons để truy xuất và lọc bài học:

terminal · session_get_lessons ví dụ

// 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
})

Mẹo chuyên nghiệp: Thêm quy tắc vào trình soạn thảo của bạn (xem phần Quy tắc AI cho Trình soạn thảo ở trên) để tự động ghi lại bài học khi người dùng bày tỏ sự thất vọng hoặc đưa ra chỉnh sửa. Điều này xây dựng một cơ sở kiến thức giúp ngăn ngừa các lỗi lặp lại.

Danh mục công cụ

Công cụ MCP.

Xem tài liệu tham khảo đầy đủ về công cụ MCP (huy hiệu PRO và các ví dụ sử dụng phổ biến).

Xem tài liệu tham khảo Công cụ MCPBộ công cụ hợp nhất sử dụng ~11 công cụ miền giúp giảm ~75% token so với các công cụ chi tiết cũ.Đọc

Ví dụ sử dụng

Nên hỏi gì.

Sau khi kết nối, bạn có thể hỏi trợ lý AI của mình những điều như:

"Nhớ rằng chúng ta đã quyết định sử dụng PostgreSQL cho cơ sở dữ liệu"

"Các quyết định trước đây của chúng ta về xác thực là gì?"

"Tìm kiếm trong codebase cách chúng ta xử lý giới hạn tốc độ API"

"Hiển thị ngữ cảnh liên quan về hệ thống thanh toán"

Ví dụ bài học

AI sẽ tự động ghi lại bài học khi bạn bày tỏ sự thất vọng hoặc đưa ra chỉnh sửa:

Người dùng nói

"KHÔNG! Bạn đã đẩy code mà không chạy kiểm thử và giờ production bị hỏng!"

→ AI ghi lại bài học với mức độ: nghiêm trọng, danh mục: xác minh

Người dùng nói

"Sai rồi. Luôn dùng snake_case cho cột cơ sở dữ liệu, không phải camelCase."

→ AI ghi lại bài học với mức độ: trung bình, danh mục: chất_lượng_code

Người dùng nói

"Tôi thích chế độ nghiêm ngặt của TypeScript. Làm ơn luôn bật nó."

→ AI ghi lại bài học với mức độ: thấp, danh mục: dự_án_cụ_thể

Những bài học này sẽ tự động xuất hiện trong các phiên làm việc sau khi ngữ cảnh liên quan được yêu cầu.

Bảo trì

Luôn cập nhật.

Để có các tính năng, bản sửa lỗi và cải tiến mới nhất, hãy cập nhật máy chủ MCP định kỳ:

terminal · terminal · macOS / Linux

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

terminal · powershell · Windows

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

Máy chủ MCP sẽ tự động cảnh báo khi có phiên bản mới hơn. Sau khi cập nhật, khởi động lại công cụ AI của bạn để sử dụng phiên bản mới.

Khắc phục sự cố

Khi có điều gì đó không hoạt động.

Máy chủ MCP không khởi động

Đảm bảo contextstream-mcp đã được cài đặt và có sẵn trong PATH của bạn. Thử chạy contextstream-mcp --version thủ công để kiểm tra lỗi.

Lỗi xác thực

Xác minh khóa API của bạn là chính xác và chưa hết hạn. Bạn có thể tạo khóa mới từ bảng điều khiển ContextStream.

Công cụ không xuất hiện

Khởi động lại ứng dụng AI của bạn sau khi sửa đổi cấu hình. Kiểm tra nhật ký ứng dụng để tìm lỗi kết nối MCP.

Không tìm thấy không gian làm việc (thiết lập lần đầu)

Nếu tài khoản của bạn chưa có không gian làm việc nào, ContextStream sẽ nhắc trợ lý AI hỏi bạn tên không gian làm việc. Thư mục hiện tại sẽ được tạo thành một dự án. Xem Công cụ MCP cho workspace_bootstrap.

Các bước tiếp theo

Tiếp tục khám phá.

Thiết lập NhómMời thành viên, chia sẻ ngữ cảnh.Đọc Bài học Kinh nghiệmGhi lại sai lầm, không bao giờ lặp lại.Đọc Sự kiện Bộ nhớTìm hiểu về các loại bộ nhớ.Đọc Tìm kiếm Ngữ nghĩaTìm kiếm theo ý nghĩa.Đọc

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