Skip to main content
Glama
SammySnake-d

Fast Context MCP

by SammySnake-d

Fast Context MCP

Семантический поиск по коду на базе ИИ в виде MCP-инструмента — на основе реверс-инжиниринга протокола SWE-grep от Windsurf.

Любой MCP-совместимый клиент (Claude Code, Claude Desktop, Cursor и т.д.) может использовать его для поиска по кодовым базам с помощью запросов на естественном языке. Все инструменты поставляются через npm — системные зависимости не требуются (ripgrep через @vscode/ripgrep, tree через tree-node-cli). Работает на macOS, Windows и Linux.

Как это работает

You: "where is the authentication logic?"
         │
         ▼
┌─────────────────────────┐
│  Fast Context MCP       │
│  (local MCP server)     │
│                         │
│  1. Maps project → /codebase
│  2. Sends query to Windsurf Devstral API
│  3. AI generates rg/readfile/tree commands
│  4. Executes commands locally (built-in rg)
│  5. Returns results to AI
│  6. Repeats for N rounds
│  7. Returns file paths + line ranges
│     + suggested search keywords
└─────────────────────────┘
         │
         ▼
Found 3 relevant files.
  [1/3] /project/src/auth/handler.py (L10-60)
  [2/3] /project/src/middleware/jwt.py (L1-40)
  [3/3] /project/src/models/user.py (L20-80)

Suggested search keywords:
  authenticate, jwt.*verify, session.*token

Related MCP server: code-rag

Предварительные требования

  • Node.js >= 18

  • Учётная запись Windsurf — бесплатного тарифа достаточно (нужен для API-ключа)

Устанавливать ripgrep не нужно — он поставляется вместе с @vscode/ripgrep.

Установка

Вариант 1: npm (рекомендуется)

# Latest stable release
npm install @sammysnake/fast-context-mcp

# Or beta/next release
npm install @sammysnake/fast-context-mcp@next

Вариант 2: из исходников

git clone https://github.com/SammySnake-d/fast-context-mcp.git
cd fast-context-mcp
npm install

Настройка

1. Получите свой API-ключ Windsurf/Devin

Сервер автоматически извлекает API-ключ из Devin CLI/Desktop или из устаревшей установки Windsurf. Также вы можете использовать MCP-инструмент extract_windsurf_key после настройки или задать WINDSURF_API_KEY вручную.

Учётные данные Desktop обнаруживаются в следующем порядке: Devin, устаревший Deviv, затем Windsurf.

Платформа

Путь

macOS

~/Library/Application Support/Devin/User/globalStorage/state.vscdb

Windows

%APPDATA%/Devin/User/globalStorage/state.vscdb

Linux

~/.config/Devin/User/globalStorage/state.vscdb

В WSL/Linux сервер сначала проверяет учётные данные Devin CLI в ~/.local/share/devin/credentials.toml. Если ключ, извлечённый в Windows, возвращает 403 внутри WSL, выполните devin login внутри WSL и повторите попытку.

2. Настройка MCP-клиента

Claude Code

Добавьте в ~/.claude.json в раздел mcpServers:

{
  "fast-context": {
    "command": "npx",
    "args": ["-y", "--prefer-online", "@sammysnake/fast-context-mcp"],
    "env": {
      "WINDSURF_API_KEY": "sk-ws-01-xxxxx"
    }
  }
}

Для бета/следующего релиза:

{
  "fast-context": {
    "command": "npx",
    "args": ["-y", "--prefer-online", "@sammysnake/fast-context-mcp@next"],
    "env": {
      "WINDSURF_API_KEY": "sk-ws-01-xxxxx"
    }
  }
}

Claude Desktop

Добавьте в claude_desktop_config.json в раздел mcpServers:

{
  "fast-context": {
    "command": "npx",
    "args": ["-y", "--prefer-online", "@sammysnake/fast-context-mcp"],
    "env": {
      "WINDSURF_API_KEY": "sk-ws-01-xxxxx"
    }
  }
}

Для бета/следующего релиза:

