Skip to main content
Glama
musadev147

Antigravity MCP Server

by musadev147
README.md
# Model Context Protocol (MCP) Express & TypeScript Server

A highly robust, production-ready, and strictly typed **Model Context Protocol (MCP) Server** built with Node.js, Express.js, TypeScript, and WebSockets. 

This server provides standard JSON-RPC 2.0 communication channels compliant with the MCP specifications, supporting dynamic tool execution, structured resource reading, and prompt template compiling. It also features a stunning, state-of-the-art **Glassmorphism Admin Control Panel & Live API Playground** served at the server root (`http://localhost:3000`).

---

## 🌟 Key Features

*   **Complete MCP Protocol Compliance**: Implements the standardized JSON-RPC 2.0 message handshake and method routing structures over both **WebSockets (`/ws`)** and **HTTP POST SSE Gateway (`/api/mcp`)**.
*   **Aesthetic Admin Dashboard & Playground**: A premium dark-mode, glassmorphism-designed front-end interface featuring:
    *   **Live Metrics Grid**: Tracking active connections, Cumulative requests count, allocated process heap memory, and simulated system CPU.
    *   **Interactive Sandbox Playground**: Dynamically renders input parameter forms directly parsed from tools/prompts schemas, compiles standard JSON-RPC request objects, sends requests, and displays color-coded responses.
    *   **Real-time Log Stream Terminal**: Watch system transactions, security check notifications, and tools validation events update in real-time.
*   **Sample Tools Out-of-the-Box**:
    *   `weather`: Generates realistic weather reports and forecasts based on location string hashes (consistent, stable results across Celsius and Fahrenheit).
    *   `calculator`: Scientific mathematical calculator (addition, subtraction, multiplication, division, exponentiation, square roots) with advanced input validation (division by zero, negative square roots).
    *   `dbQuery`: Analytics SELECT and STATS queries against a relational mock database containing `users`, `products`, and `orders` tables.
*   **Sample Resources Out-of-the-Box**:
    *   `mcp://server/config`: Exposes active server environments, capabilities, and registered module routing definitions.
    *   `mcp://server/logs`: Serves the in-memory circular buffer (last 100 entries) as line-by-line formatted developer plain text logs.
*   **Sample Prompt Templates**:
    *   `code_reviewer`: Professional, Principal Engineer review prompt layout accepting raw code blocks and languages.
    *   `system_optimizer`: Diagnostic optimization blueprint accepting architectures details and system bottleneck symptoms.
    *   `data_analyst`: Dynamic tabular/JSON data analytics and statistical insights extractor.
*   **Token-Based Middleware Security**: Comprehensive authorization checks (x-api-key headers, Bearer tokens, or query strings) supported natively across HTTP and WebSocket routes.

---

## šŸ“ Project Directory Structure

```
src/
ā”œā”€ā”€ server/
│   ā”œā”€ā”€ index.ts        # Express bootstrapping, CORS, REST gateways, & HTTP Server
│   ā”œā”€ā”€ mcp.ts          # Core MCP JSON-RPC protocol router & method controllers
│   └── websocket.ts    # WS server setup, authorization, and metrics log streams
ā”œā”€ā”€ tools/
│   ā”œā”€ā”€ index.ts        # Tool registry coordinator & dispatcher mapping
│   ā”œā”€ā”€ weather.ts      # weather tool execution and simulation handler
│   ā”œā”€ā”€ calculator.ts   # calculator tool scientific operations handler
│   └── dbQuery.ts      # dbQuery tool relational select/stats analyzer
ā”œā”€ā”€ resources/
│   ā”œā”€ā”€ index.ts        # Resource registry coordinator & dynamic loader
│   ā”œā”€ā”€ config.ts       # mcp://server/config system configurations provider
│   └── systemLogs.ts   # mcp://server/logs live logs file stream provider
ā”œā”€ā”€ prompts/
│   ā”œā”€ā”€ index.ts        # Prompt template registry coordinator
│   └── templates.ts    # code_reviewer, system_optimizer, & data_analyst prompts
ā”œā”€ā”€ middleware/
│   ā”œā”€ā”€ auth.ts         # Secure API Key & Authorization Bearer validator
│   ā”œā”€ā”€ error.ts        # Centralized Express boundary & JSON-RPC error builder
│   └── logging.ts      # Request latency tracking logger middleware
ā”œā”€ā”€ utils/
│   ā”œā”€ā”€ logger.ts       # Custom ANSI colored printer with circular buffer & emitters
│   └── validator.ts    # Dependency-free JSON Schema compliance verification tool
ā”œā”€ā”€ types/
│   ā”œā”€ā”€ index.ts        # Internal logs, registries, and metrics definitions
│   └── mcp.ts          # Standard MCP and JSON-RPC 2.0 protocol specifications
└── public/
    └── index.html      # Responsive visual dashboard and dynamic sandbox playground
```

