Skip to main content
Glama

mcp-chatgpt

Сервер MCP (Model Context Protocol), который позволяет ИИ-ассистентам (таким как Google Antigravity, Claude Desktop, Cursor, VS Code Cline/Roo Code) задавать вопросы, общаться и взаимодействовать с ChatGPT Web (https://chatgpt.com) напрямую через автоматизацию браузера, профили Chrome и сопутствующее расширение Chrome.


🌟 Возможности

  • 💬 Вопросы и общение: Задавайте вопросы ChatGPT Web и получайте ответы (форматированный текст / Markdown).

  • 🌐 Переключатель веб-поиска: Включайте веб-поиск ChatGPT в реальном времени (web_search: true) для просмотра веб-страниц и получения цитат.

  • 🧠 Выбор модели и уровня рассуждений: Выбирайте модели (model: "o3-mini", "gpt-4o", "o1") и настраивайте уровень рассуждений (reasoning_effort: "high" | "medium" | "low").

  • 📎 Вложения файлов и изображений: Прикрепляйте изображения (image_paths) и документы/код (file_paths) для мультимодального анализа.

  • ⏩ Автопродолжение вывода: Автоматически нажимает "Continue generating" / "สร้างต่อ", если длинные ответы обрываются.

  • 💻 Извлечение кода: Извлекайте и возвращайте только блоки кода с помощью extract_code_only: true.

  • 👤 Выбор профиля Chrome: Автоматически обнаруживает все профили Google Chrome на вашем компьютере (Default, Profile 1, Work, Personal, email-адреса) и позволяет выбрать, с какой учётной записью общаться.

  • 🧩 Сопутствующее расширение Chrome: Включает расширение Manifest V3 в каталоге extension/, которое можно загрузить в любой профиль Chrome для общения в реальном времени с вкладками ChatGPT без проблем с блокировкой профиля.

  • 🔄 Управление беседами: Начинайте новые чаты или продолжайте существующие обсуждения, используя идентификаторы бесед / URL-адреса.

  • 💾 Постоянная сессия: Сохраняет профиль браузера и файлы cookie для входа локально, поэтому вам нужно входить в систему только один раз.

  • 🖥️ Режимы с окном и без окна (Headed & Headless): Работайте в фоновом режиме без вывода (headless) или запускайте видимое окно (--login / --headed) для первоначальной аутентификации или решения капчи.

  • 🔌 Поддержка Chrome CDP: Подключайтесь к уже запущенному экземпляру Google Chrome через --remote-debugging-port.

  • 🧰 Инструменты рабочей области: Ищите файлы, запускайте сборки/тесты и редактируйте код с помощью кроссплатформенных инструментов shell_command и apply_patch, ограниченных корневым каталогом.

  • 🌐 Удалённый MCP-туннель: Опциональная конечная точка Streamable HTTP с аутентификацией Bearer для Cloudflare Tunnel/ngrok или другого HTTPS-туннеля.


Related MCP server: agentify-desktop

🛠️ Предоставляемые MCP-инструменты

Инструмент

Параметры

Описание

shell_command

command (string, обязательный)workdir (string, необязательный)shell (auto|powershell|bash, необязательный)timeout_ms (number, необязательный)

Выполняет команды с рабочей директорией в пределах настроенного корневого каталога. Автоматически выбирает PowerShell в Windows и Bash в Linux/macOS.

apply_patch

patch (string, обязательный)

Добавляет, обновляет, удаляет или перемещает файлы в пределах настроенного корневого каталога shell с помощью структурированных патчей.

chatgpt_ask

message (string, обязательный)web_search (boolean, необязательный)model (string, необязательный)reasoning_effort ("low"|"medium"|"high", необязательный)image_paths (string[], необязательный)file_paths (string[], необязательный)extract_code_only (boolean, необязательный)auto_continue (boolean, необязательный)refresh_page (boolean, необязательный)profile (string, необязательный)new_chat (boolean, необязательный)conversation_id (string, необязательный)timeout_ms (number, необязательный)

Отправляет запрос/вопрос в ChatGPT Web с расширенными настройками и возвращает ответ ассистента.

chatgpt_reload

Нет

Перезагружает и обновляет текущую страницу ChatGPT Web, чтобы восстановиться после зависаний или сбоев соединения.

chatgpt_list_models

Нет

Перечисляет все доступные модели ИИ (GPT-5.6 Sol, GPT-5.5, o3, GPT-4o, o1) и варианты уровня рассуждений для этой учётной записи.

chatgpt_list_conversations

limit (number, необязательный)

Перечисляет последние темы бесед и их ID прямо из боковой панели ChatGPT для поиска или продолжения чатов.

chatgpt_list_profiles

Нет

Перечисляет все обнаруженные профили Google Chrome на этом компьютере с указанием ID профиля, имени и email.

chatgpt_select_profile

profile (string, обязательный)

Выбирает и переключает активный профиль Chrome (по ID, например Profile 1, имени или email).

chatgpt_new_chat

Нет

Начинает новый сеанс чата в ChatGPT Web.

chatgpt_get_status

Нет

Получает статус браузера, активный профиль, статус моста, текущий URL и активную модель.

chatgpt_login

profile (string, необязательный)

Открывает ChatGPT Web в видимом окне браузера для входа в систему.


🚀 Быстрый старт

[!WARNING] shell_command может выполнять произвольные команды с теми же правами операционной системы, что и MCP-сервер. --shell-root ограничивает выбираемую стартовую рабочую директорию, но не является песочницей ОС. Запускайте сервер от имени ограниченного пользователя или в контейнере при подключении недоверенных клиентов. apply_patch действительно гарантирует, что все изменяемые пути остаются в пределах --shell-root.

Удалённый MCP-туннель

Локальный stdio остаётся режимом по умолчанию. Чтобы предоставить удалённо совместимую MCP-конечную точку, запустите HTTP-режим с токеном:

mcp-chatgpt --http --http-token "change-this-token"

Конечная точка — http://127.0.0.1:8787/mcp. Поместите перед ней туннель, например:

cloudflared tunnel --url http://127.0.0.1:8787

Настройте удалённый MCP-клиент на публичный URL туннеля, оканчивающийся на /mcp, и заголовок Authorization: Bearer change-this-token. /healthz можно использовать для проверки работоспособности туннеля. Если остановится этот процесс или туннель, удалённые MCP-запросы станут недоступны.

1. Установка и сборка

# Clone the repository
git clone https://github.com/JonusNattapong/mcp-chatgpt.git
cd mcp-chatgpt

# Install dependencies and Chromium
npm install
npx playwright install chromium

# Build TypeScript
npm run build

# Install the MCP command globally
npm install -g .

После установки проверьте её с помощью:

mcp-chatgpt --help

Пакет автоматически выполняет npm run build во время установки, поэтому глобальная команда всегда использует актуальный исходный код TypeScript при установке из локальной копии репозитория.

👤 Использование профилей Chrome (2 варианта)

Вариант 1: Автоопределение профиля Chrome (прямой / безголовый)

Вы можете выбрать любой профиль Chrome в вашей системе по имени папки (например, Default, Profile 1), отображаемому имени или адресу электронной почты:

# List all Chrome profiles in your system
node -e "import('./dist/profile-manager.js').then(m => console.table(m.ProfileManager.listProfiles()))"

# Login with a specific profile
node dist/index.js --login --profile "Profile 1"

Или передайте параметр profile напрямую в инструмент chatgpt_ask!


Вариант 2: Расширение-компаньон для Chrome (рекомендуется для активного Chrome)

Если вы уже ежедневно используете Google Chrome с выполненным входом в аккаунт ChatGPT, установите расширение-компаньон:

  1. Откройте Google Chrome с нужным профилем.

  2. Перейдите на chrome://extensions.

  3. Включите режим разработчика (справа вверху).

  4. Нажмите Загрузить распакованное и выберите папку d:\Projects\Github\mcp-chatgpt\extension.

  5. Нажмите на значок расширения на панели инструментов, задайте тег профиля (например, «Work Account») и нажмите Сохранить и подключить.

  6. Когда mcp-chatgpt запущен, он будет направлять запросы прямо через вашу вкладку Chrome!


⚙️ Конфигурация для MCP-клиентов

Вы можете подключить mcp-chatgpt к любому ИИ-клиенту, поддерживающему Model Context Protocol (MCP):

1. Antigravity IDE / Gemini CLI

Расположение файла: ~/.gemini/config/mcp_config.json (Windows: C:\Users\<User>\.gemini\config\mcp_config.json)

{
  "mcpServers": {
    "chatgpt": {
      "command": "node",
      "args": [
        "d:/Projects/Github/mcp-chatgpt/dist/index.js"
      ]
    }
  }
}

2. Claude Desktop

  • Windows: %APPDATA%\Claude\claude_desktop_config.json

  • macOS: ~/Library/Application Support/Claude/claude_desktop_config.json

{
  "mcpServers": {
    "chatgpt": {
      "command": "node",
      "args": [
        "d:/Projects/Github/mcp-chatgpt/dist/index.js"
      ]
    }
  }
}

3. Cursor IDE

Добавьте в .cursor/mcp.json вашего проекта или в Cursor Settings > Features > MCP:

{
  "mcpServers": {
    "chatgpt": {
      "command": "node",
      "args": [
        "d:/Projects/Github/mcp-chatgpt/dist/index.js"
      ]
    }
  }
}

4. VS Code (Cline / Roo Code / Roo Clinic)

Расположение файла:

  • Cline: %APPDATA%\Code\User\globalStorage\saoudrizwan.claude-dev\settings\cline_mcp_settings.json

  • Roo Code: %APPDATA%\Code\User\globalStorage\rooveterinaryinc.roo-cline\settings\cline_mcp_settings.json

{
  "mcpServers": {
    "chatgpt": {
      "command": "node",
      "args": [
        "d:/Projects/Github/mcp-chatgpt/dist/index.js"
      ],
      "disabled": false,
      "autoApprove": []
    }
  }
}

5. Windsurf Editor (Codeium)

Расположение файла: ~/.codeium/windsurf/mcp_config.json

{
  "mcpServers": {
    "chatgpt": {
      "command": "node",
      "args": [
        "d:/Projects/Github/mcp-chatgpt/dist/index.js"
      ]
    }
  }
}

6. Zed Editor

Добавьте в ~/.config/zed/settings.json:

{
  "context_servers": {
    "chatgpt": {
      "command": {
        "path": "node",
        "args": ["d:/Projects/Github/mcp-chatgpt/dist/index.js"]
      }
    }
  }
}

7. LibreChat (librechat.yaml)

Добавьте в librechat.yaml:

mcpServers:
  chatgpt:
    type: stdio
    command: node
    args:
      - d:/Projects/Github/mcp-chatgpt/dist/index.js

8. Удалённое подключение через Cloudflare Tunnel (Remote URL / SSE / mcp-remote)

Если ваш браузер ChatGPT или мостовой сервер работает на домашнем компьютере или VPS, и вы хотите, чтобы ИИ-клиенты на других машинах/ноутбуках подключались к нему безопасно через интернет с помощью Cloudflare Tunnel:

Шаг A: Публикация мостового сервера на хост-машине

# Start Cloudflare Quick Tunnel (Free, no account required)
cloudflared tunnel --url http://127.0.0.1:18999

Это создаст публичный HTTPS-URL, например: https://alpha-bravo-charlie.trycloudflare.com


Шаг B: Настройка клиента на удалённых машинах

1. Antigravity / Gemini CLI (Remote SSE / URL)

Добавьте в ~/.gemini/config/mcp_config.json:

{
  "mcpServers": {
    "chatgpt-remote": {
      "serverUrl": "https://alpha-bravo-charlie.trycloudflare.com/sse"
    }
  }
}
2. Cursor IDE (Remote SSE)

Добавьте в .cursor/mcp.json или в настройки Cursor:

{
  "mcpServers": {
    "chatgpt-remote": {
      "url": "https://alpha-bravo-charlie.trycloudflare.com/sse"
    }
  }
}
3. VS Code Cline / Roo Code (Remote SSE)

Добавьте в cline_mcp_settings.json:

{
  "mcpServers": {
    "chatgpt-remote": {
      "url": "https://alpha-bravo-charlie.trycloudflare.com/sse",
      "type": "sse",
      "disabled": false,
      "autoApprove": []
    }
  }
}
4. Claude Desktop / любой stdio-клиент (через mcp-remote)

Для клиентов, которые принимают только command (stdio), используйте mcp-remote для моста к URL Cloudflare Tunnel:

{
  "mcpServers": {
    "chatgpt-remote": {
      "command": "npx",
      "args": [
        "-y",
        "mcp-remote",
        "https://alpha-bravo-charlie.trycloudflare.com/sse"
      ]
    }
  }
}
5. LibreChat (librechat.yaml)
mcpServers:
  chatgpt-remote:
    type: sse
    url: https://alpha-bravo-charlie.trycloudflare.com/sse
6. Прямой HTTP REST API (cURL / Python / Node.js)

Вы также можете взаимодействовать напрямую с конечными точками моста через Cloudflare:

# Query status
curl -s https://alpha-bravo-charlie.trycloudflare.com/status

# Ask a question
curl -X POST https://alpha-bravo-charlie.trycloudflare.com/ask \
  -H "Content-Type: application/json" \
  -d '{"message": "Hello from Cloudflare Tunnel!"}'

📖 Опции CLI

Usage: mcp-chatgpt [options]

Options:
  --headed                 Run browser in headed (visible) mode (default: false)
  --login                  Open browser in interactive mode to log in to ChatGPT
  --profile <name_or_id>   Select specific Chrome Profile (e.g. "Default", "Profile 1", or Name/Email)
  --chrome                 Use installed Google Chrome browser (default: true)
  --no-chrome              Use Playwright bundled Chromium instead of Google Chrome
  --user-data-dir <path>   Custom browser profile directory
  --cdp <endpoint>         Connect to an existing Chrome browser via CDP endpoint
  --bridge-port <port>     Port for Chrome Extension bridge WebSocket (default: "18999")
  --bridge-only            Run only the Chrome Extension WebSocket bridge server
  --shell-root <path>      Restrict shell and patch tools to this directory (default: current directory)
  --shell-max-timeout <ms> Maximum shell command timeout in milliseconds (default: "300000")
  --http                   Expose an MCP Streamable HTTP endpoint for a tunnel/remote client
  --http-host <host>       HTTP bind host (default: "127.0.0.1")
  --http-port <port>       HTTP port for the MCP endpoint (default: "8787")
  --http-token <token>     Bearer token required by remote MCP clients (or MCP_HTTP_TOKEN)
  --timeout <ms>           Default timeout in milliseconds (default: "120000")
  -h, --help               Display help for command

🌟 Живая демонстрация интерактивной памяти и сохранения контекста

Ниже приведён реальный неотредактированный многоходовой интерактивный сеанс, выполненный вживую через mcp-chatgpt:

Ход 1: Установка контекста в новой сессии (new_chat: true)

Запрос:

{
  "message": "สวัสดีครับ ผมชื่อ โจ๊กเกอร์ เป็น Software Architect ชอบเขียน Go และ TypeScript กำลังพัฒนาโปรเจกต์ชื่อ MCP-ChatGPT ฝากจำข้อมูลนี้ไว้หน่อยนะครับ ตอบสั้นๆ 1 ประโยคยืนยัน",
  "new_chat": true
}

Ответ ChatGPT:

"Запомнил: вас зовут Джокер, вы программный архитектор, любите Go и TypeScript и разрабатываете проект MCP-ChatGPT."

URL: https://chatgpt.com/c/6a86843c-8f30-83ec-b064-d27f7f832244


Ход 2: Последующее извлечение из памяти (conversation_id)

Запрос:

{
  "message": "ไหนลองทบทวนดูซิว่า ผมชื่ออะไร ชอบเขียนภาษาอะไร และกำลังทำโปรเจกต์ชื่ออะไรอยู่?",
  "conversation_id": "6a86843c-8f30-83ec-b064-d27f7f832244"
}

Ответ ChatGPT (извлечено за 6 секунд):

"Вас зовут Джокер, вы любите писать на Go и TypeScript и разрабатываете проект под названием MCP-ChatGPT. 🫡"


🤖 Системный промпт для ИИ-ассистента и инструкция по интеграции

Скопируйте и вставьте следующую инструкцию непосредственно в вашего ИИ-ассистента (Cursor Rules, Claude System Prompt, Antigravity Custom Instructions, Cline, Roo Code), чтобы ваш ИИ автоматически знал, когда и как вызывать mcp-chatgpt:

# 🛠️ Instruction: Setup and Integrate `mcp-chatgpt` MCP Server

You are integrated with the `mcp-chatgpt` MCP server, granting you direct access to ChatGPT Web capabilities (o3-mini, o1, GPT-4o, live Web Search, DALL-E, and multimodal file analysis).

### 🎯 When to Automatically Use `chatgpt_ask`:

1. **Deep Reasoning & Hard Coding Tasks**:
   - For complex architecture designs, difficult debugging, or advanced algorithms, call `chatgpt_ask` with:
     `{ "model": "o3-mini", "reasoning_effort": "high", "extract_code_only": true }`
2. **Live Web Information & Current News**:
   - When the user asks for up-to-date news, today's market data, or the latest documentation of newly updated packages, call:
     `{ "web_search": true }`
3. **Image Generation (DALL-E 3)**:
   - When the user requests an image, logo, or icon design, request it via `chatgpt_ask` and present the returned `imageUrls` directly to the user.
4. **Heavy Document & File Analysis**:
   - When analyzing CSV, Excel spreadsheets, PDFs, or large source code files, attach them via `file_paths` or `image_paths`.
5. **Continuous Conversations**:
   - Always track and pass `conversation_id` to continue in the same thread, or pass `new_chat: true` when starting an unrelated topic.
6. **Finding Past Chats**:
   - Call `chatgpt_list_conversations` to search for existing topic IDs before resuming a specific past conversation.

📄 Лицензия

MIT

Available Tools

12 tools
apply_patchA

Safely add, update, delete, or move files inside the configured shell root using an *** Begin Patch / *** End Patch patch. Prefer this over shell redirection for code edits.

Inputs: patch (required).

chatgpt_askB

Send a question or prompt to ChatGPT Web (chatgpt.com) and get the assistant response. Supports Web Search, o1/o3-mini reasoning, model selection, code extraction, image/file attachments, and Chrome profiles.

Inputs: message (required), model, profile, new_chat, +9 more.

chatgpt_get_latest_responseA

Fetch and recover the latest assistant response (including text, code blocks, and images) from the current or specified conversation without asking a new question. Useful after recovering from a timeout or reload.

Inputs: refresh_first, conversation_id.

chatgpt_get_statusA

Get the current status of ChatGPT Web automation (initialized, logged in, active profile, extension bridge status, current conversation URL, title, model).

Inputs: no named parameters.

chatgpt_list_conversationsA

List recent conversation history topics and IDs from the ChatGPT sidebar so you can select and resume any previous chat.

Inputs: limit.

chatgpt_list_modelsA

List all available AI models (e.g. GPT-5.6 Sol, GPT-5.5, o3, gpt-4o, o1) and reasoning effort options for this ChatGPT account.

Inputs: no named parameters.

chatgpt_list_profilesA

List all detected Google Chrome profiles available on this machine (including Profile Folder ID, Display Name, Email).

Inputs: no named parameters.

chatgpt_loginA

Open ChatGPT Web in a visible (headed) browser window so the user can log in or solve Captcha challenges.

Inputs: profile.

chatgpt_new_chatA

Start a clean/new conversation on ChatGPT Web.

Inputs: no named parameters.

chatgpt_reloadA

Reload and refresh the current ChatGPT Web page to fix stuck conversations or connection glitches.

Inputs: no named parameters.

chatgpt_select_profileA

Select which Chrome profile to use for ChatGPT Web automation (by Profile Folder ID, Display Name, or Email).

Inputs: profile (required).

shell_commandA

Run a command with a working directory inside the configured shell root. Uses PowerShell on Windows and Bash on Linux/macOS by default. The command has the same OS permissions as this MCP server.

Inputs: command (required), shell, workdir, timeout_ms.

Tool Schema Changelog

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

Loading tool schema changelog…

    TDQS

    A3.8/5.0

    Scored across 12 tools

    Disambiguation4/5

    The ChatGPT tools mostly map to distinct lifecycle stages, such as selecting a profile, asking a question, reloading the page, and fetching status. The main potential confusions are shell_command vs apply_patch for file operations and chatgpt_ask vs chatgpt_get_latest_response for retrieving assistant output, though the descriptions provide reasonable separation.

    Naming Consistency4/5

    The 10 chatgpt_* tools consistently use a readable, mostly verb-first style with a common prefix. Two tools, shell_command and apply_patch, break away from the chatgpt_ prefix and use different naming conventions, which makes the overall set slightly inconsistent.

    Tool Count4/5

    With 12 tools, the count is reasonable, and most tools are clearly relevant to ChatGPT Web automation. The shell_command and apply_patch pair broadens the server beyond ChatGPT-specific tasks, feeling slightly like an additional generic toolkit rather than a core part of the same domain.

    Completeness4/5

    The core ChatGPT Web workflow is covered well: profile selection, login/status, starting a chat, asking questions, recovering responses, listing conversations, listing models, and reloading. Obvious gaps are conversation management actions such as delete or rename, and there is no explicit tool name for select/resume a previous conversation, though this may be handled through parameters in ask or get_latest_response.

    Related MCP Connectors

    Related MCP Servers