MCP HubMCP Hub
ravitemer

mcphub-nvim

by: ravitemer

A powerful Neovim plugin for managing MCP (Model Context Protocol) servers

648created 19/02/2025
Visit
Neovim
Plugin

📌Overview

Purpose: mcphub.nvim is designed to integrate Model Context Protocol (MCP) servers into the Neovim environment, streamlining their configuration, management, and testing.

Overview: This powerful Neovim plugin allows users to manage multiple MCP servers through a centralized configuration file. It offers a user-friendly interface to browse, install, and test server functionalities, making it particularly beneficial for integrating Large Language Models (LLMs) and providing access to tools and resources.

Key Features:

  • Centralized Server Management: Intuitive UI for managing server states, enabling/disabling tools, and configuring instructions, all with persistent settings across sessions.

  • Marketplace Integration: Users can explore, sort, and filter available MCP servers, along with easy installation options, enhancing accessibility and usability.

  • Interactive Testing Capabilities: Provides a real-time environment for testing tools and accessing resources, complete with built-in documentation for better user experience.

  • High Performance & Reliability: Supports parallel server startups, automatic lifecycle management, and resource efficiency, ensuring reliable and fast operations.

  • Developer-Friendly API: Offers comprehensive API support for synchronous and asynchronous operations, enabling seamless tool and resource interactions.


MCP Hub

A powerful Neovim plugin that integrates MCP (Model Context Protocol) servers into your workflow. Configure and manage MCP servers through a centralized config file while providing an intuitive UI for browsing, installing, and testing tools and resources. Perfect for LLM integration, offering both programmatic API access and interactive testing capabilities through the :MCPHub command.

Discord: Join our Discord server for discussions, help, and updates: https://discord.gg/NTqfxXsNuN

graph TD
subgraph "MCP Servers"
subgraph "Native MCP Servers"
N1["Buffer (Tools)"]
N2["LSP (Resources)"]
end
subgraph "Community"
C1["GitHub (Tools )"]
C2["Figma (Tools)"]
end
end

H[MCPHub]
M["@mcp tool + MCP Servers in text representation"]

subgraph "Chat Plugins"
A["Avante + @mcp tool"]
CC["CodeCompanion + @mcp tool"]
O[Others + @mcp tool]
end

subgraph "LLM Providers"
OAI[OpenAI]
AC[Claude]
M1[Mistral]
G[Grok]
D[DeepSeek]
end

N1 & N2 --> H
C1 & C2 --> H
H --> M
M --> A
M --> CC
M --> O
A --> OAI & AC
CC --> M1 & G
O --> D

✨ Features

Simple Command Interface
  • Single command :MCPHub to access all functionality
Integrated Hub View
  • Enable/disable servers and tools dynamically to optimize token usage
  • Start/stop servers with persistent state
  • Configure custom instructions per server
  • Persistent state across restarts
Native MCP Server Support
  • Create Lua-based MCP servers directly in Neovim
  • Auto-create native MCP servers using LLM templates
  • Write once, use everywhere design
  • Clean chained API for tools, resources, and prompts
  • Full URI-based resource system with templates
  • Centralized lifecycle management
Built-in MCP Servers
  • Pre-configured Neovim server with essential development tools
  • File operations, command execution, terminal integration
  • LSP integration with diagnostics, buffer and environment access
  • Interactive chat prompts
  • Can be disabled if not needed
Chat Plugin Integration
  • Integrates with popular Neovim chat plugins:
    • Avante.nvim: Full MCP tool support with auto-approval
    • CodeCompanion.nvim: MCP resources as chat variables and slash commands
  • Real-time variable updates and prompt registration
Marketplace Integration
  • Browse, sort, filter, and search MCP servers
  • View documentation and installation guides
  • One-click installation via Avante/CodeCompanion
Interactive Testing
  • Real-time tool testing interface
  • Resource browsing and access
  • Built-in documentation and help
Performance and Reliability
  • Multi-instance support with synchronized state
  • Configuration file watching with real-time updates
  • Smart shutdown with configurable delay
  • Parallel startup for improved performance
Developer-friendly
  • Supports sync and async operations
  • Clean client registration/cleanup
  • Comprehensive API for tool and resource access

📦 Installation

Using lazy.nvim:

{
    "ravitemer/mcphub.nvim",
    dependencies = {
      "nvim-lua/plenary.nvim",
    },
    cmd = "MCPHub",
    build = "npm install -g mcp-hub@latest",
    config = function()
      require("mcphub").setup()
    end,
}

Advanced Configuration