{
  "fast-context": {
    "command": "npx",
    "args": ["-y", "--prefer-online", "@sammysnake/fast-context-mcp@next"],
    "env": {
      "WINDSURF_API_KEY": "sk-ws-01-xxxxx"
    }
  }
}

Если WINDSURF_API_KEY не задан, сервер автоматически определит его из вашей локальной установки Windsurf.

Переменные окружения

Переменная

По умолчанию

Описание

WINDSURF_API_KEY

(автоопределение)

API-ключ Windsurf

FC_MAX_TURNS

3

Раундов поиска на запрос (больше = глубже, но медленнее)

FC_MAX_COMMANDS

8

Макс. параллельных команд за раунд

FC_TIMEOUT_MS

30000

Connect-Timeout-Ms для потоковых запросов

FC_HIDE_EXTRACT_WINDSURF_KEY_TOOL

false

Скрывает extract_windsurf_key из MCP-инструментов, если задано 1, true, yes или on

FC_RESULT_MAX_LINES

50

Макс. строк в выводе команды (усечение)

FC_LINE_MAX_CHARS

250

Макс. символов в строке вывода (усечение)

FC_CACHE_DISABLED

(не задано)

Отключает кэш результатов в памяти с помощью 1, true, yes или on

FC_CACHE_TTL_MS

300000

TTL кэша результатов; <=0 отключает кэширование

FC_CACHE_MAX_ENTRIES

200

Максимальное количество записей в кэше в памяти

FC_ALLOW_INSECURE_TLS

(не задано)

Устанавливайте 1 только когда доверенный корпоративный прокси требует отключённой проверки TLS

WS_MODEL

MODEL_SWE_1_6_FAST

Название модели Windsurf

WS_APP_VER

1.48.2

Версия приложения Windsurf (метаданные протокола)

WS_LS_VER

1.9544.35

Версия языкового сервера Windsurf (метаданные протокола)

Доступные модели

Модель можно изменить, задав WS_MODEL (см. переменные окружения выше).

Доступные модели

По умолчанию: MODEL_SWE_1_6_FAST — максимальная скорость, самые богатые ключевые слова grep, наилучшая гранулярность местоположений.

MCP-инструменты

Семантический поиск по коду на базе ИИ с настраиваемыми параметрами.

Параметр

Тип

Обязательный

По умолчанию

Описание

query

string

Да

—

Поисковый запрос на естественном языке

project_path

string

Нет

cwd

Абсолютный путь к корню проекта

tree_depth

integer

Нет

3

Глубина дерева каталогов для карты репозитория (1-6). Больше = больше контекста, но больше полезная нагрузка. Автоматически откатывается на меньшую глубину, если дерево превышает 250 КБ. Используйте 1-2 для огромных монорепозиториев (>5000 файлов), 3 для большинства проектов, 4-6 для небольших проектов.

max_turns

integer

Нет

3

Раундов поиска (1-5). Больше = глубже поиск, но медленнее. Используйте 1-2 для простых запросов, 3 для большинства запросов, 4-5 для сложного анализа.

max_results

integer

Нет

10

Максимальное количество файлов для возврата (1-30). Меньше = более сфокусированно, больше = более широкое исследование.

exclude_paths

string[]

Нет

[]

Шаблоны каталогов/файлов, исключённые из карты репозитория и контекста поиска.

Возвращает:

  1. Релевантные файлы с диапазонами строк

  2. Предлагаемые ключевые слова для поиска (паттерны rg, использованные при ИИ-поиске)

  3. Диагностические метаданные (строка [config], показывающая фактическую использованную tree_depth, размер дерева и произошёл ли откат)

Пример вывода:

Found 3 relevant files.

  [1/3] /project/src/auth/handler.py (L10-60, L120-180)
  [2/3] /project/src/middleware/jwt.py (L1-40)
  [3/3] /project/src/models/user.py (L20-80)

grep keywords: authenticate, jwt.*verify, session.*token

[config] tree_depth=3, tree_size=12.5KB, max_turns=3

Вывод ошибок содержит подсказки, зависящие от статуса:

Error: Request failed: HTTP 403

