npm package: @prompty-app/mcp-proxy
Description: MCP Proxy Server - Expose stdio-based MCP servers via HTTP/SSE
Latest version: 1.0.1

# MCP Proxy Server

## Overview

MCP Proxy Server is an intermediary server that exposes stdio-based MCP (Model Context Protocol) servers through HTTP and SSE (Server-Sent Events). It acts as a bridge between client applications (like Prompty) and MCP servers running as independent processes.

## Roles and Responsibilities

### 1. MCP Server Management
- **Auto-start**: Automatically spawn and manage MCP server processes based on configuration
- **Hot-reload**: Automatically update when configuration changes without server restart
- **Lifecycle management**: Handle startup, shutdown, and cleanup of processes safely
- **Auto-initialization**: Automatically perform initialize/initialized handshake with MCP servers
- **Error tracking**: Track and report server startup failures and runtime errors
- **Auto-restart**: Automatically restart failed servers with exponential backoff

### 2. HTTP Transport
- Expose MCP servers through standard HTTP endpoints
- Support JSON-RPC 2.0 protocol
- Handle both requests (with response) and notifications (without response)

### 3. SSE Transport
- Support Server-Sent Events for real-time communication
- Allow clients to receive notifications from MCP servers
- Maintain long-lived connections with keep-alive mechanism
- Real-time server status updates via SSE stream

### 4. Configuration Management
- Read and monitor configuration file (mcp-config.json)
- Automatically detect changes and apply immediately
- Support configuration updates via API

### 5. Monitoring and Health Check
- Provide endpoints to check server status
- Display information about running MCP servers
- Track status, errors, and usage time of each server
- Real-time status streaming with delta updates

## API Endpoints

### Health & Status

#### `GET /health`
Check the health status of the proxy server.

**Response:**
```json
{
  "status": "ok"
}
```

#### `GET /api/servers`
Server-Sent Events stream for real-time status updates of all MCP servers.

**Response:**
- Content-Type: `text/event-stream`
- Events:
  - `status`: Full status of all servers (first event)
  - `delta`: Delta updates when changes occur (per-server)

**Example:**
```
event: status
data: {"notionApi":{"status":"running","lastUsed":"2024-01-01T00:00:00.000Z","pendingRequests":0},"filesystem":{"status":"error","lastUsed":"2024-01-01T00:00:00.000Z","pendingRequests":0,"error":"spawn ENOENT","errorAt":"2024-01-01T00:00:00.000Z"}}

event: delta
data: {"notionApi":{"status":"restarting","lastUsed":"2024-01-01T00:00:05.000Z","pendingRequests":0,"restartCount":1}}

: keep-alive
```

**Server Status Fields:**
- `status`: `'running' | 'starting' | 'stopped' | 'error' | 'restarting'`
- `lastUsed`: ISO timestamp
- `pendingRequests`: Number of pending requests
- `error`: Error message (if any)
- `errorAt`: ISO timestamp of error (if any)
- `restartCount`: Number of restarts (if > 0)

#### `POST /api/config`
Update MCP server configuration via API (no file editing required).

**Request Body:**
```json
{
  "mcpServers": {
    "serverName": {
      "command": "command",
      "args": ["arg1", "arg2"],
      "env": { "KEY": "value" },
      "disabled": false
    }
  }
}
```

### HTTP Transport

#### `POST /:serverName/mcp`
Send request or notification to MCP server via HTTP.

**Path Parameters:**
- `serverName`: Name of the MCP server (from configuration)

**Request Body (Request):**
```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/list",
  "params": {}
}
```

**Request Body (Notification):**
```json
{
  "jsonrpc": "2.0",
  "method": "notifications/tools/list_changed"
}
```

**Response (Request):**
```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "result": { ... }
}
```

**Response (Notification):**
- Status: `204 No Content`

### SSE Transport

#### `GET /:serverName/sse`
Connect to SSE stream to receive notifications from MCP server.

**Path Parameters:**
- `serverName`: Name of the MCP server

**Response:**
- Content-Type: `text/event-stream`
- Events:
  - `endpoint`: Contains URL for sending messages
  - `message`: Notifications from server
  - `close`: Server closed
  - `error`: Error occurred

