Skip to main content
Glama
GianBaeza

GitHub Next.js Optimizer MCP Server

by GianBaeza

🚀 GitHub Next.js Optimizer MCP Server

Version License Node MCP

Servidor MCP inteligente que analiza repositorios de GitHub y proporciona recomendaciones avanzadas de optimización para proyectos Next.js y React

CaracterísticasInstalaciónConfiguraciónUsoPatrones


📋 Tabla de Contenidos


Related MCP server: MCP Next.js Hook Generator

🤔 ¿Qué es este proyecto?

GitHub Next.js Optimizer MCP Server es un servidor del Model Context Protocol (MCP) que se integra con herramientas de IA como Claude para analizar repositorios de GitHub y proporcionar recomendaciones inteligentes sobre:

  • ✅ Arquitectura limpia (Clean Architecture)

  • ✅ Principios SOLID

  • ✅ Patrones de diseño (Design Patterns)

  • ✅ Optimizaciones de rendimiento en React/Next.js

  • ✅ Server Components vs Client Components

  • ✅ Anti-patrones y code smells

  • ✅ Best practices de Next.js App Router


✨ Características

🔍 Análisis Profundo

  • Análisis de repositorio completo: Escanea todos los archivos React/Next.js (.tsx, .jsx, .ts, .js)

  • Análisis de archivos individuales: Obtén recomendaciones específicas para un archivo

  • Detección de patrones: Identifica más de 50+ patrones y anti-patrones

🎯 Recomendaciones Inteligentes

  • Principios SOLID: SRP, OCP, LSP, ISP, DIP

  • Clean Architecture: Domain, Use Cases, Infrastructure, Presentation

  • React/Next.js Best Practices: Server Components, memoización, hooks optimizados

  • Performance: Lazy loading, code splitting, optimizaciones de rendering

🛠️ Herramientas

  • analizar_repositorio: Análisis completo del proyecto

  • listar_archivos_react: Lista todos los archivos React/Next.js

  • analizar_archivo: Análisis detallado de un archivo específico


📦 Requisitos Previos

Antes de comenzar, asegúrate de tener instalado:

  • Node.js: >= 18.0.0 (Descargar)

  • npm: >= 9.0.0 (viene con Node.js)

  • Git: Para clonar el repositorio

  • GitHub Personal Access Token: Para acceder a la API de GitHub

  • VS Code: Con la extensión Cline instalada


🚀 Instalación

Opción 1: Instalación Global (Recomendada)

# Instalar desde npm
npm install -g github-nextjs-optimizer-mcp

# Verificar instalación
github-nextjs-optimizer-mcp --version

Opción 2: Instalación desde Repositorio

# Clonar el repositorio
git clone https://github.com/GianBaeza/Next.js-Optimizer-MCP-Server.git
cd Next.js-Optimizer-MCP-Server

# Instalar dependencias
npm install

# Compilar el proyecto
npm run build

# Enlazar globalmente (opcional)
npm link

Opción 3: Uso con npx (Sin instalación)

# Usar directamente con npx
npx github-nextjs-optimizer-mcp

🔑 Obtener GitHub Personal Access Token

  1. Ve a GitHub Settings → Developer settings → Personal access tokens → Tokens (classic)

  2. Haz clic en "Generate new token (classic)"

  3. Configura el token:

    • Note: "MCP Server Token" (o cualquier nombre descriptivo)

    • Expiration: 90 días (o sin expiración para desarrollo)

    • Scopes: Selecciona los siguientes permisos:

      • repo (Full control of private repositories)

      • read:org (Read org and team membership)

      • read:user (Read user profile data)

  4. Haz clic en "Generate token"

  5. ⚠️ IMPORTANTE: Copia el token inmediatamente (solo se muestra una vez)

    • Ejemplo: ghp_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx


⚙️ Configuración con Cline (VS Code)

Paso 1: Instalar Cline

  1. Abre VS Code

  2. Ve a Extensions (Ctrl+Shift+X o Cmd+Shift+X)

  3. Busca "Cline"

  4. Instala la extensión oficial de Cline

Paso 2: Ubicar el archivo de configuración

