# Zephex MCP Proxy

[![npm version](https://img.shields.io/npm/v/zephex.svg)](https://www.npmjs.com/package/zephex)
[![npm downloads](https://img.shields.io/npm/dm/zephex.svg)](https://www.npmjs.com/package/zephex)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

JSON-RPC router combining multiple MCP backends into one endpoint. Supports STDIO (local) and Streamable HTTP (remote) transports with API key auth and Stripe billing.

### Supported Clients

Works with **Cursor** • **Claude Desktop** • **VS Code** • **Windsurf** • and any MCP-compatible client

## MCP Compatibility

- Supported `MCP-Protocol-Version` values: `2025-03-26`, `2025-06-18`, `2025-11-25`
- Primary MCP endpoint is `/mcp` (Streamable HTTP). Compatibility alias: `/mcp/sse`.
- Authentication uses an API key in the `Authorization` header (`Authorization: Bearer mcp_...` or `Authorization: mcp_...`) by default; OAuth/JWT bearer tokens are not used by most MCP clients.
- Browser check: `GET /` returns a small status page (HTML for browsers, JSON otherwise).

## Quick Start

```bash
npx zephex setup
```

**Shorter commands** (install once, then use any alias):

```bash
npm install -g zephex@latest
mcpcli setup          # same as zephex setup
zepx help             # same as zephex help
```

Terminal tools (same MCP API, human output):

```bash
npx zephex get-context
npx zephex find-code "auth middleware"
npx zephex summarize src/index.ts
npx zephex architecture
npx zephex cli-guide          # full Mode 2 guide
npx zephex help terminal      # all aliases
```

Works from **any project folder** on Mac/Linux. Monorepos auto-index the richest package (`mcp-proxy/` from repo root). Default is **local files**, not `git remote` — use `--path github:owner/repo` only when you mean it.

Docs: [zephex.dev/docs/cli-terminal](https://zephex.dev/docs/cli-terminal)

Or install globally (enables `zephex`, `mcpcli`, `zepx`, `zphx`, `mcpz`, `zepcli`, `zephx`):

```bash
npm install -g zephex@latest
mcpcli init              # first-run wizard → zephex.dev/cli/auth
mcpcli connect --cursor  # same as setup / login
```

**Account lifecycle** (all bins: `mcpcli`, `zephex`, `zepx`, `zphx`, …):

```bash
mcpcli connect --claude-code
mcpcli disconnect --vscode
mcpcli reconnect --zed
mcpcli logout --all
mcpcli update --apply
mcpcli list
```

Login URL: **https://zephex.dev/cli/auth** · Help: `mcpcli connect --help`  
Install reference: [download.md](./download.md) · Docs: [cli-account](https://zephex.dev/docs/cli-account)

## MCP Client Configuration

### Claude Desktop (STDIO mode)

Add to `claude_desktop_config.json`:

```json
{
  "mcpServers": {
    "zephex": {
      "type": "stdio",
      "command": "npx",
      "args": ["-y", "zephex"],
      "env": {
        "ZEPHEX_API_KEY": "mcp_sk_your_api_key"
      }
    }
  }
}
```

Get your API key from the [dashboard](https://zephex.dev/dashboard/api-keys).

### Cursor

```json
{
  "mcpServers": {
    "zephex": {
      "command": "npx",
      "args": ["-y", "zephex"],
      "env": {
        "ZEPHEX_API_KEY": "mcp_sk_your_api_key"
      }
    }
  }
}
```

## Features

- **Multi-backend routing** - Combine multiple MCP servers with namespaced tools
- **Dual transport** - STDIO for local, HTTP for remote access
- **Project analyzer** - Detect languages, frameworks, and project structure
- **API key authentication** - SHA-256 hashed keys with `mcp_sk_` prefix
- **Optional JWT auth** - Supabase JWT validation (off by default for MCP clients)
- **SSO integration** - Enterprise single sign-on (Okta, Azure AD, Google)
- **Usage-based billing** - Stripe Meters API integration
- **Enterprise billing** - Custom contracts with invoice-based payment
- **Rate limiting** - Per-user request limits by tier
- **SLA tracking** - Uptime monitoring with service credits
- **Dashboard** - Next.js app for key management and billing

## Built-in Analyzer Tools

The proxy includes intelligent project analysis tools:

### analyzer__detect_stack

Detect programming languages, frameworks, and build systems:

```json
{
  "name": "analyzer__detect_stack",
  "arguments": {
    "path": "/path/to/project"
  }
}
```

Returns: languages, frameworks, build system, runtime requirements, monorepo detection.

### analyzer__get_structure

Get directory structure and identify key files:

```json
{
  "name": "analyzer__get_structure",
  "arguments": {
    "path": "/path/to/project",
    "maxDepth": 4,
    "maxFiles": 500
  }
}
```

Returns: directory tree, key files (entry points, configs, docs), file statistics.

**Supported:** TypeScript, JavaScript, Python, Go, Rust, Java, Ruby, PHP, and 40+ frameworks.

## Built-in Security Scanner Tools

Scan code for security vulnerabilities using Semgrep with OWASP 2025 mapping:

### scanner__security_check

Quick security scan of specific files:

```json
{
  "name": "scanner__security_check",
  "arguments": {
    "projectPath": "/path/to/project",
    "severity": "high"
  }
}
```

### scanner__full_scan

Comprehensive project scan with OWASP mapping:

```json
{
  "name": "scanner__full_scan",
  "arguments": {
    "projectPath": "/path/to/project",
    "languages": ["typescript", "python"],
    "frameworks": ["nextjs"],
    "includeOwasp": true
  }
}
```

Returns: findings with severity, OWASP 2025 category, CWE IDs, file locations, and fix suggestions.

### scanner__get_rules

List available Semgrep rulesets:

```json
{
  "name": "scanner__get_rules",
  "arguments": {
    "language": "python"
  }
}
```

**Scanner Tier Limits:**

| Tier | Scans/Hour | Max Files |
|------|------------|-----------|
| free | 10 | 100 |
| pro | 100 | 1,000 |
| enterprise | 1,000 | 10,000 |

## Tier Limits

| Tier | Requests/month | Backends | SLA | Price |
|------|----------------|----------|-----|-------|
| free | 300 | 3 | - | $0 |
| pro | 3,000 | 10 | 99.9% | $7/mo |
| max | 10,000 | 20 | 99.95% | $19/mo |
| enterprise | custom | unlimited | 99.99% | custom |

## Authentication

### API Keys

Standard authentication using `mcp_sk_` prefixed keys:

```
Authorization: Bearer mcp_sk_your_api_key
```

### Optional JWT Tokens (disabled by default)

Optional: Bearer tokens from Supabase Auth are also supported:

```
Authorization: Bearer eyJhbGciOiJIUzI1NiIs...
```

JWT auth is disabled by default for `/mcp`. To enable it, set:

```
MCP_ALLOW_JWT_AUTH=true
```

JWT tokens are validated for:
- Signature (using `SUPABASE_JWT_SECRET`)
- Expiration (`exp` claim)
- Audience (`aud` claim must match `JWT_AUDIENCE`)

### OAuth

OAuth discovery endpoints exist only on the legacy HTTP server (`src/server/http.ts`) and are not part of the hosted Streamable HTTP MCP surface.

## Admin Dashboard

Platform administrators can access analytics and user management at `/dashboard/admin`.

### Features
- **Revenue Metrics** - MRR, ARR, ARPU, NRR, Quick Ratio
- **User Management** - Search, filter, tier changes, impersonation
- **Cohort Analysis** - Retention heatmap with CSV export
- **Churn Detection** - Early warning signals for at-risk users
- **Audit Log** - All admin actions tracked

### Admin Setup

1. Set admin emails in environment:
```bash
ADMIN_EMAILS=admin@company.com,cto@company.com
```

2. Users with matching emails get `role: admin` on signup

3. Admin section appears in sidebar for admin users

### Aggregation Jobs

Analytics data is pre-aggregated via scheduled Edge Functions:

| Job | Schedule | Purpose |
|-----|----------|---------|
| aggregate-daily-stats | 1 AM UTC | Usage metrics per user |
| aggregate-revenue | 2 AM UTC | MRR, ARR, customer counts |
| detect-churn-signals | 3 AM UTC | Churn risk detection |

Jobs use pg_cron + pg_net to trigger Supabase Edge Functions.

### Churn Signals

| Signal | Weight | Trigger |
|--------|--------|---------|
| usage_decline | 0.30 | 7-day avg < 50% of prior 23 days |
| inactivity | 0.20 | No activity for 14+ days (paying) |
| payment_failed | 0.25 | Stripe payment failure |
| downgrade | 0.25 | Paid → free tier change |

Risk levels: >0.7 = high, >0.4 = medium, ≤0.4 = low

## Enterprise Features

### SSO Configuration

Enterprise users can configure SSO via the dashboard:

1. Go to **Settings > SSO**
2. Enter your company email domain (e.g., `company.com`)
3. Contact support to configure your IdP (Okta, Azure AD, Google Workspace)
4. Optionally enable "Require SSO" to block password login

### Enterprise Billing

Custom contracts with:
- Negotiated pricing and volume discounts
- Invoice-based billing (Net 30/60/90)
- Annual billing with upfront payment
- Custom SLA targets

Contact sales for enterprise pricing.

### Usage Reports

Enterprise admins can generate usage reports:
- Requests by user
- Tool invocations by type
- Uptime percentage
- CSV export for chargeback

## Environment Variables

### Required for HTTP mode

| Variable | Description |
|----------|-------------|
| `SUPABASE_URL` | Supabase project URL |
| `SUPABASE_SERVICE_ROLE_KEY` | Supabase service role key |

### Optional

| Variable | Description | Default |
|----------|-------------|---------|
| `PORT` | HTTP server port | `3000` |
| `HTTP_MODE` | Enable HTTP mode | `false` |
| `ALLOWED_HOSTS` | Comma-separated allowed hosts | `localhost,127.0.0.1` |
| `JWT_AUDIENCE` | Expected JWT audience | `authenticated` |
| `UPSTASH_REDIS_REST_URL` | Upstash Redis URL for rate limiting | - |
| `UPSTASH_REDIS_REST_TOKEN` | Upstash Redis token | - |
| `METRICS_TOKEN` | Enables `GET /metrics` (send `x-metrics-token`) | - |
| `MCP_ALLOW_STDIO_BACKENDS_IN_PROD` | Allow `transport:"stdio"` backends in production | `false` |
| `STRIPE_ENTERPRISE_PRICE_ID` | Stripe price for enterprise tier | - |
| `INSTATUS_API_KEY` | Status page API key | - |
| `INSTATUS_PAGE_ID` | Status page ID | - |
| `ADMIN_EMAILS` | Comma-separated admin emails | - |
| `ADMIN_RATE_LIMIT` | Admin requests per hour | `100` |
| `ANALYTICS_RETENTION_DAYS` | Days to keep daily stats | `365` |

## Backend Configuration

Configure backends in `config/backends.json`:

```json
{
  "backends": [
    {
      "key": "filesystem",
      "name": "Filesystem MCP Server",
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/dir"],
      "transport": "stdio",
      "prefix": "fs",
      "pool": { "size": 2 },
      "enabled": true
    },
    {
      "key": "github",
      "name": "GitHub MCP Server",
      "transport": "sse",
      "url": "https://your-github-mcp.example.com/sse",
      "envFrom": ["GITHUB_TOKEN"],
      "enabled": true
    }
  ]
}
```

Tools are namespaced: `filesystem__read_file`, `github__search_repositories`.

## Security

See [/security](https://your-dashboard.vercel.app/security) for:
- Encryption details (AES-256-GCM at rest, TLS 1.3 in transit)
- Access control documentation
- Audit logging information
- SOC 2 compliance timeline

## Development

```bash
# Clone and install
git clone https://github.com/anthropic/mcp-proxy.git
cd mcp-proxy
bun install

# STDIO mode (local)
bun run dev:stdio

# HTTP mode (remote)
bun run dev:http

# Dashboard
cd dashboard && bun run dev

# Run tests
bun test
```

## Railway Deployment

### Build the Docker Image Locally

```bash
docker build -t zephex .
docker run --cap-add=SYS_ADMIN -p 8080:8080 zephex
```

Note: `--cap-add=SYS_ADMIN` is required locally for Chrome's sandbox. Railway handles this automatically.

### Deploy to Railway

1. Push this repo to GitHub
2. Create a new Railway project → Deploy from GitHub repo
3. Railway auto-detects Dockerfile and railway.json
4. Set required environment variables in Railway dashboard:
   - `PORT=8080`
   - `HTTP_MODE=true`
   - `NODE_ENV=production`
   - `SUPABASE_URL`, `SUPABASE_ANON_KEY`, etc.
5. Wait for the health check to pass (green status)
6. Copy the Railway public URL from Settings → Networking

### Testing the Deployed Server

```bash
# Test 1: Verify tools/list returns Zephex_dev_info
curl -s -X POST https://YOUR-URL.railway.app/mcp \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}' \
  | jq '.result.tools[] | select(.name=="Zephex_dev_info") | {name, title}'

# Test 2: Run Zephex_dev_info tool
curl -s -X POST https://YOUR-URL.railway.app/mcp \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -d '{
    "jsonrpc":"2.0",
    "id":2,
    "method":"tools/call",
    "params":{
      "name":"Zephex_dev_info",
      "arguments":{"url":"https://example.com"}
    }
  }' \
  | jq '.result.content[0].text | fromjson | {url, content_length}'
```

### Troubleshooting

- Chrome fails to start: Ensure `PUPPETEER_EXECUTABLE_PATH=/usr/bin/google-chrome` is set
- Health check fails: Confirm `PORT=8080` and `/health` returns 200
- Tool not found: Check that the tool is registered in `src/handlers/tools.ts`

## License

MIT
