homebrew-mcp

by jeannier (community) · Claude Desktop, macOS + Homebrew

MCP MCP Servers Open Source v0.1.0

MCP-сервер для управления Homebrew на macOS через естественный язык. Позволяет Claude устанавливать, обновлять и искать пакеты, не покидая чата. Возможности: - Поиск формул и cask по ключевым словам - Установка / удаление пакетов (`brew install`, `uninstall`) - Обновление (`brew upgrade`) - Список установленных пакетов - Информация о формуле: версия, зависимости, описание - Поддержка cask (GUI-приложений)

v0.1.0
current
Добавлен 18.06.2026 · Обновлён 18.06.2026 · MCP Servers
Установка
# Требуется macOS + Homebrew

# Claude Desktop — claude_desktop_config.json:
{
  "mcpServers": {
    "homebrew": {
      "command": "uvx",
      "args": ["homebrew-mcp"]
    }
  }
}

# Claude Code (CLI):
claude mcp add homebrew -- uvx homebrew-mcp

# OpenCode — ~/.config/opencode/opencode.json:
{
  "mcp": {
    "homebrew": {
      "type": "local",
      "command": ["uvx", "homebrew-mcp"]
    }
  }
}
переведено ИИ

Homebrew MCP Python-сервер

Сервер протокола контекста модели (MCP) для управления пакетами Homebrew на macOS, предназначенный для бесшовной интеграции с Claude Desktop и другими MCP-совместимыми клиентами.

  • Язык: Python 3.13
  • MCP: Model Context Protocol
  • Менеджер пакетов: Homebrew (macOS)
  • Менеджер виртуальных окружений/зависимостей: uv

Возможности

  • Предоставляет команды Homebrew как инструменты MCP. Поддерживаемые команды сгруппированы по функционалу:
  • Управление пакетами: install, uninstall, upgrade, cleanup
  • Информация и поиск: list, search, info, outdated, deps
  • Здоровье системы и обновления: doctor, update
  • Управление тапами и источниками: tap, untap
  • Управление версиями: pin, unpin
  • Управление сервисами: services
  • Запускает реальные команды brew через подпроцесс (требуется Homebrew на macOS).
  • Полностью соответствует спецификации MCP (stdio, JSON-RPC 2.0, MCP spec 2025-06-18).
  • Предназначен для Claude Desktop и других клиентов LLM.
  • Функциональный, декларативный Python (без классов).
  • Логирует все запросы/результаты в файл homebrew_mcp.log.
  • Включает интерактивный тестовый скрипт (test_claude_homebrew_mcp.py), который:
    • Динамически получает доступные инструменты от MCP-сервера.
    • Позволяет Claude выполнять несколько вызовов инструментов для одного запроса пользователя.
    • Демонстрирует продвинутые паттерны взаимодействия с API Anthropic.

Установка

  1. Клонируйте этот репозиторий: sh git clone https://github.com/jeannier/homebrew-mcp cd homebrew-mcp
  2. Установите uv (если еще не установлен): sh brew install uv
  3. Создайте виртуальное окружение и установите зависимости: sh uv venv source .venv/bin/activate # Активировать виртуальное окружение uv pip install -r requirements.txt
  4. Запустите MCP-сервер (для локального тестирования): Чтобы протестировать сервер локально во время разработки, вы можете запустить его напрямую: sh uv run python homebrew_mcp.py Сервер запустится. При успешном запуске немедленного вывода не будет; он будет молча слушать MCP-запросы через stdio. Вы можете проверить его работу, просмотрев файл homebrew_mcp.log.

Примечание: Если вы интегрируете его с Claude Desktop, вам не нужно запускать эту команду вручную. Claude Desktop запустит сервер автоматически на основе конфигурации, описанной в разделе «Интеграция с Claude Desktop». Эта команда предназначена для прямого тестирования или разработки.


Интеграция с Cursor

Предварительное условие: Прежде чем добавлять инструмент, пожалуйста, выполните шаги из раздела Установка для настройки проекта и его зависимостей. Кнопка «Добавить в Cursor» предполагает, что проект находится по адресу ~/Documents/GitHub/homebrew-mcp.

Добавить в Cursor

  1. Установите Cursor через Homebrew (macOS): sh brew install --cask cursor

  2. Добавьте инструмент в Cursor:

  3. Нажмите кнопку «Добавить Cursor» выше. Это откроет Cursor и автоматически установит инструмент.
  4. Если ваш проект находится не по адресу, предполагаемому кнопкой, вам придется отредактировать сгенерированную конфигурацию. На macOS этот файл находится по адресу ~/.cursor/mcp.json. Откройте его и обновите путь внутри строки command для записи homebrew-mcp. Файл mcp.json из этого репозитория можно использовать в качестве справки.

  5. Перезапустите Cursor:

  6. Чтобы инструмент стал активным, перезапустите Cursor после установки.

