Skip to main content
Glama
LeonidYasin

MCP GitHub Server

by LeonidYasin

MCP GitHub Server

Servidor MCP HTTP extensible para la API de GitHub con arquitectura modular y detección automática de herramientas.

Características

El servidor proporciona 19 herramientas para trabajar con GitHub:

📁 Trabajo con archivos (4)

Herramienta

Descripción

get_file_contents

Lectura del contenido de archivos del repositorio

create_or_update_file

Creación y actualización de archivos de texto

create_or_update_binary_file

Creación y actualización de archivos binarios (base64)

delete_file

Eliminación de archivos (obtiene el SHA automáticamente)

📝 Commits (2)

Herramienta

Descripción

list_commits

Lista de los últimos commits

get_commit_status

Estado de las comprobaciones de un commit

⚙️ Workflow (7)

Herramienta

Descripción

get_latest_workflow_error

Error de la última compilación

get_workflow_run_logs

Registros de una ejecución específica del workflow

get_full_workflow_logs

Registros completos de todos los jobs de la ejecución

get_workflow_by_file

Ejecuciones del workflow por nombre del archivo YAML

list_workflow_runs

Lista de ejecuciones con run_id y estados

get_latest_run_id

run_id de la última ejecución

get_workflow_run_steps

Lista de todos los pasos de la ejecución con sus estados

🏗️ Compilación y depuración (6)

Herramienta

Descripción

watch_build

Supervisión de la compilación

auto_fix_build

Corrección automática de errores de compilación (Android/iOS)

get_android_build_error

Error detallado de la compilación de Android

get_ios_build_error

Error detallado de la compilación de iOS

get_run_logs_by_step

Registros de un paso específico por nombre

create_or_update_file_with_sha

Creación/actualización con obtención automática del SHA

Related MCP server: git-mcp

Instalación

git clone https://github.com/LeonidYasin/mcp-server.git
cd mcp-server
pip install flask httpx python-dotenv flask-cors

Ejecución

python -m mcp_server.server

El servidor se ejecuta en http://0.0.0.0:3001, el endpoint MCP es: POST /mcp.

El token de GitHub se envía mediante el encabezado Authorization: Bearer <token>.

Conexión a DeepSeek++

En la configuración del plugin DeepSeek++:

  • URL: http://127.0.0.1:3001/mcp

  • Tipo: HTTP

  • Encabezado: Authorization: Bearer <su_token_de_github>

Estructura del proyecto

mcp-server/
├── pyproject.toml
├── README.md
└── mcp_server/
    ├── __init__.py
    ├── server.py              # Flask HTTP-сервер
    ├── core/
    │   ├── __init__.py
    │   ├── tool.py            # Tool dataclass
    │   └── registry.py        # ToolRegistry с авто-обнаружением
    └── tools/
        ├── __init__.py
        └── github/
            ├── __init__.py            # Экспорт инструментов
            ├── client.py              # GitHub API HTTP-клиент
            ├── file_ops.py            # get_file_contents, create_or_update_file, delete_file
            ├── file_sha_ops.py        # create_or_update_file_with_sha
            ├── create_update_binary.py # create_or_update_binary_file
            ├── commits.py             # list_commits, get_commit_status
            ├── workflows.py           # workflow-инструменты (4 шт)
            ├── workflow_runs.py       # list_workflow_runs, get_latest_run_id, get_workflow_run_steps, get_run_logs_by_step
            ├── build_logs.py          # watch_build
            ├── build_logs_loader.py   # auto_fix_build, get_android_build_error, get_ios_build_error
            └── build_logs_tools.py    # вспомогательные функции для сборки

Cómo añadir una nueva herramienta

Paso 1: Cree un archivo en mcp_server/tools/github/

Ejemplo: mcp_server/tools/github/create_branch.py

"""MCP tool: create_branch - создаёт новую ветку."""

from mcp_server.core.registry import mcp_tool
from mcp_server.tools.github.client import GitHubClient