El archivo de configuración de Cline se encuentra en:

  • Windows:

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

    ~/Library/Application Support/Code/User/globalStorage/saoudrizwan.claude-dev/settings/cline_mcp_settings.json
  • Linux:

    ~/.config/Code/User/globalStorage/saoudrizwan.claude-dev/settings/cline_mcp_settings.json

Paso 3: Configurar el servidor MCP

Abre el archivo cline_mcp_settings.json y agrega la siguiente configuración:

Si instalaste globalmente:

{
  "mcpServers": {
    "github-nextjs-optimizer": {
      "command": "github-nextjs-optimizer-mcp",
      "args": [],
      "env": {
        "GITHUB_TOKEN": "ghp_tu_token_de_github_aqui"
      }
    }
  }
}

Si usas npx (sin instalación global):

{
  "mcpServers": {
    "github-nextjs-optimizer": {
      "command": "npx",
      "args": [
        "-y",
        "github-nextjs-optimizer-mcp"
      ],
      "env": {
        "GITHUB_TOKEN": "ghp_tu_token_de_github_aqui"
      }
    }
  }
}

Si instalaste desde el repositorio local:

{
  "mcpServers": {
    "github-nextjs-optimizer": {
      "command": "node",
      "args": [
        "/ruta/completa/a/Next.js-Optimizer-MCP-Server/build/index.js"
      ],
      "env": {
        "GITHUB_TOKEN": "ghp_tu_token_de_github_aqui"
      }
    }
  }
}

Paso 4: Reiniciar VS Code

  1. Cierra completamente VS Code

  2. Ábrelo nuevamente

  3. Abre la extensión Cline desde la barra lateral

Paso 5: Verificar la conexión

  1. Abre Cline en VS Code

  2. Haz clic en el ícono de configuración (⚙️)

  3. Ve a "MCP Servers"

  4. Deberías ver github-nextjs-optimizer con estado "Connected"

Si aparece "Disconnected" ❌, ve a la sección Troubleshooting.


🔧 Configuración con Continue

Si prefieres usar Continue en lugar de Cline:

Paso 1: Instalar Continue

code --install-extension continue.continue

Paso 2: Configurar Continue

Edita el archivo ~/.continue/config.json:

{
  "models": [
    {
      "title": "Claude Sonnet 4.5",
      "provider": "anthropic",
      "model": "claude-sonnet-4-5-20250929",
      "apiKey": "tu_anthropic_api_key"
    }
  ],
  "mcpServers": [
    {
      "name": "github-nextjs-optimizer",
      "command": "npx",
      "args": ["-y", "github-nextjs-optimizer-mcp"],
      "env": {
        "GITHUB_TOKEN": "ghp_tu_token_de_github_aqui"
      }
    }
  ]
}

🛠️ Herramientas Disponibles

1. analizar_repositorio

Analiza un repositorio completo de GitHub.

Parámetros:

  • owner (string, requerido): Propietario del repositorio

  • repo (string, requerido): Nombre del repositorio

  • branch (string, opcional): Rama a analizar (default: "main")

Ejemplo de uso en Cline:

Analiza el repositorio GianBaeza/veterinariaFrontend

Respuesta:

  • Total de archivos React/Next.js encontrados

  • Problemas detectados por archivo

  • Recomendaciones específicas

  • Nivel de severidad (high, medium, low)


2. listar_archivos_react

Lista todos los archivos React/Next.js en un repositorio.

Parámetros:

  • owner (string, requerido): Propietario del repositorio

  • repo (string, requerido): Nombre del repositorio

  • path (string, opcional): Ruta específica a listar

Ejemplo de uso en Cline:

Lista todos los archivos React del repositorio GianBaeza/veterinariaFrontend

3. analizar_archivo

Analiza un archivo específico en detalle.

Parámetros:

  • owner (string, requerido): Propietario del repositorio

  • repo (string, requerido): Nombre del repositorio

  • path (string, requerido): Ruta al archivo

  • branch (string, opcional): Rama (default: "main")

Ejemplo de uso en Cline:

Analiza el archivo src/app/page.tsx del repositorio GianBaeza/veterinariaFrontend

💡 Ejemplos de Uso

Análisis Completo de un Proyecto

Usuario: Analiza mi proyecto de veterinaria en GitHub

Cline (con MCP):

Voy a analizar tu repositorio usando el servidor MCP...

📁 Repositorio: GianBaeza/veterinariaFrontend
📊 Total de archivos: 9