Интеграция с Claude Desktop

  1. Установите Claude Desktop через Homebrew (macOS): sh brew install --cask claude

  2. Убедитесь, что uv находится в вашем PATH и проект доступен.

  3. Настройте Claude Desktop для использования этого MCP-сервера:

  4. На macOS отредактируйте или создайте файл пользовательской конфигурации MCP по адресу: ~/Library/Application Support/Claude/claude_desktop.json.
  5. Добавьте следующее определение сервера, заменив /path/to/your/project/ на абсолютный путь к каталогу, куда вы клонировали этот проект. В качестве примера можно обратиться к файлу claude_desktop_config.json в этом репозитории.
{
  "mcpServers": {
    "homebrew-mcp": {
      "command": "uv",
      "args": [
        "run",
        "--directory",
        "/path/to/your/project/",
        "homebrew_mcp.py"
      ],
      "type": "stdio"
    }
  }
}

Аргумент --directory указывает uv, где найти скрипт homebrew_mcp.py и его контекст (например, .venv).

  1. Перезапустите Claude Desktop.

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

  • Скрипты Python
  • homebrew_mcp.py — Основной скрипт MCP-сервера.
  • test_claude_homebrew_mcp.py — Интерактивный скрипт тестирования интеграции с Claude.
  • Конфигурация
  • claude_desktop_config.json — Пример конфигурации для Claude Desktop.
  • mcp.json — Пример конфигурации для Cursor.
  • requirements.txt — Зависимости проекта Python.
  • Документация и метаданные
  • README.md — Этот файл.
  • LICENSE — Лицензия MIT проекта.
  • .gitignore — Указывает файлы для игнорирования Git.
  • Сгенерированные файлы (отсутствуют в Git)
  • .venv/ — Виртуальное окружение Python, управляемое uv.
  • homebrew_mcp.log — Файл журнала MCP-сервера.

Мониторинг журналов

Чтобы отслеживать журнал сервера в реальном времени и красиво печатать каждую строку JSON:

tail -f homebrew_mcp.log | jq .

Тестированная среда

Этот MCP-сервер и его интеграция с Claude в основном тестировались в следующей среде:

  • macOS: Sonoma 14.7.5
  • Homebrew: 4.5.8
  • Python: 3.13 (управляемый через uv)
  • Модуль mcp: 1.9.4 (установлен с помощью uv pip)
  • Модуль anthropic: 0.55.0 (установлен с помощью uv pip)
  • Claude Desktop: 0.10.38 (установлен через Homebrew Cask на macOS).
  • Cursor: 1.1.4

Примеры запросов

Вот несколько примеров запросов, которые вы можете использовать с Claude (или другим MCP-клиентом) при взаимодействии с этим MCP-сервером Homebrew:

  • предоставить сводку всех установленных пакетов
  • проверить, какие пакеты установлены, и предложить предложения по установке других пакетов
  • есть ли какие-либо проблемы с моей конфигурацией homebrew? и как я могу их исправить?
  • показать информацию о пакете python 3.13
  • установить пакет wget

Интерактивный тестовый скрипт для Claude

Для запуска теста интеграции с Claude (test_claude_homebrew_mcp.py) вам понадобится API-ключ Anthropic Claude. Установите ваш API-ключ в переменной ANTHROPIC_API_KEY в начале тестового скрипта. Этот скрипт позволяет вам взаимодействовать с Claude, который, в свою очередь, использует сервер homebrew_mcp.py. Он демонстрирует динамическое обнаружение инструментов и способность Claude выполнять несколько вызовов инструментов.

uv run python test_claude_homebrew_mcp.py

Пример вывода тестового запуска

Этот раздел показывает пример вывода при запуске скрипта test_claude_homebrew_mcp.py. Он демонстрирует взаимодействие между Claude и сервером Homebrew MCP, включая динамическое обнаружение инструментов, множественные вызовы инструментов и окончательные ответы.

$ uv run python test_claude_homebrew_mcp.py

============================== Claude Prompt 1/7 ===============================
install wget if not installed, or uninstall if already installed
================================================================================
============================= Claude's Answer 1/7 ==============================
I've successfully installed wget on your system. Now that wget is installed, if you'd like me to uninstall it instead (as per your request to either install if not present or uninstall if already installed), I can do that for you.

Would you like me to proceed with uninstalling wget now? Please let me know.
================================================================================

============================== Claude Prompt 2/7 ===============================
restore initial state of wget
================================================================================
============================= Claude's Answer 2/7 ==============================
I've successfully uninstalled wget, returning your system to its initial state before our conversation. The wget package has been completely removed from your system.
================================================================================