[hint] 403 Forbidden: Authentication failed. The API key may be expired or revoked.
Try re-extracting with extract_windsurf_key, or set a fresh WINDSURF_API_KEY env var.
If you are running inside WSL, run `devin login` inside WSL so `~/.local/share/devin/credentials.toml` exists.
Error: Request failed: HTTP 413

[diagnostic] tree_depth_used=3, tree_size=280.0KB (auto fell back from requested depth)
[hint] If the error is payload-related, try a lower tree_depth value.

extract_windsurf_key

Извлекает API-ключ Windsurf из локальной установки. Без параметров.

Установите FC_HIDE_EXTRACT_WINDSURF_KEY_TOOL=1 при запуске MCP-сервера, чтобы скрыть этот инструмент из tools/list. Это не отключает внутреннее автоматическое определение API-ключа для fast_context_search.

Структура проекта

fast-context-mcp/
├── package.json
├── src/
│   ├── server.mjs        # MCP server entry point
│   ├── core.mjs          # Auth, message building, streaming, search loop
│   ├── executor.mjs      # Tool executor: rg, readfile, tree, ls, glob
│   ├── extract-key.mjs   # Windsurf API Key extraction (SQLite)
│   ├── path-safety.mjs   # Project-root confinement for model-selected paths
│   ├── response-repair.mjs # Malformed response repair and evidence salvage
│   ├── shared.mjs        # Repository map, answer parser, prompt builder
│   ├── cache.mjs         # In-memory search-result cache
│   └── protobuf.mjs      # Protobuf encoder/decoder + Connect-RPC frames
├── test/                 # Unit and MCP stdio integration tests
├── README.md
└── LICENSE

Как работает поиск

  1. Каталог проекта сопоставляется с виртуальным путём /codebase

  2. Дерево каталогов генерируется на запрошенной глубине (по умолчанию L=3), с автоматическим откатом на меньшую глубину, если дерево превышает 250 КБ

  3. Запрос + дерево каталогов отправляются модели Devstral от Windsurf через Connect-RPC/Protobuf

  4. Devstral генерирует команды инструментов (ripgrep, чтение файлов, tree, ls, glob)

  5. Команды выполняются локально параллельно (до FC_MAX_COMMANDS за раунд)

  6. Результаты отправляются обратно Devstral для следующего раунда

  7. После max_turns раундов Devstral возвращает пути к файлам + диапазоны строк

  8. Все паттерны rg, использованные во время поиска, собираются как предлагаемые ключевые слова

  9. Добавляются диагностические метаданные, чтобы помочь вызывающему ИИ настроить параметры

Технические детали

  • Протокол: Connect-RPC через HTTP/1.1, кодирование Protobuf, сжатие gzip

  • Модель: Devstral (MODEL_SWE_1_6_FAST, настраивается)

  • Локальные инструменты: rg (поставляется через @vscode/ripgrep), readfile (Node.js fs), tree (tree-node-cli), ls (Node.js fs), glob (Node.js fs)

  • Аутентификация: API-ключ → JWT (автоматически получается для каждой сессии)

  • Среда выполнения: Node.js >= 18 (ESM)

Зависимости

Пакет

Назначение

@modelcontextprotocol/sdk

Каркас MCP-сервера

@vscode/ripgrep

Встроенный бинарный файл ripgrep (кроссплатформенный)

tree-node-cli

Кроссплатформенное дерево каталогов (заменяет системный tree)

sql.js

Чтение локальной SQLite-базы Devin/Windsurf без нативного этапа сборки

zod (^3.25.76)

Проверка схемы; позволяет избежать неполного tar-архива 3.25.0, который отдают некоторые зеркала npm

Дружественные ссылки

Лицензия

MIT

Available Tools

2 tools
extract_windsurf_keyA

Extract Windsurf API Key from local installation. Auto-detects OS (macOS/Windows/Linux) and reads the API key from Windsurf's local database. Set the result as WINDSURF_API_KEY env var.

ParametersJSON Schema
NameRequiredDescriptionDefault

No parameters

TDQS

