Claude
Skills
Sign in
Back

mcp-server

Included with Lifetime
$97 forever

Deploy a remote MCP (Model Context Protocol) server with OAuth 2.1 authentication. Agents connect via Streamable HTTP, authenticate with PKCE, and access your custom tools. Use this skill when the user says "setup mcp server", "create mcp server", "serve mcp tools", "deploy mcp", or "remote mcp server".

Cloud & DevOps

What this skill does


# Remote MCP Server with OAuth 2.1

Creates a standalone, deployable MCP server that agents (Claude Code, Claude Desktop, VS Code, etc.) can connect to via URL and authenticate using OAuth 2.1 with PKCE. Built with Hono, the MCP TypeScript SDK, Drizzle ORM, and PostgreSQL.

## What This Creates

A single deployable server exposing:

| Endpoint | Method | Purpose |
|----------|--------|---------|
| `/mcp` | POST/GET/DELETE | MCP Streamable HTTP transport |
| `/.well-known/oauth-protected-resource` | GET | Protected Resource Metadata (RFC 9728) |
| `/.well-known/oauth-authorization-server` | GET | Authorization Server Metadata (RFC 8414) |
| `/oauth/register` | POST | Dynamic Client Registration (RFC 7591) |
| `/oauth/authorize` | GET/POST | User login + consent page |
| `/oauth/token` | POST | Token exchange and refresh |
| `/health` | GET | Health check |

Agents connect by adding:
```bash
claude mcp add --transport http my-server https://your-server.com/mcp
```

## Project Structure

```
├── src/
│   ├── index.ts                 # Entry point — HTTP server + Hono + MCP handler
│   ├── env.ts                   # Zod-validated environment
│   ├── db/
│   │   ├── index.ts             # Drizzle client (postgres.js)
│   │   └── schema.ts            # All tables: users, oauth_clients, codes, tokens
│   ├── auth/
│   │   └── password.ts          # scrypt password hashing
│   ├── oauth/
│   │   ├── metadata.ts          # .well-known endpoints
│   │   ├── register.ts          # Dynamic Client Registration
│   │   ├── authorize.ts         # Login + consent page
│   │   ├── token.ts             # Token exchange + refresh
│   │   └── verify.ts            # Token verification + generation
│   ├── mcp/
│   │   ├── server.ts            # McpServer instance + tool registration
│   │   └── handler.ts           # Streamable HTTP session manager
│   └── seed.ts                  # Seed a test user
├── docker-compose.yml           # PostgreSQL 17
├── drizzle.config.ts            # Drizzle Kit config
├── tsconfig.json
├── package.json
└── .env.local
```

## Prerequisites

- **Bun** installed (`curl -fsSL https://bun.sh/install | bash`)
- **Docker** running (for PostgreSQL)

## Installation

```bash
bun init -y
bun add hono @hono/node-server @modelcontextprotocol/sdk drizzle-orm postgres zod
bun add -d drizzle-kit @types/node typescript
```

## Environment Variables

### Create `.env.local`

```env
DATABASE_URL=postgresql://postgres:postgres@localhost:5432/mcp
MCP_SERVER_URL=http://localhost:3001
PORT=3001
```

**Production**: Set `MCP_SERVER_URL` to your public HTTPS URL (e.g., `https://mcp.yourapp.com`).

## Docker Setup

### Create `docker-compose.yml`

```yaml
services:
  postgres:
    image: postgres:17-alpine
    ports:
      - "5432:5432"
    environment:
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: postgres
      POSTGRES_DB: mcp
    volumes:
      - postgres_data:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD", "pg_isready", "-U", "postgres"]
      interval: 5s
      timeout: 5s
      retries: 5
      start_period: 30s
    restart: unless-stopped

volumes:
  postgres_data:
```

Start PostgreSQL:

```bash
docker compose up -d
```

## Setup Steps

### Step 1: Create `tsconfig.json`

```json
{
  "compilerOptions": {
    "target": "ESNext",
    "module": "ESNext",
    "moduleResolution": "bundler",
    "strict": true,
    "skipLibCheck": true,
    "outDir": "dist",
    "rootDir": "src",
    "baseUrl": ".",
    "paths": {
      "@/*": ["./src/*"]
    },
    "types": ["bun-types"]
  },
  "include": ["src/**/*.ts"],
  "exclude": ["node_modules"]
}
```

### Step 2: Create `drizzle.config.ts`