---

## šŸš€ Setup & Installation Instructions

### 1. Prerequisites
Make sure you have [Node.js](https://nodejs.org/) installed (v18+ recommended).

### 2. Install Dependencies
In the workspace directory, run:
```bash
npm install
```

### 3. Configure the Environment
Create a `.env` file in the root directory (one is pre-configured for you):
```env
PORT=3000
API_KEY=mcp_secret_token_2026
NODE_ENV=development
SERVER_NAME=Antigravity MCP Server
```
*Note: If `API_KEY` is commented out or left blank, authentication is fully disabled, allowing public access.*

### 4. Running the Server

#### Development Mode (with hot-reloading)
Runs `ts-node-dev` to watch and hot-reload changes instantly:
```bash
npm run dev
```

#### Production Build & Start
Compiles TypeScript down to optimized JavaScript (`/dist`) and runs the production build:
```bash
npm run build
npm start
```

---

## šŸ“” REST API & Gateway Blueprints

All REST API routes are fully authenticated when `API_KEY` is configured in `.env`. Authenticate requests by adding either the `x-api-key` header, `Authorization: Bearer <key>` header, or appending `?token=<key>` to the query string.

### 1. Health & Server Specifications Check
```bash
curl -X GET http://localhost:3000/api/health \
  -H "x-api-key: mcp_secret_token_2026"
```

### 2. Standard MCP Protocol POST Gateway
Send standard JSON-RPC 2.0 payloads directly to `/api/mcp`.
```bash
# Call Tools List
curl -X POST http://localhost:3000/api/mcp \
  -H "Content-Type: application/json" \
  -H "x-api-key: mcp_secret_token_2026" \
  -d '{"jsonrpc":"2.0", "id": 1, "method": "tools/list", "params": {}}'

# Call Weather Tool
curl -X POST http://localhost:3000/api/mcp \
  -H "Content-Type: application/json" \
  -H "x-api-key: mcp_secret_token_2026" \
  -d '{"jsonrpc":"2.0", "id": 2, "method": "tools/call", "params": {"name": "weather", "arguments": {"location": "San Francisco", "days": 3, "unit": "fahrenheit"}}}'
```

### 3. Relational Web Services Endpoints

#### List Tools
`GET /api/tools`
```bash
curl -X GET http://localhost:3000/api/tools -H "x-api-key: mcp_secret_token_2026"
```

#### Execute Tool
`POST /api/tools/:name` (Accepts arguments directly in body JSON)
```bash
curl -X POST http://localhost:3000/api/tools/calculator \
  -H "Content-Type: application/json" \
  -H "x-api-key: mcp_secret_token_2026" \
  -d '{"operation": "power", "a": 5, "b": 3}'
```

#### List Resources
`GET /api/resources`
```bash
curl -X GET http://localhost:3000/api/resources -H "x-api-key: mcp_secret_token_2026"
```

#### Read Specific Resource URI
`GET /api/resources/read?uri=<resource_uri>`
```bash
curl -X GET "http://localhost:3000/api/resources/read?uri=mcp://server/config" \
  -H "x-api-key: mcp_secret_token_2026"
```

#### List Prompt Templates
`GET /api/prompts`
```bash
curl -X GET http://localhost:3000/api/prompts -H "x-api-key: mcp_secret_token_2026"
```

#### Compile Prompt Template
`POST /api/prompts/:name`
```bash
curl -X POST http://localhost:3000/api/prompts/code_reviewer \
  -H "Content-Type: application/json" \
  -H "x-api-key: mcp_secret_token_2026" \
  -d '{"code": "const a = () => { return 42; };", "language": "JavaScript"}'
```

---

## šŸ”Œ WebSocket JSON-RPC channel

Connect standard WebSocket clients (such as MCP client environments) to:
`ws://localhost:3000/ws?token=mcp_secret_token_2026`

All messages exchanged over WebSocket must conform strictly to JSON-RPC 2.0 structures.

### Example Exchange

#### 1. Initialize Handshake
**Client -> Server**:
```json
{
  "jsonrpc": "2.0",
  "id": 101,
  "method": "initialize",
  "params": {
    "protocolVersion": "1.0.0",
    "capabilities": {},
    "clientInfo": {
      "name": "Custom-Client",
      "version": "1.0"
    }
  }
}
```

**Server -> Client**:
```json
{
  "jsonrpc": "2.0",
  "id": 101,
  "result": {
    "protocolVersion": "1.0.0",
    "capabilities": {
      "tools": { "listChanged": false },
      "resources": { "subscribe": false, "listChanged": false },
      "prompts": { "listChanged": false }
    },
    "serverInfo": {
      "name": "Antigravity MCP Server",
      "version": "1.0.0"
    }
  }
}
```

---

## šŸ› ļø Registering with LLM Clients (e.g. Claude Desktop)

To connect this custom MCP server to **Claude Desktop**, add the configuration into your `claude_desktop_config.json` file:

### For macOS
File location: `~/Library/Application Support/Claude/claude_desktop_config.json`

Add the following inside the `"mcpServers"` block (Note: Adjust absolute pathing to point to your compiled project location):

```json
{
  "mcpServers": {
    "express-mcp-server": {
      "command": "node",
      "args": [
        "/Users/laptopheaven/mcp-skill/dist/server/index.js"
      ],
      "env": {
        "PORT": "3000",
        "API_KEY": "mcp_secret_token_2026",
        "NODE_ENV": "production",
        "SERVER_NAME": "Production Claude MCP Server"
      }
    }
  }
}
```

Restart Claude Desktop, and you will see the Weather, Calculator, and Mock Database querying tools appear in the attachments/tools toolbar!

---

## ā˜ļø Cloud Deployment Guides

The project is pre-configured for instant deployments to **Render** or **Fly.io** using the provided declarative manifest blueprints.

### Option A: One-Click Blueprint Deploy on Render
The repository includes a declarative `render.yaml` blueprint.
1. Push your codebase to a personal GitHub or GitLab repository.
2. Go to the [Render Dashboard](https://dashboard.render.com/) and select **Blueprints** -> **New Blueprint Instance**.
3. Link your repository. Render will automatically read the `render.yaml` config and:
   - Provision a Node.js web service.
   - Install dependencies and build: `npm install && npm run build`.
   - Boot utilizing: `npm start` on port `10000`.
   - **Automatically generate a secure secret API key** for your `API_KEY` environmental variable. Go to your Render service **Environment** settings to retrieve this secret!

### Option B: Containerized Deploy on Fly.io
The repository includes both a two-stage `Dockerfile` and a `fly.toml` definition.
1. Install the [Fly CLI](https://fly.io/docs/hands-on/install-cli/) and log in: `fly auth login`.
2. Initialize configuration: `fly launch` (select "Copy settings from fly.toml" if prompted).
3. Securely set your custom API authentication secret:
   ```bash
   fly secrets set API_KEY="your_secret_mcp_auth_token_value"
   ```
4. Deploy the application: `fly deploy`.
5. Your live admin control panel and JSON-RPC WebSocket will be hosted at: `https://your-app-name.fly.dev`