Skip to main content
Glama
marlondivino

OpenCode MCP Server

by marlondivino

MCP-сервер OpenCode для Antigravity

Этот репозиторий содержит MCP-сервер OpenCode, сервер на основе Model Context Protocol (MCP), разработанный для работы в качестве помощника для Antigravity в задачах разработки и архитектуры программного обеспечения.

Основная цель этого MCP — экономия токенов в сложных задачах Antigravity за счет того, что OpenCode может уточнять промпты и выполнять предварительный анализ перед отправкой финальных инструкций основной модели.

Возможности

  • Уточнение промптов: Преобразует расплывчатые промпты в подробные и технические инструкции.

  • Поддержка разработки: Помогает в исправлении ошибок и реализации новых функций с упором на эффективность.

  • Семантическая память: Хранит и извлекает технический контекст для обогащения промптов.

Related MCP server: Mem0 MCP Server

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

Перед началом работы необходимо настроить среду разработки. Мы рекомендуем использовать NVM (Node Version Manager) для управления версиями Node.js в Windows.

1. Установка NVM и Node.js (Windows)

  1. Загрузите установщик nvm-setup.exe с nvm-windows.

  2. Следуйте инструкциям по установке.

  3. Откройте новый терминал PowerShell и установите рекомендуемую версию Node.js:

    nvm install 22
    nvm use 22

2. Установка Ollama (для семантической памяти)

Ollama требуется для генерации локальных эмбеддингов.

  1. Откройте PowerShell от имени администратора и выполните:

    winget install ollama
  2. После установки перезапустите терминал и загрузите модель памяти:

    ollama pull nomic-embed-text

3. Проверка установки

Проверьте готовность инструментов в PowerShell:

node -v # Should return v22.x.x or higher
ollama --version

Установка и настройка проекта

Выполните следующие шаги для настройки MCP-сервера OpenCode с помощью PowerShell:

  1. Клонируйте репозиторий:

    git clone <repository-url>
    cd open-code-as-mcp
  2. Установите зависимости:

    npm install
  3. Соберите проект:

    npm run build

Настройка Antigravity

Чтобы интегрировать этот MCP-сервер с Antigravity, необходимо выбрать между локальным режимом (работа на той же машине) или удаленным режимом (работа на сервере/в облаке).

Вариант А: Локальная настройка (Stdio)

Используйте этот вариант, если сервер находится на той же машине, что и клиент.

Глобальная память (по умолчанию)

Память будет общей для всех проектов и храниться в папке сервера.

{
  "mcpServers": {
    "opencode": {
      "command": "node",
      "args": ["D:/IA/MCP/open-code-as-mcp/build/index.js"]
    }
  }
}

Память для каждого проекта (рекомендуется)

Чтобы каждый проект имел свою изолированную память внутри папки .mcp_memory проекта:

{
  "mcpServers": {
    "opencode": {
      "command": "node",
      "args": ["D:/IA/MCP/open-code-as-mcp/build/index.js"],
      "env": {
        "MCP_MEMORY_PATH": ".mcp_memory/vectors"
      }
    }
  }
}

Примечание: Не забудьте добавить .mcp_memory/ в ваш .gitignore, если вы не хотите версионировать базу данных.

Вариант Б: Удаленная настройка (SSE)

Используйте этот вариант, если сервер запущен удаленно. Сервер должен быть запущен с активным режимом SSE.

{
  "mcpServers": {
    "opencode": {
      "url": "http://your-remote-server:3000/sse"
    }
  }
}

Примечание: Убедитесь, что порт и IP доступны при использовании удаленного режима.

Автоматическое использование в Antigravity

Чтобы гарантировать, что Antigravity правильно использует этот MCP, настройте следующие правила в вашем системном промпте (System Prompt):

Глобальные правила Antigravity

  1. Уточнение промпта: Всякий раз, когда пользователь отправляет запрос, сначала используйте opencode:refine_prompt.

  2. Обогащение контекста: После получения уточненного промпта проверьте, есть ли технические термины, требующие дополнительного поиска в семантической памяти.

  3. Непрерывное обучение: После успешной реализации сложной функции или исправления неочевидной ошибки используйте opencode:learn_context для сохранения технических знаний.

Доступные инструменты

MCP OpenCode предоставляет следующие инструменты:

1. refine_prompt

Уточняет промпт для разработки, чтобы сделать его более четким и эффективным.

  • Аргументы:

    • prompt: (строка) Исходный промпт, требующий уточнения.

2. learn_context

Запоминает важную информацию (предпочтения, технические правила, контекст) для будущего использования в семантической памяти.

  • Аргументы:

    • information: (строка) Информация, которую нужно запомнить.

    • category: (строка, необязательно) Категория информации (например, 'preference', 'architecture', 'style').

Удаленный доступ (SSE)

Сервер поддерживает удаленный доступ через SSE (Server-Sent Events). Для запуска в удаленном режиме в PowerShell используйте:

Запуск в удаленном режиме:

$env:MCP_MODE="sse"; $env:PORT="3000"; npm start

Разработка

Для запуска сервера в режиме разработки с горячей перезагрузкой в PowerShell:

npm run dev

Отладка

Вы можете протестировать сервер локально, запустив его в PowerShell:

node build/test-mcp.js

Преимущества MCP OpenCode

  1. Экономия токенов: Уточняя промпты локально, мы снижаем нагрузку на контекст, отправляемый в Antigravity.

  2. Обогащенный контекст: OpenCode может обращаться к локальным файлам и предоставлять более богатый контекст для Antigravity.

  3. Гибкость: Быстрые ответы для задач уточнения.


Разработано при поддержке Gemini CLI.

Available Tools

2 tools
learn_contextB

Memorizes important information (preference, technical rule, context) for future use.

ParametersJSON Schema
NameRequiredDescriptionDefault
informationYesThe information to be remembered.
categoryNoInformation category (e.g., 'preference', 'architecture', 'style').

TDQS

B3.4/5.0
Behavior2/5

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

No annotations are provided, so the description must fully disclose behavior. It says 'memorizes... for future use' but lacks details on persistence, scope, or retrieval, leaving significant ambiguity about the tool's behavior.

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 a single, concise sentence with no redundant words. Every part serves to define the tool's purpose efficiently.

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 simple tool with two parameters and no output schema, the description covers the core functionality. However, it lacks context about when to prefer this over the sibling tool, which slightly reduces completeness.

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

Parameters3/5

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

Schema coverage is 100% (both parameters have descriptions). The description adds minimal value beyond the schema, citing examples like 'preference, technical rule, context', which weakly maps to the 'category' parameter. Baseline 3 is appropriate.

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 the verb 'memorizes' and the resource 'important information', listing examples like preferences and technical rules. It effectively distinguishes from the sibling tool 'refine_prompt' which has a different purpose.

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

Usage Guidelines2/5

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

The description gives no guidance on when to use this tool versus alternatives, nor does it specify when not to use it. It only implies usage for storing information without context about trade-offs.

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

refine_promptB

Refines a prompt using semantic memory to make it more contextual and efficient.

ParametersJSON Schema
NameRequiredDescriptionDefault
promptYesThe original prompt that needs refinement.

TDQS

B3.2/5.0
Behavior2/5

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

No annotations are provided, so the description must disclose behavioral traits. It mentions 'using semantic memory' but does not explain side effects (e.g., memory updates), performance implications, or whether the operation is read-only or modifying. This leaves the agent uncertain about expectations.

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 a single, efficient sentence that starts with the verb. No unnecessary words or structure.

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

Completeness2/5

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

Given no output schema and simple input, the description should explain what 'refinement' means and how semantic memory is used. It does not specify the output format or any side effects, leaving the agent without enough context to invoke the tool correctly.

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

Parameters3/5

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

Schema coverage is 100% for the single parameter, so baseline is 3. The description does not add any meaning beyond the schema's description of 'The original prompt that needs refinement.' No additional constraints, formats, or examples are given.

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 the verb 'refines' and the resource 'prompt', and uses 'semantic memory' to add specificity. It distinguishes from sibling 'learn_context' by focusing on prompt refinement rather than context learning.

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

Usage Guidelines2/5

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

No guidance on when to use this tool versus 'learn_context' or other alternatives. The description implies it is for making prompts more contextual and efficient, but does not specify prerequisites, exclusions, or when refinement is appropriate.

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. 2 tool updatesv1.0.0
    • First observedlearn_context
    • First observedrefine_prompt

TDQS

A3.6/5.0

Scored across 2 tools

Disambiguation5/5

The two tools have clearly distinct purposes: one stores information and the other uses it to refine prompts. There is no overlap or ambiguity.

Naming Consistency5/5

Both tool names follow the verb_noun pattern consistently ('learn_context' and 'refine_prompt'), making them predictable and easy to understand.

Tool Count3/5

With only 2 tools, the server feels thin for its scope. While the core functionality is covered, a typical server would include more tools (e.g., for updating or deleting context).

Completeness4/5

The server covers the basic workflow of storing and using context for prompt refinement. However, it lacks operations to update or delete learned context, which is a minor gap.

Maintenance

ActivityInactive
ResponsivenessNo issues

Related MCP Connectors

Related MCP Servers

  • A
    license
    Not graded
    quality
    D
    maintenance
    Enables persistent memory and semantic search for development workflows with hierarchical compression. Store and retrieve development knowledge across IDE sessions using natural language queries, circumventing context window limitations.
    3
    AGPL 3.0
  • F
    license
    Not graded
    quality
    Not graded
    maintenance
    Enables persistent storage and semantic search of coding preferences, patterns, and implementations using Mem0, allowing AI agents to remember and retrieve development best practices across sessions.
    3
    -