Default Config Example
require("mcphub").setup({
    port = 37373,
    config = vim.fn.expand("~/.config/mcphub/servers.json"),
    native_servers = {},

    auto_approve = false,
    auto_toggle_mcp_servers = true,

    extensions = {
        avante = {
            make_slash_commands = true,
        },
        codecompanion = {
            show_result_in_chat = false,
            make_vars = true,
            make_slash_commands = true,
        },
    },

    ui = {
        window = {
            width = 0.8,
            height = 0.8,
            relative = "editor",
            zindex = 50,
            border = "rounded",
        },
        wo = {},
    },

    on_ready = function(hub)
        -- Called when hub is ready
    end,
    on_error = function(err)
        -- Called on errors
    end,

    use_bundled_binary = false,
    shutdown_delay = 600000,

    log = {
        level = vim.log.levels.WARN,
        to_file = false,
        file_path = nil,
        prefix = "MCPHub",
    },
})

Configuration File (~/.config/mcphub/servers.json)

Defines MCP Servers. Example:

{
  "mcpServers": {
    "fetch": {
      "command": "uvx",
      "args": ["mcp-server-fetch"],
      "env": {
        "API_KEY": "",
        "SERVER_URL": null,
        "DEBUG": "true"
      }
    },
    "remote-server": {
      "url": "https://api.example.com/mcp",
      "headers": {
        "Authorization": "Bearer your-token"
      }
    }
  }
}

Supports:

  • Local stdio servers (command, args, env)
  • Remote SSE servers (url, headers)
  • Server options like disabled, disabled_tools, custom_instructions configurable via UI

🚀 Usage

Open the MCPHub UI:

:MCPHub
API for Chat Plugin Developers
local hub = mcphub.get_hub_instance()

-- Call a tool (sync)
local response, err = hub:call_tool("server-name", "tool-name", {
    param1 = "value1"
}, {
    return_text = true
})

-- Call a tool (async)
hub:call_tool("server-name", "tool-name", {
    param1 = "value1"
}, {
    return_text = true,
    callback = function(response, err)
      -- Use response
    end
})

-- Access resource (sync)
local response, err = hub:access_resource("server-name", "resource://uri", {
    return_text = true
})

-- Get prompt helpers
local prompts = hub:generate_prompts()

🔌 Extensions

MCPHub provides extensions integrating with popular Neovim chat plugins.

Avante.nvim

  • Enable MCP tools with auto_approve option for auto tool approval.
  • Enable /slash commands from server prompts.
  • Example setup:
require("mcphub").setup({
    extensions = {
        avante = {
            make_slash_commands = true,
        }
    }
})

require("avante").setup({
    system_prompt = function()
        local hub = require("mcphub").get_hub_instance()
        return hub:get_active_servers_prompt()
    end,
    custom_tools = function()
        return {
            require("mcphub.extensions.avante").mcp_tool(),
        }
    end,
})

Disable any conflicting Avante built-in tools in your config to avoid duplicates:

disabled_tools = {
    "list_files",
    "search_files",
    "read_file",
    "create_file",
    "rename_file",
    "delete_file",
    "create_dir",
    "rename_dir",
    "delete_dir",
    "bash",
},

CodeCompanion

  • Auto approve tool requests.
  • Show resources as #variables in chat.
  • Show prompts as /slash_commands.
  • Server prompts are /mcp:prompt_name.
  • Example setup:
require("mcphub").setup({
    extensions = {
        codecompanion = {
            show_result_in_chat = true,
            make_vars = true,
            make_slash_commands = true,
        },
    }
})

require("codecompanion").setup({
    strategies = {
        chat = {
            tools = {
                ["mcp"] = {
                    callback = function() return require("mcphub.extensions.codecompanion") end,
                    description = "Call tools and resources from the MCP Servers",
                }
            }
        }
    }
})

Lualine

Example setup:

require('lualine').setup {
    sections = {
        lualine_x = {
            {require('mcphub.extensions.lualine')},
        },
    },
}

Shows connection status and number of connected servers in the statusline.


Lua Native MCP Servers (detailed guide)

Why Use Native MCP Servers?

They provide a unified API and interface enabling a "write once, use everywhere" model for Neovim chat plugins.

Example static server definition:

native_servers = { 
  weather = {
    name = "weather",
    capabilities = {
      tools = {
        {
          name = "get_weather",
          description = "Get current weather information for a city",
          inputSchema = {
            type = "object",
            properties = {
              city = { type = "string", description = "City name to get weather for" }
            },
          },
          handler = function(req, res)
            res:text("Weather in " .. req.params.city .. ": ☀️ Sunny, 22°C"):send()
          end
        }
      },
      resources = {
        {
          name = "current",
          uri = "weather://current/london",
          description = "Get current weather data for London",
          handler = function(req, res)
            res:text("London: ☀️ Sunny, 22°C, Humidity: 65%"):send()
          end
        }
      },
      resourceTemplates = {
        {
          name = "city_weather",
          uriTemplate = "weather://forecast/{city}",
          description = "Get weather forecast for any city",
          handler = function(req, res)
            res:text(req.params.city .. " 5-day forecast:\n" ..
                   "Mon: ☀️ 22°C\n" ..
                   "Tue: ⛅ 20°C\n" ..
                   "Wed: 🌧️ 18°C"):send()
          end
        }
      },
      prompts = {
        name = "weather_chat",
        description = "Chat about weather in any city",
        arguments = {
          { name = "city", description = "City to check weather for" }
        },
        handler = function(req, res)
          return res
          :user()
          :text(string.format("What's the weather like in %s?", req.params.city))
          :llm()
          :text(string.format("Let me check the weather in %s for you...", req.params.city))
          :text(string.format("The weather in %s is ☀️ 22°C.", req.params.city))
          :send()
        end
      }
    }
  }
}

Alternatively, dynamically add features via API:

local mcphub = require("mcphub")

mcphub.add_tool("weather", {...})
mcphub.add_resource("weather", {...})
mcphub.add_resource_template("weather", {...})
mcphub.add_prompt({...})

Benefits

  • Write once, use everywhere
  • Rich resource capabilities with URI-based resources and templates
  • Centralized lifecycle management
  • Seamless integration with chat plugins

🔨 Troubleshooting

  1. Environment Requirements

    • node >= 18.0.0
    • python installed
    • uvx installed
    • Verify npx or uvx commands work
  2. LLM Model Issues

    • Models with function calling (e.g., claude-3.5) work best
    • Ensure correct tool call formats
    • Recommended models: GPT-4o, Claude 3.5 Sonnet, Claude 3.7, Gemini 2.0, Mistral Large
  3. Port Issues

    • If port is in use, kill existing process:
      lsof -i :[port]
      kill [pid]
      
  4. Configuration File

    • Use absolute path
    • Valid JSON with mcpServers key
    • Correct commands and args per server
  5. MCP Server Issues

    • Validate servers with MCP Inspector or mcp-cli
    • Check logs in MCPHub UI
    • Test tools and resources individually
  6. Need Help?

    • Test with minimal.lua
    • Open an issue or discussion on GitHub repository

🔄 How It Works

MCPHub.nvim uses an Express server for managing MCP servers and clients.

  • On setup, it verifies installation, version, and starts the mcp-hub server if not running.
  • Provides REST API and real-time UI updates in Neovim.
  • Supports multi-instance with client registration and graceful shutdown.
  • Synchronizes config file changes across instances.

Architecture Flows

Server Lifecycle

sequenceDiagram
    participant N1 as First Neovim
    participant N2 as Other Neovim clients
    participant S as MCP Hub Server

    N1->>S: Check if running
    alt Not running
      N1->>S: Start hub
      S-->>N1: Ready
    end
    N1->>S: Register client
    N2->>S: Register client
    N2->>S: Unregister client
    N1->>S: Unregister client (last)
    S: Grace period and shutdown

Request Flow

sequenceDiagram
    participant N as Neovim
    participant P as Plugin
    participant S as MCP Hub Server

    N->>P: start_hub()
    P->>S: Health check and start if needed
    P->>S: Register client
    N->>P: Open :MCPHub
    P->>S: Get status
    P->>N: Display UI

Cleanup Flow

flowchart LR
    VimLeavePre --> Stop Hub
    Stop Hub --> Unregister Client
    Unregister Client --> Server Shutdown (if last client)

API Flow

sequenceDiagram
    participant C as Chat Plugin
    participant H as Hub Instance
    participant S as MCP Server

    C->>H: call_tool()
    H->>S: POST /tools
    S-->>H: Tool Result
    H-->>C: Return Result

    C->>H: access_resource()
    H->>S: POST /resources
    S-->>H: Resource Data
    H-->>C: Return Data

Requirements

  • Neovim >= 0.8.0
  • Node.js >= 18.0.0
  • plenary.nvim
  • mcp-hub (automatically installed via build command)

🚧 TODO

  • Neovim MCP Server with enhanced editing, diffs, terminal integration
  • Enhanced help view with documentation
  • MCP Resources as variables in chat plugins
  • MCP Prompts as slash commands in chat plugins
  • Enable LLMs to start and stop MCP servers dynamically
  • Support SSE transport
  • Support slash commands in Avante
  • Better documentation and wiki

👏 Acknowledgements

Thanks to:

  • cline/mcp-marketplace for marketplace API
  • nui.nvim for text highlighting utilities inspiration

📚 Documentation

Visit our Wiki for detailed documentation:

  • Installation Guide
  • Configuration Guide
  • Extension Setup
  • Avante Integration
  • CodeCompanion Integration
  • Lualine Integration
  • Native MCP Servers
  • Example Implementations
  • API Reference
  • Troubleshooting Guide