A4.4/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the burden. It discloses OS auto-detection, reading from the local database, and setting the result as an env var. It does not mention error cases or prerequisites, but it is transparent about its main side effect.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is two sentences, front-loaded with the primary action, and every sentence adds value without redundancy.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a zero-parameter tool with no output schema, the description covers the core function and side effect. It lacks mention of failure cases or requirements, but is otherwise complete for its simplicity.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The tool has zero parameters and 100% schema coverage (empty), so the baseline is 4. No additional parameter explanation is needed.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states 'Extract Windsurf API Key from local installation', a specific verb+resource with source. It distinguishes itself from the unrelated sibling fast_context_search.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides clear context for when to use the tool (to get the API key and set it as an env var), and the sibling tool is unrelated, so no exclusions are needed. It does not explicitly list alternatives, but usage is apparent.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

  1. 1 tool updatev1.2.1
    • Changedfast_context_search4 fields changed
      • addedInput schema / properties / exclude_paths
        Added value: +{
        +  "default": [],
        +  "description": "Directory/file patterns to exclude from tree and search context. Useful for reducing payload size on large repos. Examples: ['node_modules', 'dist', '.git', 'build', 'coverage', '*.min.*']",
        +  "items": {
        +    "type": "string"
        +  },
        +  "type": "array"
        +}
      • addedInput schema / properties / max_results
        Added value: +{
        +  "default": 10,
        +  "description": "Maximum number of files to return. Default 10. Use a smaller value (3-5) for focused queries. Use a larger value (15-30) for broad exploration queries.",
        +  "maximum": 30,
        +  "minimum": 1,
        +  "type": "integer"
        +}
      • addedInput schema / properties / max_turns
        Added value: +{
        +  "default": 3,
        +  "description": "Number of search rounds. Each round: remote AI generates search commands → local execution → results sent back. Default 3. Use 1 for quick simple lookups. Use 4-5 for complex queries requiring deep tracing across many files. More rounds = better results but slower and uses more API quota.",
        +  "maximum": 5,
        +  "minimum": 1,
        +  "type": "integer"
        +}
      • addedInput schema / properties / tree_depth
        Added value: +{
        +  "default": 3,
        +  "description": "Directory tree depth for the initial repo map sent to the remote AI. Default 3. Use 1-2 for huge monorepos (>5000 files) or if you get payload size errors. Use 4-6 for small projects (<200 files) where you want the AI to see deeper structure. Auto falls back to a lower depth if tree output exceeds 250KB.",
        +  "maximum": 6,
        +  "minimum": 1,
        +  "type": "integer"
        +}
  2. 2 tool updatesv1.0.0
    • First observedextract_windsurf_key
    • First observedfast_context_search

TDQS

A4.1/5.0

Scored across 2 tools

Disambiguation5/5

The two tools have completely distinct purposes: one extracts an API key from a local installation, the other performs semantic code search. No overlap or ambiguity exists.

Naming Consistency4/5

Both tools use snake_case and follow a descriptive pattern (extract_* and fast_*). Although the verb style differs slightly (command vs. brand adjective), the naming is clear and consistent in format.

Tool Count3/5

With only two tools, the server feels minimal. While the tools are focused, the count is on the low end of what is typically expected, making it borderline appropriate.

Completeness2/5

The server covers API key extraction and semantic search, but lacks related operations like API key management, file content retrieval, or result navigation. Significant gaps exist for a context-focused server.

Maintenance

ActivityMaintained
ResponsivenessWithin a week

Related MCP Connectors

Related MCP Servers

  • A
    license
    A
    quality
    D
    maintenance
    Enables AI-driven semantic code search using Windsurf's reverse-engineered SWE-grep protocol to query local codebases with natural language. It executes local search tools like ripgrep and tree-node-cli to return relevant file paths and line ranges to MCP-compatible clients.
    2
    134 npm
    MIT
  • F
    license
    Not graded
    quality
    C
    maintenance
    A semantic code search MCP server that enables natural language queries against your codebase, supporting features like related file discovery and context expansion, all running locally.
    2
    -
  • A
    license
    A
    quality
    C
    maintenance
    Semantic code search MCP server that reduces token usage by ~95% by returning top relevant code chunks instead of full files.
    8
    9
    MIT