============================== Claude Prompt 3/7 ===============================
check for outdated packages
================================================================================
============================= Claude's Answer 3/7 ==============================
You have 3 outdated packages:
1. libnghttp2
2. uv
3. yt-dlp

These packages have newer versions available and can be upgraded if you wish.
================================================================================

============================== Claude Prompt 4/7 ===============================
provide a summary of all installed packages
================================================================================
============================= Claude's Answer 4/7 ==============================
Here's a summary of all installed packages on your system:

1. **Command Line Tools & Utilities**: bash, coreutils, curl, git, jq, nmap, grep, watch, etc.
2. **Programming Languages & Tools**: python (multiple versions), node, go, lua
3. **Media Tools & Libraries**: ffmpeg and its dependencies (x264, x265, etc.), yt-dlp
4. **Development Tools**: neovim, tree-sitter, shellcheck
5. **Applications (Casks)**:
   - Browsers: google-chrome, firefox
   - Development: visual-studio-code, iterm2, cursor, github
   - Communication: discord, whatsapp
   - Media: vlc, spotify, stremio
   - Utilities: docker-desktop, keepassxc, alt-tab, disk-inventory-x
   - AI/ML tools: chatgpt, claude, ollama, superwhisper

You have 3 outdated packages (libnghttp2, uv, and yt-dlp) that could be updated.
================================================================================

============================== Claude Prompt 5/7 ===============================
provide 5 suggestions of other packages to install
================================================================================
============================= Claude's Answer 5/7 ==============================
Based on your installed packages and common developer tools, here are 5 suggested packages that would complement your setup:

1. **tmux** - A terminal multiplexer that allows you to manage multiple terminal sessions within a single window. Great companion to your iterm2 and neovim setup.

2. **htop** - An interactive process viewer and system monitor, much more feature-rich than the standard top command.

3. **ripgrep** - A faster alternative to grep, designed for searching code. Works well with your development tools.

4. **fzf** - A command-line fuzzy finder that can dramatically improve your terminal workflow for searching files, command history, and more.

5. **tldr** - Simplified and community-driven man pages with practical examples. Perfect for quickly finding common command usage patterns.

These tools would enhance your command-line productivity and integrate well with your existing development environment. Would you like more information about any of these packages?
================================================================================

============================== Claude Prompt 6/7 ===============================
use brew doctor to see if there are any issues, try to find a fix for all of these issues
================================================================================
============================= Claude's Answer 6/7 ==============================
Based on the complete analysis, here's my recommendation to fix the one minor warning:

Since this is just a warning about having both the core and tap version of nextdns available, and you're actually using the core version (as shown by the info command), this isn't causing any functional problems with your system. The warning is simply informing you that if you want to specifically use the tap version, you need to use the full name.

If you want to fully resolve this warning, you have two options:

1. Continue using the core version of nextdns (which you are currently using) and untap the nextdns tap to remove the ambiguity. This would require identifying the exact tap name and then using the untap command.

2. Keep both versions available and just be aware that you need to use the full name when referring to the tap version.

Since the warning isn't causing any actual issues with your Homebrew installation and everything is functioning correctly, I would recommend option 2 - simply being aware of the naming convention when you need to use the tap version.

The brew doctor results suggest your Homebrew installation is actually in good shape with no critical issues that need fixing!
================================================================================

============================== Claude Prompt 7/7 ===============================
provide a summary of what was done
================================================================================
============================= Claude's Answer 7/7 ==============================
# Homebrew Session Summary

Here's a summary of what was done during our session:

1. **Checked and installed wget**:
   - Initially verified that wget was not installed on your system
   - Installed wget version 1.25.0

2. **Restored initial state**:
   - Uninstalled wget to return to the original system state

3. **Checked for outdated packages**:
   - Found 3 outdated packages: libnghttp2, uv, and yt-dlp

4. **Listed all installed packages**:
   - Displayed a complete list of installed formulae and casks
   - Your system has numerous development tools, utilities, and applications installed

5. **Suggested 5 additional packages**:
   - tmux: Terminal multiplexer
   - htop: Interactive process viewer
   - ripgrep: Fast alternative to grep
   - fzf: Command-line fuzzy finder
   - tldr: Simplified man pages

6. **Ran system diagnostics**:
   - Executed brew doctor to check for issues
   - Found only one minor warning related to the nextdns package having the same name in both core formulae and a custom tap
   - This warning is informational only and doesn't require action unless you experience issues with nextdns

7. **Examined package versions**:
   - Listed all installed packages with their versions to get a better understanding of your system configuration

Overall, your Homebrew installation appears to be in good health with only a minor naming conflict that doesn't impact functionality.
================================================================================

Лицензия

Лицензия MIT

Комментарии
Войдите, чтобы оставить комментарий