Problemas encontrados:

1. src/app/page.tsx:
   ❗ Componente sin 'use client' pero usa hooks
   💡 Recomendación: Agregar 'use client' al inicio del archivo

2. src/feature/auth/Auth.tsx:
   ⚠️ Componente muy simple sin funcionalidad
   💡 Recomendación: Implementar formulario de autenticación con validación

Análisis de Archivo Específico

Usuario: Analiza el middleware.ts de mi proyecto

Cline (con MCP):

📄 Análisis de middleware.ts:

❌ CRÍTICO: Configuración de matcher incorrecta
🔄 Redirección infinita detectada

Código actual:
export const config = {
    matcher: ['/home/:path*']
}

Problema: El middleware redirige a /home pero el matcher captura /home/*

Solución recomendada:
export const config = {
    matcher: '/'  // Solo captura la raíz
}

🎨 Patrones Analizados

🏛️ Arquitectura Limpia

  • Domain Layer: Entidades, Value Objects

  • Use Cases: Lógica de negocio

  • Infrastructure: Repositorios, API clients

  • Presentation: Componentes UI

🔷 Principios SOLID

  • Single Responsibility Principle

  • Open/Closed Principle

  • Liskov Substitution Principle

  • Interface Segregation Principle

  • Dependency Inversion Principle

⚛️ React/Next.js Best Practices

  • Server Components vs Client Components

  • React.memo y optimizaciones

  • useCallback y useMemo

  • Lazy loading y code splitting

  • Suspense y streaming

📐 Design Patterns

  • Singleton

  • Factory

  • Observer

  • Strategy

  • Composite

  • Adapter

  • Repository Pattern

⚠️ Anti-Patrones Detectados

  • Prop drilling excesivo

  • God components

  • Tight coupling

  • Funciones inline en props

  • Arrays/Objects inline

  • useEffect sin dependencias

  • Fetch en cliente sin caché


🐛 Troubleshooting

Problema: "Server disconnected" en Cline

Causa: El servidor MCP no puede iniciarse correctamente.

Soluciones:

  1. Verifica que el token de GitHub es válido:

    # Prueba el token manualmente
    curl -H "Authorization: token ghp_tu_token" https://api.github.com/user
  2. Verifica que Node.js está actualizado:

    node --version  # Debe ser >= 18.0.0
  3. Prueba el servidor manualmente:

    export GITHUB_TOKEN="ghp_tu_token"
    github-nextjs-optimizer-mcp
  4. Revisa los logs de Cline:

    • Abre Cline

    • Ve a Settings → MCP Servers

    • Haz clic en el servidor y revisa los logs


Problema: "Cannot find module"

Solución:

# Limpia la caché de npm
npm cache clean --force

# Reinstala las dependencias
cd Next.js-Optimizer-MCP-Server
rm -rf node_modules package-lock.json
npm install

# Recompila
npm run build

Problema: "GITHUB_TOKEN is not defined"

Solución:

Asegúrate de que el token está configurado en cline_mcp_settings.json:

{
  "mcpServers": {
    "github-nextjs-optimizer": {
      "command": "github-nextjs-optimizer-mcp",
      "args": [],
      "env": {
        "GITHUB_TOKEN": "ghp_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
      }
    }
  }
}

⚠️ El token debe empezar con ghp_ y tener 40 caracteres.


Problema: Permission denied en macOS/Linux

Solución:

# Da permisos de ejecución
chmod +x build/index.js

# O reinstala con permisos
sudo npm install -g github-nextjs-optimizer-mcp

Problema: El servidor se conecta pero no responde

Solución:

  1. Verifica que el repositorio existe y es accesible

  2. Verifica que tu token tiene los permisos correctos

  3. Prueba con un repositorio público primero

Analiza el repositorio facebook/react

📝 Logs y Debugging

El servidor genera logs detallados. Para ver los logs:

En Cline:

  1. Abre Cline

  2. Settings → MCP Servers

  3. Selecciona tu servidor

  4. Haz clic en "View Logs"

En la terminal:

# Ejecuta el servidor con logs
export DEBUG=*
export GITHUB_TOKEN="tu_token"
github-nextjs-optimizer-mcp

🤝 Contribuir

¡Las contribuciones son bienvenidas! Si quieres mejorar este proyecto:

  1. Fork el repositorio

  2. Crea una branch para tu feature (git checkout -b feature/AmazingFeature)

  3. Commit tus cambios (git commit -m 'Add some AmazingFeature')

  4. Push a la branch (git push origin feature/AmazingFeature)

  5. Abre un Pull Request

Ideas para contribuir:

  • 🎯 Agregar más patrones de análisis

  • 🔍 Mejorar la detección de anti-patrones

  • 📚 Agregar más ejemplos de código

  • 🌐 Soporte para otros frameworks (Vue, Angular)

  • 🧪 Agregar tests unitarios

  • 📖 Mejorar la documentación


📄 Licencia

Este proyecto está bajo la Licencia MIT. Ver el archivo LICENSE para más detalles.


🙏 Agradecimientos


📧 Contacto

Gian Baeza - GitHub Profile

Link del Proyecto: https://github.com/GianBaeza/Next.js-Optimizer-MCP-Server


⭐ Si este proyecto te fue útil, considera darle una estrella en GitHub ⭐

Made with ❤️ by Gian Baeza

Available Tools

3 tools
analizar_archivoC

Analiza un archivo específico de React/Next.js y proporciona recomendaciones

ParametersJSON Schema
NameRequiredDescriptionDefault
pathYesRuta al archivo a analizar
repoYesNombre del repositorio
ownerYesPropietario del repositorio
branchNoRama (por defecto: main)main

TDQS

C2.9/5.0
Behavior2/5

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

No annotations are provided, so the description carries full behavioral burden. It does not state whether the operation is read-only, what permissions or authentication are needed, whether it produces side effects, or what the recommendations output looks like. Only the high-level analysis purpose is disclosed.

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

Conciseness4/5

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

The description is a single, front-loaded sentence with no wasted words. It is appropriately concise, though it lacks any structuring or elaboration for a tool with several inputs and an implied output.

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

Completeness3/5

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

With no annotations or output schema, the description should compensate more than it does. It identifies the resource and the type of output (recommendations), but omits when to use it versus alternatives and does not describe the recommendation format or scope limitations.

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 description coverage is 100%, so all four parameters are already documented in the schema. The description adds no parameter-level detail beyond implying a file path, so the baseline score of 3 is appropriate.

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

Purpose4/5

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

States a specific verb (analizar) and resource (archivo específico de React/Next.js) plus the outcome (recomendaciones). It is clear what the tool does, but it does not explicitly distinguish itself from the sibling analizar_repositorio tool.

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 analizar_repositorio or listar_archivos_react. No prerequisites, context, or exclusions are mentioned; the agent must infer that a single file should be analyzed here.

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

analizar_repositorioB

Analiza un repositorio de GitHub completo y proporciona recomendaciones de optimización para proyectos Next.js y React

ParametersJSON Schema
NameRequiredDescriptionDefault
repoYesNombre del repositorio
ownerYesPropietario del repositorio de GitHub
branchNoRama a analizar (por defecto: main)main

TDQS

B3.2/5.0
Behavior2/5

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

With no annotations, the description carries the full behavioral burden and falls short. It does not disclose whether the operation is read-only, whether GitHub authentication or a token is required, rate/scope limits, whether it clones or indexes the repo, or roughly how expensive/long the analysis is.

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

Conciseness4/5

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

A single front-loaded sentence covering action, scope, and value with no filler. It is appropriately sized, though it omits any conditional context that would make it a model of tight structure.

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

Completeness3/5

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

No output schema exists, so the description must cover more than it does. It names the deliverable (optimization recommendations) but leaves unstated the analysis's mechanics, prerequisites, and limitations for a fairly complex repository-wide operation.

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 description coverage is 100%: owner, repo, and branch (with default main) are all documented in the schema. The description adds no extra meaning beyond that, so the baseline of 3 applies.

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

Purpose4/5

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

States a clear verb (analiza) and resource (repositorio de GitHub completo) plus the deliverable (recomendaciones de optimización). The word 'completo' implicitly scopes it apart from the single-file sibling analizar_archivo, though no sibling is named explicitly.

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

Usage Guidelines3/5

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

Usage is only implied: the whole-repository scope suggests it belongs after or instead of the file-level siblings, but there is no explicit when-to-use, when-not-to-use, or alternative routing. An agent must infer the placement in the workflow.

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

listar_archivos_reactB

Lista todos los archivos React/Next.js (.tsx, .jsx, .ts, .js) en un repositorio

ParametersJSON Schema
NameRequiredDescriptionDefault
pathNoRuta específica a listar (opcional)
repoYesNombre del repositorio
ownerYesPropietario del repositorio

TDQS

B3.1/5.0
Behavior2/5

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

No annotations are provided, so the description carries the full burden. It doesn't disclose whether this requires authentication, rate limits, pagination behavior, recursive vs non-recursive traversal, or how files are filtered. For a repository listing tool with zero annotation coverage, this is a significant gap.

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?

A single front-loaded sentence stating verb, resource, and file-type constraints with zero waste. Well-structured and appropriately sized for the tool's scope.

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

Completeness3/5

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

The description covers the core purpose but lacks behavioral context that matters for a repository listing tool with no annotations and no output schema. An agent knows what it lists but not how the operation behaves (recursion, auth, pagination) or what the return structure looks like. Minimum viable but with clear gaps.

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 description coverage is 100%, so the schema already documents all three parameters (owner, repo, path). The description adds no additional parameter semantics beyond what the schema provides. Baseline 3 is appropriate when schema does the heavy lifting.

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

Purpose4/5

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

States a specific verb (listar) and resource (archivos React/Next.js) with extension filters, clearly distinguishing it from analizar_repositorio and analizar_archivo which analyze rather than list. Sibling differentiation is implied by the 'list' vs 'analyze' verbs but not explicitly stated. Clear enough for an agent to select correctly.

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 explicit guidance on when to use this tool versus analizar_repositorio or analizar_archivo. The listing scope suggests it's a discovery step before analysis, but this is left to inference. No prerequisites or exclusions are stated.

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. 3 tool updatesv1.0.0
    • First observedanalizar_archivo
    • First observedanalizar_repositorio
    • First observedlistar_archivos_react

TDQS

B3.3/5.0

Scored across 3 tools

Disambiguation4/5

The three tools have distinct scopes: whole-repository analysis, file listing, and single-file analysis. However, 'analizar_repositorio' and 'analizar_archivo' both provide optimization recommendations and could be confused if an agent isn't careful about the target scope.

Naming Consistency5/5

All tool names follow a consistent Spanish verb_noun pattern in snake_case: analizar_repositorio, listar_archivos_react, analizar_archivo. No deviations or mixed conventions.

Tool Count4/5

Three tools is a reasonable, focused set for a specialized Next.js/React optimizer. It is on the thin side but each tool has a clear role, and the count aligns well with the narrow domain.

Completeness3/5

The surface covers analysis of repos and files plus file listing, which addresses the core need of providing recommendations. However, notable gaps exist: no tools for applying fixes, analyzing dependencies (e.g., package.json), inspecting Next.js configuration, or generating structured reports, which limits the 'optimizer' workflow.

Maintenance

ActivityInactive
ResponsivenessNo issues

Related MCP Connectors

Related MCP Servers

  • A
    license
    Not graded
    quality
    D
    maintenance
    Enables AI assistants to analyze GitHub repository structures and read file contents with features like directory traversal, file type analysis, syntax highlighting, and code pattern detection. Supports both public and private repositories through GitHub API integration.
    5 npm
    Apache 2.0
  • -
    license
    Not graded
    quality
    Not graded
    maintenance
    Automatically generates typed React hooks for Next.js projects by crawling API routes, GraphQL queries, and components. Analyzes pages to suggest optimal render modes (SSR/CSR/ISR) and produces documentation with performance guidance.
    -
  • F
    license
    Not graded
    quality
    D
    maintenance
    Automatically generates typed React hooks for Next.js projects by crawling API routes, GraphQL queries, and components. Analyzes pages to suggest optimal render modes (SSR/CSR/ISR) and produces comprehensive documentation with AI-powered guidance.
    -
  • A
    license
    A
    quality
    D
    maintenance
    Enables analysis of any GitHub repository to get architecture, file roles, execution flows, system design Q\&A, and structured agent context. Works with MCP-compatible clients like Claude Desktop, Cursor, and Windsurf.
    6
    23 npm
    MIT