@mcp_tool(
    name="create_branch",
    description="Создаёт новую ветку в репозитории",
    parameters={
        "owner": {"type": "string", "description": "Владелец репозитория"},
        "repo": {"type": "string", "description": "Имя репозитория"},
        "branch": {"type": "string", "description": "Имя новой ветки"},
        "from_branch": {"type": "string", "description": "Источник (по умолчанию main)"},
    },
    required=["owner", "repo", "branch"],
)
def create_branch(client: GitHubClient, owner: str, repo: str, branch: str, from_branch: str = "main") -> dict:
    """Создать новую ветку."""
    # 1. Получаем SHA родительской ветки
    ref_resp = client._request(
        "GET", f"/repos/{owner}/{repo}/git/ref/heads/{from_branch}"
    )
    sha = ref_resp.json()["object"]["sha"]

    # 2. Создаём ветку
    client._request(
        "POST",
        f"/repos/{owner}/{repo}/git/refs",
        json={"ref": f"refs/heads/{branch}", "sha": sha},
    )

    return {
        "content": [{
            "type": "text",
            "text": f"✅ Ветка '{branch}' создана из '{from_branch}'"
        }]
    }

Paso 2: Exporte la herramienta

En mcp_server/tools/github/__init__.py añada la línea:

from mcp_server.tools.github.create_branch import create_branch

Paso 3: Reinicie el servidor

# Остановите Ctrl+C и снова запустите
python -m mcp_server.server

La herramienta aparecerá automáticamente en la lista. No se requiere ninguna otra configuración.

Cómo funciona la auto-detección

ToolRegistry (en mcp_server/core/registry.py) al iniciarse:

  1. Escanea mcp_server/tools/

  2. Encuentra todos los subpaquetes (directorios con __init__.py)

  3. Los importa y busca funciones con el decorador @mcp_tool

  4. Registra las herramientas encontradas

Reglas para escribir herramientas

  1. La función debe ser síncrona y aceptar client: GitHubClient como primer argumento

  2. El decorador @mcp_tool define:

    • name — nombre de la herramienta (cómo se invocará)

    • description — descripción para el asistente de IA

    • parameters — diccionario de parámetros en formato JSON Schema

    • required — lista de parámetros obligatorios

  3. Debe devolver un dict con la clave content — una lista de objetos {"type": "text", "text": "..."}

  4. Para solicitudes a la API de GitHub use client._request(method, path, ...)

Plantilla para copiar

"""MCP tool: имя_инструмента - краткое описание."""

from mcp_server.core.registry import mcp_tool
from mcp_server.tools.github.client import GitHubClient


@mcp_tool(
    name="имя_инструмента",
    description="Что делает инструмент",
    parameters={
        "owner": {"type": "string", "description": "Владелец репозитория"},
        "repo": {"type": "string", "description": "Имя репозитория"},
    },
    required=["owner", "repo"],
)
def имя_инструмента(client: GitHubClient, owner: str, repo: str) -> dict:
    # Ваш код здесь
    return {
        "content": [{"type": "text", "text": "Результат работы"}]
    }

Requisitos del token de GitHub

El token debe tener los siguientes permisos (scopes):

  • repo (o Contents: Read and write) — para trabajar con archivos

  • Actions: Read — para ver los workflows

  • Metadata: Read — para información básica (normalmente por defecto)

Prueba del servidor mediante curl

# Проверка списка инструментов
curl -X POST http://127.0.0.1:3001/mcp \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer <токен>" \
  -d '{"jsonrpc":"2.0","id":"1","method":"tools/list","params":{}}'

# Чтение файла
curl -X POST http://127.0.0.1:3001/mcp \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer <токен>" \
  -d '{"jsonrpc":"2.0","id":"2","method":"tools/call","params":{"name":"get_file_contents","arguments":{"owner":"LeonidYasin","repo":"mcp-server","path":"README.md"}}}'

Versionado

  • v0.1.0 — transporte stdio, arquitectura modular básica

  • v0.2.0 — transporte HTTP Flask, 10 herramientas, auto-detección, instrucciones para desarrolladores

  • v0.3.0 — Se añadieron 9 herramientas nuevas: 19 en total, incluyendo trabajo con workflows, compilación y depuración

Related MCP Connectors

Related MCP Servers

  • F
    license
    Not graded
    quality
    D
    maintenance
    Standalone MCP server for GitHub that enables repository management, branch operations, pull request handling, and commit retrieval via tools listed in the README.
    1
    -
  • A
    license
    B
    quality
    D
    maintenance
    MCP (Model Context Protocol) server for GitHub API integration. This server provides comprehensive tools for interacting with GitHub repositories, issues, pull requests, branches, and code search through a unified interface.
    15
    6 npm
    MIT
  • A
    license
    Not graded
    quality
    B
    maintenance
    A lightweight MCP server that exposes GitHub operations as tools over HTTP, enabling any MCP-compatible client to interact with GitHub repositories without a built-in connector.
    1
    MIT