Skip to content
Back to search

mcp-hub

A centralized manager for Model Context Protocol (MCP) servers with dynamic server management and monitoring

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/ravitemer--mcp-hub/badge.svg)](/listings/ravitemer--mcp-hub)

HTML

<a href="/listings/ravitemer--mcp-hub"><img src="/api/listings/ravitemer--mcp-hub/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

npm install -g mcp-hub

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 1,270 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. # MCP Hub
  2. [![npm version](https://badge.fury.io/js/mcp-hub.svg)](https://www.npmjs.com/package/mcp-hub)
  3. [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
  4. [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](./CONTRIBUTING.md)
  5. MCP Hub acts as a central coordinator for MCP servers and clients, providing two key interfaces:
  6. 1. **Management Interface** (/api/*): Manage multiple MCP servers through a unified REST API and web UI
  7. 2. **MCP Server Interface** (/mcp): Connect ANY MCP client to access ALL server capabilities through a single endpoint
  8. This dual-interface approach means you can manage servers through the Hub's UI while MCP clients (Claude Desktop, Cline, etc.) only need to connect to one endpoint (`localhost:37373/mcp`) to access all capabilities. Implements [MCP 2025-03-26](https://modelcontextprotocol.io/specification/2025-03-26) specification.
  9. ## Feature Support
  10. | Category | Feature | Support | Notes |
  11. |----------|---------|---------|-------|
  12. | **Transport** ||||
  13. | | streamable-http | ✅ | Primary transport protocol for remote servers |
  14. | | SSE | ✅ | Fallback transport for remote servers |
  15. | | STDIO | ✅ | For running local servers |
  16. | **Authentication** ||||
  17. | | OAuth 2.0 | ✅ | With PKCE flow |
  18. | | Headers | ✅ | For API keys/tokens |
  19. | **Capabilities** ||||
  20. | | Tools | ✅ | List tools |
  21. | | 🔔 Tool List Changed | ✅ | Real-time updates |
  22. | | Resources | ✅ | Full support |
  23. | | 🔔 Resource List Changed | ✅ | Real-time updates |
  24. | | Resource Templates | ✅ | URI templates |
  25. | | Prompts | ✅ | Full support |
  26. | | 🔔 Prompts List Changed | ✅ | Real-time updates |
  27. | | Roots | ❌ | Not supported |
  28. | | Sampling | ❌ | Not supported |
  29. | | Completion | ❌ | Not supported |
  30. | **Marketplace** ||||
  31. | | Server Discovery | ✅ | Browse available servers |
  32. | | Installation | ✅ | Auto configuration |
  33. | **Real-time** ||||
  34. | | Status Updates | ✅ | Server & connection state |
  35. | | Capability Updates | ✅ | Automatic refresh |
  36. | | Event Streaming to clients | ✅ | SSE-based |
  37. | | Auto Reconnection | ✅ | With backoff |
  38. | **Development** ||||
  39. | | Hot Reload | ✅ | Auto restart a MCP server on file changes with `dev` mode |
  40. | **Configuration** ||||
  41. | | `${}` Syntax | ✅ | Environment variables and command execution across all fields |
  42. | | VS Code Compatibility | ✅ | Support for `servers` key, `${env:}`, `${input:}`, predefined variables |
  43. | | JSON5 Support | ✅ | Comments and trailing commas in configuration files |
  44. ## Simplified Client Configuration
  45. Configure all MCP clients with just one endpoint:
  46. ```json
  47. {
  48. "mcpServers" : {
  49. "Hub": {
  50. "url" : "http://localhost:37373/mcp"
  51. }
  52. }
  53. }
  54. ```
  55. The Hub automatically:
  56. - Namespaces capabilities to prevent conflicts (e.g., `filesystem__search` vs `database__search`)
  57. - Routes requests to the appropriate server
  58. - Updates capabilities in real-time when servers are added/removed
  59. - Handles authentication and connection management
  60. ## Key Features
  61. - **Unified MCP Server Endpoint** (/mcp):
  62. - Single endpoint for ALL MCP clients to connect to
  63. - Access capabilities from all managed servers through one connection
  64. - Automatic namespacing prevents conflicts between servers
  65. - Real-time capability updates when servers change
  66. - Simplified client configuration - just one endpoint instead of many
  67. - **Dynamic Server Management**:
  68. - Start, stop, enable/disable servers on demand
  69. - Real-time configuration updates with automatic server reconnection
  70. - Support for local (STDIO) and remote (streamable-http/SSE) MCP servers
  71. - Health monitoring and automatic recovery
  72. - OAuth authentication with PKCE flow
  73. - Header-based token authentication
  74. - **Unified REST API**:
  75. - Execute tools from any connected server
  76. - Access resources and resource templates
  77. - Real-time status updates via Server-Sent Events (SSE)
  78. - Full CRUD operations for server management
  79. - **Real-time Events & Monitoring**:
  80. - Live server status and capability updates
  81. - Client connection tracking
  82. - Tool and resource list change notifications
  83. - Structured JSON logging with file output
  84. - **Client Connection Management**:
  85. - Simple SSE-based client connections via /api/events
  86. - Automatic connection cleanup on disconnect
  87. - Optional auto-shutdown when no clients connected
  88. - Real-time connection state monitoring
  89. - **Process Lifecycle Management**:
  90. - Graceful startup and shutdown handling
  91. - Proper cleanup of server connections
  92. - Error recovery and reconnection
  93. - **Workspace Management**:
  94. - Track active MCP Hub instances across different working directories
  95. - Global workspace cache in XDG-compliant state directory
  96. - Real-time workspace updates via SSE events
  97. - API endpoints to list and monitor active workspaces
  98. ### Components
  99. #### Hub Server
  100. The main management server that:
  101. - Maintains connections to multiple MCP servers
  102. - Provides unified API access to server capabilities
  103. - Handles server lifecycle and health monitoring
  104. - Manages SSE client connections and events
  105. - Processes configuration updates and server reconnection
  106. #### MCP Servers
  107. Connected services that:
  108. - Provide tools, resources, templates, and prompts
  109. - Support two connectivity modes:
  110. - Script-based STDIO servers for local operations
  111. - Remote servers (streamable-http/SSE) with OAuth support
  112. - Implement real-time capability updates
  113. - Support automatic status recovery
  114. - Maintain consistent interface across transport types
  115. ## Installation
  116. ```bash
  117. npm install -g mcp-hub
  118. ```
  119. ## Basic Usage
  120. Start the hub server:
  121. ```bash
  122. mcp-hub --port 3000 --config path/to/config.json
  123. # Or with multiple config files (merged in order)
  124. mcp-hub --port 3000 --config ~/.config/mcphub/global.json --config ./.mcphub/project.json
  125. ```
  126. ### CLI Options
  127. ```bash
  128. Options:
  129. --port Port to run the server on (required)
  130. --config Path to config file(s). Can be specified multiple times. Merged in order. (required)
  131. --watch Watch config file for changes, only updates affected servers (default: false)
  132. --auto-shutdown Whether to automatically shutdown when no clients are connected (default: false)
  133. --shutdown-delay Delay in milliseconds before shutting down when auto-shutdown is enabled (default: 0)
  134. -h, --help Show help information
  135. ```
  136. ## Configuration
  137. MCP Hub uses JSON configuration files to define managed servers with **universal `${}` placeholder syntax** for environment variables and command execution.
  138. ## VS Code Configuration Compatibility
  139. MCP Hub provides seamless compatibility with VS Code's `.vscode/mcp.json` configuration format, enabling you to use the same configuration files across both VS Code and MCP Hub.
  140. ### Supported Features
  141. #### Server Configuration Keys
  142. Both `mcpServers` and `servers` keys are supported:
  143. ```json
  144. {
  145. "servers": {
  146. "github": {
  147. "url": "https://api.githubcopilot.com/mcp/"
  148. },
  149. "perplexity": {
  150. "command": "npx",
  151. "args": ["-y", "server-perplexity-ask"],
  152. "env": {
  153. "API_KEY": "${env:PERPLEXITY_API_KEY}"
  154. }
  155. }
  156. }
  157. }
  158. ```
  159. #### Variable Substitution
  160. MCP Hub supports VS Code-style variable substitution:
  161. - **Environment Variables**: `${env:VARIABLE_NAME}` or `${VARIABLE_NAME}`
  162. - **Workspace Variables**: `${workspaceFolder}`, `${userHome}`, `${pathSeparator}`
  163. - **Command Execution**: `${cmd: command args}`
  164. **Supported Predefined Variables:**
  165. - `${workspaceFolder}` - Directory where mcp-hub is running
  166. - `${userHome}` - User's home directory
  167. - `${pathSeparator}` - OS path separator (/ or \)
  168. - `${workspaceFolderBasename}` - Just the folder name
  169. - `${cwd}` - Alias for workspaceFolder
  170. - `${/}` - VS Code shorthand for pathSeparator
  171. #### VS Code Input Variables
  172. For `${input:}` variables used in VS Code configs, use the `MCP_HUB_ENV` environment variable:
  173. ```bash
  174. # Set input variables globally
  175. export MCP_HUB_ENV='{"input:api-key":"your-secret-key","input:database-url":"postgresql://..."}'
  176. # Then use in config
  177. {
  178. "servers": {
  179. "myserver": {
  180. "env": {
  181. "API_KEY": "${input:api-key}"
  182. }
  183. }
  184. }
  185. }
  186. ```
  187. ### Migration from VS Code
  188. Existing `.vscode/mcp.json` files work directly with MCP Hub. Simply point MCP Hub to your VS Code configuration:
  189. ```bash
  190. mcp-hub --config .vscode/mcp.json --port 3000
  191. ```
  192. ### Multiple Configuration Files
  193. MCP Hub supports loading multiple configuration files that are merged in order. This enables flexible configuration management:
  194. - **Global Configuration**: System-wide settings (e.g., `~/.config/mcphub/global.json`)
  195. - **Project Configuration**: Project-specific settings (e.g., `./.mcphub/project.json`)
  196. - **Environment Configuration**: Environment-specific overrides
  197. When multiple config files are specified, they are merged with later files overriding earlier ones:
  198. ```bash
  199. # Global config is loaded first, then project config overrides
  200. mcp-hub --port 3000 --config ~/.config/mcphub/global.json --config ./.mcphub/project.json
  201. ```
  202. **Merge Behavior:**
  203. - `mcpServers` sections are merged (server definitions from later files override earlier ones)
  204. - Other top-level properties are completely replaced by later files
  205. - Missing config files are silently skipped
  206. ### Universal Placeholder Syntax
  207. - **`${ENV_VAR}`** or **`${env:ENV_VAR}`** - Resolves environment variables
  208. - **`${cmd: command args}`** - Executes commands and uses output
  209. - **`${workspaceFolder}`** - Directory where mcp-hub is running
  210. - **`${userHome}`** - User's home directory
  211. - **`${pathSeparator}`** - OS path separator
  212. - **`${input:variable-id}`** - Resolves from MCP_HUB_ENV (VS Code compatibility)
  213. - **`null` or `""`** - Falls back to `process.env`
  214. ### Configuration Examples
  215. #### Local STDIO Server
  216. ```json
  217. {
  218. "mcpServers": {
  219. "local-server": {
  220. "command": "${MCP_BINARY_PATH}/server",
  221. "args": [
  222. "--token", "${API_TOKEN}",
  223. "--database", "${DB_URL}",
  224. "--secret", "${cmd: op read op://vault/secret}"
  225. ],
  226. "env": {
  227. "API_TOKEN": "${cmd: aws ssm get-parameter --name /app/token --query Parameter.Value --output text}",
  228. "DB_URL": "postgresql://user:${DB_PASSWORD}@localhost/myapp",
  229. "DB_PASSWORD": "${cmd: op read op://vault/db/password}",
  230. "FALLBACK_VAR": null
  231. },
  232. "dev": {
  233. "enabled": true,
  234. "watch": ["src/**/*.js", "**/*.json"],
  235. "cwd": "/absolute/path/to/server/directory"
  236. }
  237. }
  238. }
  239. }
  240. ```
  241. #### Remote Server
  242. ```json
  243. {
  244. "mcpServers": {
  245. "remote-server": {
  246. "url": "https://${PRIVATE_DOMAIN}/mcp",
  247. "headers": {
  248. "Authorization": "Bearer ${cmd: op read op://vault/api/token}",
  249. "X-Custom-Header": "${CUSTOM_VALUE}"
  250. }
  251. }
  252. }
  253. }
  254. ```
  255. ### Configuration Options
  256. MCP Hub supports both STDIO servers and remote servers (streamable-http/SSE). The server type is automatically detected from the configuration. **All fields support the universal `${}` placeholder syntax.**
  257. #### STDIO Server Options
  258. For running script-based MCP servers locally:
  259. - **command**: Command to start the MCP server executable (supports `${VARIABLE}` and `${cmd: command}`)
  260. - **args**: Array of command line arguments (supports `${VARIABLE}` and `${cmd: command}` placeholders)
  261. - **env**: Environment variables with placeholder resolution and system fallback
  262. - **cwd**: The cwd for process spawning the MCP server
  263. - **dev**: Development mode configuration (optional)
  264. - **enabled**: Enable/disable dev mode (default: true)
  265. - **watch**: Array of glob patterns to watch for changes (default: ["**/*.js", "**/*.ts", "**/*.json"])
  266. - **cwd**: **Required** absolute path to the server's working directory for file watching
  267. ##### Global Environment Variables (`MCP_HUB_ENV`)
  268. MCP Hub will look for the environment variable `MCP_HUB_ENV` (a JSON string) in its own process environment. If set, all key-value pairs from this variable will be injected into the environment of every managed MCP server (both stdio and remote). This is useful for passing secrets, tokens, or other shared configuration to all servers without repeating them in each server config.
  269. - Server-specific `env` fields always override values from `MCP_HUB_ENV`.
  270. - Example usage:
  271. ```sh
  272. MCP_HUB_ENV='{"DBUS_SESSION_BUS_ADDRESS":"/run/user/1000/bus","MY_TOKEN":"abc"}' mcp-hub --port 3000 --config path/to/config.json
  273. ```
  274. #### Remote Server Options
  275. For connecting to remote MCP servers:
  276. - **url**: Server endpoint URL (supports `${VARIABLE}` and `${cmd: command}` placeholders)
  277. - **headers**: Authentication headers (supports `${VARIABLE}` and `${cmd: command}` placeholders)
  278. #### Server Type Detection
  279. The server type is determined by:
  280. - STDIO server → Has `command` field
  281. - Remote server → Has `url` field
  282. Note: A server configuration cannot mix STDIO and remote server fields.
  283. #### Placeholder Resolution Order
  284. 1. **Commands First**: `${cmd: command args}` are executed first
  285. 2. **Environment Variables**: `${VAR}` are resolved from `env` object, then `process.env`
  286. 3. **Fallback**: `null` or `""` values fall back to `process.env`
  287. 4. **Multi-pass**: Dependencies between variables are resolved automatically
  288. ## Nix
  289. ### Nixpkgs install
  290. > coming...
  291. ### Flake install
  292. Just add it to your NixOS flake.nix or home-manager:
  293. ```nix
  294. inputs = {
  295. mcp-hub.url = "github:ravitemer/mcp-hub";
  296. ...
  297. }
  298. ```
  299. To integrate mcp-hub to your NixOS/Home Manager configuration, add the following to your environment.systemPackages or home.packages respectively:
  300. ```nix
  301. inputs.mcp-hub.packages."${system}".default
  302. ```
  303. ### Usage without install
  304. If you want to use mcphub.nvim without having mcp-hub server in your PATH you can link the server under the hood adding
  305. the mcp-hub nix store path to the `cmd` command in the plugin config like
  306. [Nixvim](https://github.com/nix-community/nixvim) example:
  307. ```nix
  308. { mcphub-nvim, mcp-hub, ... }:
  309. {
  310. extraPlugins = [mcphub-nvim];
  311. extraConfigLua = ''
  312. require("mcphub").setup({
  313. port = 3000,
  314. config = vim.fn.expand("~/mcp-hub/mcp-servers.json"),
  315. cmd = "${mcp-hub}/bin/mcp-hub"
  316. })
  317. '';
  318. }
  319. # where
  320. {
  321. # For nixpkgs (not available yet)
  322. mcp-hub = pkgs.mcp-hub;
  323. # For flakes
  324. mcp-hub = inputs.mcp-hub.packages."${system}".default;
  325. }
  326. ```
  327. ## Example Integrations
  328. ### Neovim Integration
  329. The [ravitemer/mcphub.nvim](https://github.com/ravitemer/mcphub.nvim) plugin provides seamless integration with Neovim, allowing direct interaction with MCP Hub from your editor:
  330. - Execute MCP tools directly from Neovim
  331. - Access MCP resources within your editing workflow
  332. - Real-time status updates in Neovim
  333. - Auto install mcp servers with marketplace addition
  334. ## REST API
  335. ### Health and Status
  336. #### Health Check
  337. ```bash
  338. GET /api/health
  339. ```
  340. The health endpoint provides comprehensive status information including:
  341. - Current hub state (starting, ready, restarting, restarted, stopping, stopped, error)
  342. - Connected server statuses and capabilities
  343. - Active SSE connection details
  344. - Detailed connection metrics
  345. - Error state details if applicable
  346. Response:
  347. ```json
  348. {
  349. "status": "ok",
  350. "state": "ready",
  351. "server_id": "mcp-hub",
  352. "version": "4.1.1",
  353. "activeClients": 2,
  354. "timestamp": "2024-02-20T05:55:00.000Z",
  355. "servers": [],
  356. "connections": {
  357. "totalConnections": 2,
  358. "connections": [
  359. {
  360. "id": "client-uuid",
  361. "state": "connected",
  362. "connectedAt": "2024-02-20T05:50:00.000Z",
  363. "lastEventAt": "2024-02-20T05:55:00.000Z"
  364. }
  365. ]
  366. },
  367. "workspaces": {
  368. "current": "40123",
  369. "allActive": {
  370. "40123": {
  371. "cwd": "/path/to/project-a",
  372. "config_files": ["/home/user/.config/mcphub/global.json", "/path/to/project-a/.mcphub/project.json"],
  373. "pid": 12345,
  374. "port": 40123,
  375. "startTime": "2025-01-17T10:00:00.000Z",
  376. "state": "active",
  377. "activeConnections": 2,
  378. "shutdownStartedAt": null,
  379. "shutdownDelay": null
  380. }
  381. }
  382. }
  383. }
  384. ```
  385. #### List MCP Servers
  386. ```bash
  387. GET /api/servers
  388. ```
  389. #### Get Server Info
  390. ```bash
  391. POST /api/servers/info
  392. Content-Type: application/json
  393. {
  394. "server_name": "example-server"
  395. }
  396. ```
  397. #### Refresh Server Capabilities
  398. ```bash
  399. POST /api/servers/refresh
  400. Content-Type: application/json
  401. {
  402. "server_name": "example-server"
  403. }
  404. ```
  405. Response:
  406. ```json
  407. {
  408. "status": "ok",
  409. "server": {
  410. "name": "example-server",
  411. "capabilities": {
  412. "tools": ["tool1", "tool2"],
  413. "resources": ["resource1", "resource2"],
  414. "resourceTemplates": []
  415. }
  416. },
  417. "timestamp": "2024-02-20T05:55:00.000Z"
  418. }
  419. ```
  420. #### Refresh All Servers
  421. ```bash
  422. POST /api/refresh
  423. ```
  424. Response:
  425. ```json
  426. {
  427. "status": "ok",
  428. "servers": [
  429. {
  430. "name": "example-server",
  431. "capabilities": {
  432. "tools": ["tool1", "tool2"],
  433. "resources": ["resource1", "resource2"],
  434. "resourceTemplates": []
  435. }
  436. }
  437. ],
  438. "timestamp": "2024-02-20T05:55:00.000Z"
  439. }
  440. ```
  441. #### Start Server
  442. ```bash
  443. POST /api/servers/start
  444. Content-Type: application/json
  445. {
  446. "server_name": "example-server"
  447. }
  448. ```
  449. Response:
  450. ```json
  451. {
  452. "status": "ok",
  453. "server": {
  454. "name": "example-server",
  455. "status": "connected",
  456. "uptime": 123
  457. },
  458. "timestamp": "2024-02-20T05:55:00.000Z"
  459. }
  460. ```
  461. #### Stop Server
  462. ```bash
  463. POST /api/servers/stop?disable=true|false
  464. Content-Type: application/json
  465. {
  466. "server_name": "example-server"
  467. }
  468. ```
  469. The optional `disable` query parameter can be set to `true` to disable the server in the configuration.
  470. Response:
  471. ```json
  472. {
  473. "status": "ok",
  474. "server": {
  475. "name": "example-server",
  476. "status": "disconnected",
  477. "uptime": 0
  478. },
  479. "timestamp": "2024-02-20T05:55:00.000Z"
  480. }
  481. ```
  482. ### Workspace Management
  483. #### List Active Workspaces
  484. ```bash
  485. GET /api/workspaces
  486. ```
  487. Response:
  488. ```json
  489. {
  490. "workspaces": {
  491. "40123": {
  492. "cwd": "/path/to/project-a",
  493. "config_files": ["/home/user/.config/mcphub/global.json", "/path/to/project-a/.mcphub/project.json"],
  494. "pid": 12345,
  495. "port": 40123,
  496. "startTime": "2025-01-17T10:00:00.000Z",
  497. "state": "active",
  498. "activeConnections": 2,
  499. "shutdownStartedAt": null,
  500. "shutdownDelay": null
  501. },
  502. "40567": {
  503. "cwd": "/path/to/project-b",
  504. "config_files": ["/home/user/.config/mcphub/global.json"],
  505. "pid": 54321,
  506. "port": 40567,
  507. "startTime": "2025-01-17T10:05:00.000Z",
  508. "state": "shutting_down",
  509. "activeConnections": 0,
  510. "shutdownStartedAt": "2025-01-17T10:15:00.000Z",
  511. "shutdownDelay": 600000
  512. }
  513. },
  514. "timestamp": "2024-02-20T05:55:00.000Z"
  515. }
  516. ```
  517. ### Marketplace Integration
  518. #### List Available Servers
  519. ```bash
  520. GET /api/marketplace
  521. ```
  522. Query Parameters:
  523. - `search`: Filter by name, description, or tags
  524. - `category`: Filter by category
  525. - `tags`: Filter by comma-separated tags
  526. - `sort`: Sort by "newest", "stars", or "name"
  527. Response:
  528. ```json
  529. {
  530. "servers": [
  531. {
  532. "id": "example-server",
  533. "name": "Example Server",
  534. "description": "Description here",
  535. "author": "example-author",
  536. "url": "https://github.com/user/repo",
  537. "category": "search",
  538. "tags": ["search", "ai"],
  539. "stars": 100,
  540. "featured": true,
  541. "verified": true,
  542. "lastCommit": 1751257963,
  543. "updatedAt": 1751265038
  544. }
  545. ],
  546. "timestamp": "2024-02-20T05:55:00.000Z"
  547. }
  548. ```
  549. #### Get Server Details
  550. ```bash
  551. POST /api/marketplace/details
  552. Content-Type: application/json
  553. {
  554. "mcpId": "example-server"
  555. }
  556. ```
  557. Response:
  558. ```json
  559. {
  560. "server": {
  561. "id": "example-server",
  562. "name": "Example Server",
  563. "description": "Description here",
  564. "author": "example-author",
  565. "url": "https://github.com/user/repo",
  566. "category": "search",
  567. "tags": ["search", "ai"],
  568. "installations": [],
  569. "stars": 100,
  570. "featured": true,
  571. "verified": true,
  572. "lastCommit": 1751257963,
  573. "updatedAt": 1751265038
  574. },
  575. "readmeContent": "# Server Documentation...",
  576. "timestamp": "2024-02-20T05:55:00.000Z"
  577. }
  578. ```
  579. ### MCP Server Operations
  580. #### Execute Tool
  581. ```bash
  582. POST /api/servers/tools
  583. Content-Type: application/json
  584. {
  585. "server_name": "example-server",
  586. "tool": "tool_name",
  587. "arguments": {},
  588. "request_options" : {}
  589. }
  590. ```
  591. #### Access Resource
  592. ```bash
  593. POST /api/servers/resources
  594. Content-Type: application/json
  595. {
  596. "server_name": "example-server",
  597. "uri": "resource://uri",
  598. "request_options" : {}
  599. }
  600. ```
  601. #### Get Prompt
  602. ```bash
  603. POST /api/servers/prompts
  604. Content-Type: application/json
  605. {
  606. "server_name": "example-server",
  607. "prompt": "prompt_name",
  608. "arguments": {},
  609. "request_options" : {}
  610. }
  611. ```
  612. Response:
  613. ```json
  614. {
  615. "result": {
  616. "messages": [
  617. {
  618. "role": "assistant",
  619. "content": {
  620. "type": "text",
  621. "text": "Text response example"
  622. }
  623. },
  624. {
  625. "role": "assistant",
  626. "content": {
  627. "type": "image",
  628. "data": "base64_encoded_image_data",
  629. "mimeType": "image/png"
  630. }
  631. }
  632. ]
  633. },
  634. "timestamp": "2024-02-20T05:55:00.000Z"
  635. }
  636. ```
  637. #### Restart Hub
  638. ```bash
  639. POST /api/restart
  640. ```
  641. Reloads the configuration file and restarts all MCP servers.
  642. Response:
  643. ```json
  644. {
  645. "status": "ok",
  646. "timestamp": "2024-02-20T05:55:00.000Z"
  647. }
  648. ```
  649. ## Real-time Events System
  650. MCP Hub implements a comprehensive real-time events system using Server-Sent Events (SSE) at `/api/events`. This endpoint provides live updates about server status, configuration changes, capability updates, and more.
  651. ### Hub States
  652. The hub server transitions through several states during its lifecycle:
  653. | State | Description |
  654. |-------|-------------|
  655. | `starting` | Initial startup, loading configuration |
  656. | `ready` | Server is running and ready to handle requests |
  657. | `restarting` | Reloading configuration/reconnecting servers |
  658. | `restarted` | Configuration reload complete |
  659. | `stopping` | Graceful shutdown in progress |
  660. | `stopped` | Server has fully stopped |
  661. | `error` | Error state (includes error details) |
  662. You can monitor these states through the `/health` endpoint or SSE events.
  663. ### Event Types
  664. MCP Hub emits several types of events:
  665. #### Core Events
  666. 1. **heartbeat** - Periodic connection health check
  667. ```json
  668. {
  669. "connections": 2,
  670. "timestamp": "2024-02-20T05:55:00.000Z"
  671. }
  672. ```
  673. 2. **hub_state** - Hub server state changes
  674. ```json
  675. {
  676. "state": "ready",
  677. "server_id": "mcp-hub",
  678. "version": "1.0.0",
  679. "pid": 12345,
  680. "port": 3000,
  681. "timestamp": "2024-02-20T05:55:00.000Z"
  682. }
  683. ```
  684. 3. **log** - Server log messages
  685. ```json
  686. {
  687. "type": "info",
  688. "message": "Server started",
  689. "data": {},
  690. "timestamp": "2024-02-20T05:55:00.000Z"
  691. }
  692. ```
  693. #### Subscription Events
  694. 1. **config_changed** - Configuration file changes detected
  695. ```json
  696. {
  697. "type": "config_changed",
  698. "newConfig": {},
  699. "isSignificant": true,
  700. "timestamp": "2024-02-20T05:55:00.000Z"
  701. }
  702. ```
  703. 2. **servers_updating** - Server updates in progress
  704. ```json
  705. {
  706. "type": "servers_updating",
  707. "changes": {
  708. "added": ["server1"],
  709. "removed": [],
  710. "modified": ["server2"],
  711. "unchanged": ["server3"]
  712. },
  713. "timestamp": "2024-02-20T05:55:00.000Z"
  714. }
  715. ```
  716. 3. **servers_updated** - Server updates completed
  717. ```json
  718. {
  719. "type": "servers_updated",
  720. "changes": {
  721. "added": ["server1"],
  722. "removed": [],
  723. "modified": ["server2"],
  724. "unchanged": ["server3"]
  725. },
  726. "timestamp": "2024-02-20T05:55:00.000Z"
  727. }
  728. ```
  729. 4. **tool_list_changed** - Server's tools list updated
  730. ```json
  731. {
  732. "type": "tool_list_changed",
  733. "server": "example-server",
  734. "tools": ["tool1", "tool2"],
  735. "timestamp": "2024-02-20T05:55:00.000Z"
  736. }
  737. ```
  738. 5. **resource_list_changed** - Server's resources/templates updated
  739. ```json
  740. {
  741. "type": "resource_list_changed",
  742. "server": "example-server",
  743. "resources": ["resource1", "resource2"],
  744. "resourceTemplates": [],
  745. "timestamp": "2024-02-20T05:55:00.000Z"
  746. }
  747. ```
  748. 6. **prompt_list_changed** - Server's prompts list updated
  749. ```json
  750. {
  751. "type": "prompt_list_changed",
  752. "server": "example-server",
  753. "prompts": ["prompt1", "prompt2"],
  754. "timestamp": "2024-02-20T05:55:00.000Z"
  755. }
  756. ```
  757. 7. **workspaces_updated** - Active workspaces changed
  758. ```json
  759. {
  760. "type": "workspaces_updated",
  761. "workspaces": {
  762. "40123": {
  763. "cwd": "/path/to/project-a",
  764. "config_files": ["/home/user/.config/mcphub/global.json", "/path/to/project-a/.mcphub/project.json"],
  765. "pid": 12345,
  766. "port": 40123,
  767. "startTime": "2025-01-17T10:00:00.000Z",
  768. "state": "active",
  769. "activeConnections": 2,
  770. "shutdownStartedAt": null,
  771. "shutdownDelay": null
  772. }
  773. },
  774. "timestamp": "2024-02-20T05:55:00.000Z"
  775. }
  776. ```
  777. ### Connection Management
  778. - Each SSE connection is assigned a unique ID
  779. - Connections are automatically cleaned up on client disconnect
  780. - Connection statistics available via `/health` endpoint
  781. - Optional auto-shutdown when no clients are connected
  782. ## Logging
  783. MCP Hub uses structured JSON logging for all events. Logs are written to both console and file following XDG Base Directory Specification:
  784. - **XDG compliant**: `$XDG_STATE_HOME/mcp-hub/logs/mcp-hub.log` (typically `~/.local/state/mcp-hub/logs/mcp-hub.log`)
  785. - **Legacy fallback**: `~/.mcp-hub/logs/mcp-hub.log` (for backward compatibility)
  786. Example log entry:
  787. ```json
  788. {
  789. "type": "error",
  790. "code": "TOOL_ERROR",
  791. "message": "Failed to execute tool",
  792. "data": {
  793. "server": "example-server",
  794. "tool": "example-tool",
  795. "error": "Invalid parameters"
  796. },
  797. "timestamp": "2024-02-20T05:55:00.000Z"
  798. }
  799. ```
  800. Log levels include:
  801. - `info`: Normal operational messages
  802. - `warn`: Warning conditions
  803. - `debug`: Detailed debug information (includes configuration changes)
  804. - `error`: Error conditions (includes error code and stack trace)
  805. Logs are rotated daily and kept for 30 days by default.
  806. ## Workspace Cache
  807. MCP Hub maintains a global workspace cache to track active instances across different working directories with real-time lifecycle management:
  808. - **Cache Location**: `$XDG_STATE_HOME/mcp-hub/workspaces.json` (typically `~/.local/state/mcp-hub/workspaces.json`)
  809. - **Purpose**: Prevents port conflicts, enables workspace discovery, and provides real-time lifecycle tracking
  810. - **Content**: Maps port numbers (as keys) to hub process information with detailed lifecycle state
  811. - **Cleanup**: Automatically removes stale entries when processes are no longer running
  812. ### Cache Structure
  813. ```json
  814. {
  815. "40123": {
  816. "cwd": "/path/to/project-a",
  817. "config_files": ["/home/user/.config/mcphub/global.json", "/path/to/project-a/.mcphub/project.json"],
  818. "pid": 12345,
  819. "port": 40123,
  820. "startTime": "2025-01-17T10:00:00.000Z",
  821. "state": "active",
  822. "activeConnections": 2,
  823. "shutdownStartedAt": null,
  824. "shutdownDelay": null
  825. },
  826. "40567": {
  827. "cwd": "/path/to/project-b",
  828. "config_files": ["/home/user/.config/mcphub/global.json"],
  829. "pid": 54321,
  830. "port": 40567,
  831. "startTime": "2025-01-17T10:05:00.000Z",
  832. "state": "shutting_down",
  833. "activeConnections": 0,
  834. "shutdownStartedAt": "2025-01-17T10:15:00.000Z",
  835. "shutdownDelay": 600000
  836. }
  837. }
  838. ```
  839. ## Error Handling
  840. MCP Hub implements a comprehensive error handling system with custom error classes for different types of errors:
  841. ### Error Classes
  842. - **ConfigError**: Configuration-related errors (invalid config, missing fields)
  843. - **ConnectionError**: Server connection issues (failed connections, transport errors)
  844. - **ServerError**: Server startup/initialization problems
  845. - **ToolError**: Tool execution failures
  846. - **ResourceError**: Resource access issues
  847. - **ValidationError**: Request validation errors
  848. Each error includes:
  849. - Error code for easy identification
  850. - Detailed error message
  851. - Additional context in the details object
  852. - Stack trace for debugging
  853. Example error structure:
  854. ```json
  855. {
  856. "code": "CONNECTION_ERROR",
  857. "message": "Failed to communicate with server",
  858. "details": {
  859. "server": "example-server",
  860. "error": "connection timeout"
  861. },
  862. "timestamp": "2024-02-20T05:55:00.000Z"
  863. }
  864. ```
  865. ## Architecture
  866. ### Hub Server Lifecycle
  867. ```mermaid
  868. sequenceDiagram
  869. participant C as Client
  870. participant H as Hub Server
  871. participant M1 as MCP Server 1
  872. participant M2 as MCP Server 2
  873. Note over H: Server Start (state: starting)
  874. activate H
  875. Note over H: Config Loading
  876. H->>H: Load & Validate Config
  877. H->>H: Watch Config File
  878. H->>H: Initialize SSE Manager
  879. Note over H: Server Connections (state: ready)
  880. H->>+M1: Connect
  881. M1-->>-H: Connected + Capabilities
  882. H->>+M2: Connect
  883. M2-->>-H: Connected + Capabilities
  884. H-->>C: hub_state (ready)
  885. Note over C,H: Client Setup
  886. C->>H: Connect to /api/events (SSE)
  887. H-->>C: connection_opened
  888. Note over C,H: Client Operations
  889. C->>H: Execute Tool (HTTP)
  890. H->>M1: Execute Tool
  891. M1-->>H: Tool Result
  892. H-->>C: HTTP Response
  893. Note over H,C: Real-time Updates
  894. H->>H: Detect Config Change
  895. H-->>C: servers_updating (SSE)
  896. H->>M1: Reconnect with New Config
  897. M1-->>H: Updated Capabilities
  898. H-->>C: servers_updated (SSE)
  899. Note over H,C: Server Events
  900. M2->>H: Tool List Changed
  901. H-->>C: tool_list_changed (SSE)
  902. Note over H: Shutdown Process
  903. Note over C,H: Client Disconnects
  904. H-->>C: hub_state (stopping) (SSE)
  905. H->>M1: Disconnect
  906. H->>M2: Disconnect
  907. H-->>C: hub_state (stopped) (SSE)
  908. deactivate H
  909. ```
  910. The Hub Server coordinates communication between clients and MCP servers:
  911. 1. Starts and connects to configured MCP servers
  912. 2. Handles SSE client connections and events
  913. 3. Routes tool and resource requests to appropriate servers
  914. 4. Monitors server health and maintains capabilities
  915. 5. Manages graceful startup/shutdown processes
  916. ### MCP Server Management
  917. ```mermaid
  918. flowchart TB
  919. A[Hub Server Start] --> B{Config Available?}
  920. B -->|Yes| C[Load Server Configs]
  921. B -->|No| D[Use Default Settings]
  922. C --> E[Initialize Connections]
  923. D --> E
  924. E --> F{For Each MCP Server}
  925. F -->|Enabled| G[Attempt Connection]
  926. F -->|Disabled| H[Skip Server]
  927. G --> I{Connection Status}
  928. I -->|Success| J[Fetch Capabilities]
  929. I -->|Failure| K[Log Error]
  930. J --> L[Store Server Info]
  931. K --> M[Mark Server Unavailable]
  932. L --> N[Monitor Health]
  933. M --> N
  934. N --> O{Health Check}
  935. O -->|Healthy| P[Update Capabilities]
  936. O -->|Unhealthy| Q[Attempt Reconnect]
  937. Q -->|Success| P
  938. Q -->|Failure| R[Update Status]
  939. P --> N
  940. R --> N
  941. ```
  942. The Hub Server actively manages MCP servers through:
  943. 1. Configuration-based server initialization
  944. 2. Connection and capability discovery
  945. 3. Health monitoring and status tracking
  946. 4. Automatic reconnection attempts
  947. 5. Server state management
  948. ### Request Handling
  949. ```mermaid
  950. sequenceDiagram
  951. participant C as Client
  952. participant H as Hub Server
  953. participant M as MCP Server
  954. Note over C,H: Tool Execution
  955. C->>H: POST /api/servers/tools (HTTP)
  956. H->>H: Validate Request & Server
  957. alt Server Not Connected
  958. H-->>C: 503 Server Unavailable (HTTP)
  959. else Server Connected
  960. H->>M: Execute Tool
  961. alt Success
  962. M-->>H: Tool Result
  963. H-->>C: Result Response (HTTP)
  964. else Error
  965. M-->>H: Error Details
  966. H-->>C: Error Response (HTTP)
  967. H-->>C: log (SSE Event)
  968. end
  969. end
  970. Note over C,H: Resource Access
  971. C->>H: POST /api/servers/resources (HTTP)
  972. H->>H: Validate URI & Template
  973. alt Invalid Resource
  974. H-->>C: 404 Not Found (HTTP)
  975. else Server Not Connected
  976. H-->>C: 503 Unavailable (HTTP)
  977. else Valid Request
  978. H->>M: Request Resource
  979. alt Success
  980. M-->>H: Resource Data
  981. H-->>C: Resource Content (HTTP)
  982. else Error
  983. M-->>H: Error Details
  984. H-->>C: Error Response (HTTP)
  985. H-->>C: log (SSE Event)
  986. end
  987. end
  988. Note over C,H: Prompt Execution
  989. C->>H: POST /api/servers/prompts (HTTP)
  990. H->>H: Validate Prompt & Args
  991. alt Invalid Prompt
  992. H-->>C: 404 Not Found (HTTP)
  993. else Server Not Connected
  994. H-->>C: 503 Unavailable (HTTP)
  995. else Valid Request
  996. H->>M: Execute Prompt
  997. alt Success
  998. M-->>H: Messages Array
  999. H-->>C: Messages Response (HTTP)
  1000. else Error
  1001. M-->>H: Error Details
  1002. H-->>C: Error Response (HTTP)
  1003. H-->>C: log (SSE Event)
  1004. end
  1005. end
  1006. ```
  1007. All client requests follow a standardized flow:
  1008. 1. Request validation
  1009. 2. Server status verification
  1010. 3. Request routing to appropriate MCP server
  1011. 4. Response handling and error management
  1012. ## Requirements
  1013. - Node.js >= 18.0.0
  1014. ## MCP Registry
  1015. MCP Hub now uses the [MCP Registry](https://github.com/ravitemer/mcp-registry) system for marketplace functionality. This provides:
  1016. - **Decentralized Server Discovery**: Registry hosted on GitHub Pages for better reliability
  1017. - **Direct GitHub Integration**: README documentation fetched directly from repositories
  1018. - **Enhanced Metadata**: Comprehensive server information including stars, categories, and installation instructions
  1019. - **Better Caching**: Improved cache system with 1-hour TTL for frequent updates
  1020. - **Fallback Support**: Automatic fallback to curl when fetch fails (useful for proxy/VPN environments)
  1021. The registry is updated regularly with new servers and improvements to existing entries.
  1022. ## Todo
  1023. - [x] Implement custom marketplace rather than depending on mcp-marketplace
  1024. - [ ] TUI like mcphub.nvim
  1025. - [ ] Web UI for managing servers
  1026. ## Acknowledgements
  1027. - [ravitemer/mcp-registry](https://github.com/ravitemer/mcp-registry) - For providing the MCP server marketplace endpoints that power MCP Hub's marketplace integration

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.