**Example:**
```
event: endpoint
data: {"uri":"http://localhost:3000/filesystem/message"}

event: message
data: {"jsonrpc":"2.0","method":"notifications/tools/list_changed"}

: keep-alive
```

#### `POST /:serverName/message`
Send request or notification to MCP server in SSE transport.

**Path Parameters:**
- `serverName`: Name of the MCP server

**Request Body:**
Same as HTTP transport endpoint.

**Response:**
Same as HTTP transport endpoint.

## Configuration

### Configuration File: `mcp-config.json`

```json
{
  "mcpServers": {
    "serverName": {
      "command": "command or executable",
      "args": ["arg1", "arg2"],
      "env": {
        "ENV_VAR": "value"
      },
      "disabled": false,
      "autoRestart": true,
      "maxRestarts": 3
    }
  }
}
```

**Fields:**
- `command`: Command to run MCP server (e.g., `npx`, `node`, `python`, `docker`)
- `args`: Array of arguments for the command
- `env`: (Optional) Environment variables for the process
- `disabled`: (Optional) If `true`, server will not be started
- `autoRestart`: (Optional) Auto-restart on failure (default: `true`)
- `maxRestarts`: (Optional) Maximum restart attempts (default: `3`)

### Environment Variables

Create a `.env` file or set environment variables:

```bash
PORT=4953                      # Port for HTTP server (default: 3000)
CONFIG_PATH=./mcp-config.json  # Path to configuration file
IDLE_TIMEOUT=300000            # Timeout for idle servers (ms, default: 5 minutes)
```

## Installation and Usage

### Install Dependencies

```bash
npm install
```

### Development

```bash
npm run dev
```

Server will automatically reload when code changes.

### Build

```bash
npm run build
```

### Production

```bash
npm start
```

## Usage Examples

### HTTP Transport - List Tools

```bash
curl -X POST http://localhost:3000/filesystem/mcp \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "id": 1,
    "method": "tools/list",
    "params": {}
  }'
```

### SSE Transport - Connect and Listen

```bash
# Terminal 1: Connect to SSE stream
curl -N http://localhost:3000/filesystem/sse

# Terminal 2: Send request
curl -X POST http://localhost:3000/filesystem/message \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "id": 1,
    "method": "tools/list",
    "params": {}
  }'
```

### Server Status Stream

```bash
# Connect to status stream to receive real-time updates
curl -N http://localhost:3000/api/servers
```

## Key Features

### ✅ Hot Reload Configuration
Edit `mcp-config.json` and the server will automatically update without restart.

### ✅ Multiple Transport Support
Supports both HTTP and SSE transports for different use cases.

### ✅ Process Management
Automatically manages lifecycle of MCP server processes, including spawn, cleanup, and error handling.

### ✅ Auto-restart with Exponential Backoff
Failed servers automatically restart with configurable retry limits and exponential backoff.

### ✅ Error Tracking and Reporting
Track server failures and expose error information via status endpoint.

### ✅ Auto-initialization
Automatically performs MCP protocol handshake when server starts.

### ✅ Graceful Shutdown
Handles shutdown safely, ensuring all resources are cleaned up properly.

### ✅ Real-time Status Updates
Server-Sent Events stream for monitoring server status changes in real-time.

## Architecture

```
┌─────────────┐
│   Client    │ (Prompty, Web App, etc.)
└──────┬──────┘
       │ HTTP/SSE
       │
┌──────▼──────────────────┐
│   MCP Proxy Server       │
│  ┌────────────────────┐  │
│  │  Config Watcher    │  │ ← Monitors mcp-config.json
│  └────────────────────┘  │
│  ┌────────────────────┐  │
│  │   MCP Manager      │  │ ← Manages processes
│  └────────────────────┘  │
│  ┌────────────────────┐  │
│  │  HTTP/SSE Routes  │  │ ← Exposes endpoints
│  └────────────────────┘  │
└──────┬───────────────────┘
       │ stdio (stdin/stdout)
       │
┌──────▼──────┐
│ MCP Servers │ (filesystem, notion, etc.)
└─────────────┘
```

## License

MIT