```typescript
import { defineConfig } from "drizzle-kit";

export default defineConfig({
  schema: "./src/db/schema.ts",
  out: "./drizzle",
  dialect: "postgresql",
  dbCredentials: {
    url: process.env.DATABASE_URL ?? "",
  },
});
```

### Step 3: Create `src/env.ts`

```typescript
import { z } from "zod";

const envSchema = z.object({
  DATABASE_URL: z.string(),
  MCP_SERVER_URL: z.string().url(),
  PORT: z.coerce.number().default(3001),
});

export const env = envSchema.parse(process.env);
```

### Step 4: Create `src/db/index.ts`

```typescript
import { drizzle } from "drizzle-orm/postgres-js";
import postgres from "postgres";
import * as schema from "./schema";

const connectionString = process.env.DATABASE_URL;
if (!connectionString) {
  throw new Error("DATABASE_URL is not set");
}

export const client = postgres(connectionString);
export const db = drizzle(client, { schema });
```

### Step 5: Create `src/db/schema.ts`

All database tables in one file — users and OAuth entities.

```typescript
import { pgTable, text, timestamp, jsonb } from "drizzle-orm/pg-core";

// --- Users ---

export const users = pgTable("users", {
  id: text("id").primaryKey(),
  email: text("email").notNull().unique(),
  passwordHash: text("password_hash").notNull(),
  name: text("name").notNull(),
  createdAt: timestamp("created_at", { withTimezone: true })
    .notNull()
    .defaultNow(),
});

// --- OAuth Clients (from Dynamic Client Registration) ---

export const oauthClients = pgTable("oauth_clients", {
  clientId: text("client_id").primaryKey(),
  clientSecret: text("client_secret"),
  clientName: text("client_name").notNull(),
  redirectUris: jsonb("redirect_uris").$type<string[]>().notNull(),
  grantTypes: jsonb("grant_types").$type<string[]>().notNull(),
  createdAt: timestamp("created_at", { withTimezone: true })
    .notNull()
    .defaultNow(),
});

// --- Authorization Codes ---

export const oauthCodes = pgTable("oauth_codes", {
  code: text("code").primaryKey(),
  clientId: text("client_id")
    .notNull()
    .references(() => oauthClients.clientId),
  userId: text("user_id")
    .notNull()
    .references(() => users.id),
  redirectUri: text("redirect_uri").notNull(),
  scope: text("scope").notNull().default(""),
  codeChallenge: text("code_challenge").notNull(),
  codeChallengeMethod: text("code_challenge_method").notNull().default("S256"),
  expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
  createdAt: timestamp("created_at", { withTimezone: true })
    .notNull()
    .defaultNow(),
});

// --- Access Tokens ---

export const oauthAccessTokens = pgTable("oauth_access_tokens", {
  token: text("token").primaryKey(),
  clientId: text("client_id")
    .notNull()
    .references(() => oauthClients.clientId),
  userId: text("user_id")
    .notNull()
    .references(() => users.id),
  scope: text("scope").notNull().default(""),
  expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
  createdAt: timestamp("created_at", { withTimezone: true })
    .notNull()
    .defaultNow(),
});

// --- Refresh Tokens ---

export const oauthRefreshTokens = pgTable("oauth_refresh_tokens", {
  token: text("token").primaryKey(),
  clientId: text("client_id")
    .notNull()
    .references(() => oauthClients.clientId),
  userId: text("user_id")
    .notNull()
    .references(() => users.id),
  scope: text("scope").notNull().default(""),
  expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
  createdAt: timestamp("created_at", { withTimezone: true })
    .notNull()
    .defaultNow(),
});
```

### Step 6: Create `src/auth/password.ts`

```typescript
import { scryptSync, randomBytes, timingSafeEqual } from "node:crypto";

const SCRYPT_PARAMS = { N: 16384, r: 8, p: 1, maxmem: 128 * 16384 * 8 * 2 };
const KEY_LENGTH = 64;

export function hashPassword(password: string): string {
  const salt = randomBytes(16).toString("hex");
  const key = scryptSync(password, salt, KEY_LENGTH, SCRYPT_PARAMS);
  return `${salt}:${key.toString("hex")}`;
}

export function verifyPassword(password: string, hash: string): boolean {
  const [salt, key] = hash.split(":");
  if (!salt || !key) return false;
  const derived = scryptSync(password, salt, KEY_LENGTH, SCRYPT_PARAMS);
  return timingSafeEqual(Buffer.from(key, "hex"), derived);
}
```

### Ste
Files: 1
Size: 39.1 KB
Complexity: 40/100
Category: Cloud & DevOps

Related in Cloud & DevOps