Skip to main content
Glama
SecureMCP Starter

SecureMCP Starter

by TheStawlker

SecureMCP Starter (Bun + TypeScript)

Ship a remote MCP server in under 30 minutes — with authentication, input validation, rate limiting and safe logging already in place.

Recent scans of public MCP servers keep finding the same thing: a large share of remote servers expose tools without any authentication. This starter is a small, readable, secure-by-default base so yours is not one of them.

Built on the official MCP TypeScript SDK v2 (@modelcontextprotocol/server, MCP spec 2026-07-28) and the Streamable HTTP transport, running natively on Bun.

What you get

🔐 Bearer-token auth

Authorization: Bearer … checked by the SDK's requireBearerAuth (OAuth 2.1 resource-server semantics, RFC 6750 WWW-Authenticate challenge, audience check). Tokens are stored hashed (SHA-256) and compared in constant time. Tokens in query strings are ignored.

✅ Input validation

Every tool input is a strict zod schema with size limits; unknown keys are rejected before your handler runs.

🚦 Rate limiting

Token bucket per client + coarse per-IP limit before auth (slows token brute force). 429 + Retry-After. Memory-bounded.

🧾 Safe logging

JSON logs; tokens, JWTs, API keys and sensitive fields are redacted; control characters stripped (no log injection).

🛡️ Hardening

Host/Origin allow-lists (DNS rebinding & CSRF), body-size limit, security headers, fail-closed config (refuses to start without tokens, refuses plain HTTP when exposed).

🧪 Tests

bun test: auth, validation, rate limits, Host/Origin, logging — run against a real HTTP server.

🧰 2 read-only example tools

server_time, search_docs — replace them with yours.

Related MCP server: mcp-starter-kit

Quick start

bun install
bun test                       # all green
bun run token:new my-laptop    # prints a token (once) + the hash line for MCP_TOKENS
cp .env.example .env           # paste the hash line into MCP_TOKENS=
bun start                      # http://127.0.0.1:3000/mcp

Check it from another terminal:

# Without a token -> 401 with a Bearer challenge
curl -i -X POST http://127.0.0.1:3000/mcp \
  -H 'Content-Type: application/json' -H 'Accept: application/json, text/event-stream' \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'

# With the token -> tools list
curl -s -X POST http://127.0.0.1:3000/mcp \
  -H "Authorization: Bearer $MCP_TOKEN" \
  -H 'Content-Type: application/json' -H 'Accept: application/json, text/event-stream' \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'

# Or the full client round-trip
MCP_TOKEN=smcp_... bun run smoke

Connect a client

Most MCP clients accept custom headers for remote servers, for example (mcp.json style):

{
  "mcpServers": {
    "my-secure-server": {
      "url": "https://mcp.example.com/mcp",
      "headers": { "Authorization": "Bearer ${env:MY_MCP_TOKEN}" }
    }
  }
}

Keep the token in an environment variable or your client's secret store, not in a committed file.

Add your own tool

Edit src/tools/index.ts:

server.registerTool(
  'get_invoice',
  {
    description: 'Read one invoice by id',
    inputSchema: z.object({ id: z.string().regex(/^inv_[a-z0-9]{8}$/) }).strict(),
    annotations: { readOnlyHint: true }
  },
  async ({ id }, ctx) => {
    const caller = ctx.http?.authInfo?.clientId; // who is calling
    // ... check that `caller` may read `id`, then return data
    return { content: [{ type: 'text', text: `invoice ${id}` }] };
  }
);

Rules of thumb: strict schemas with limits, read-only by default, check who is calling inside the handler for any per-record data, return generic error messages.

Configuration

All settings are environment variables, validated at startup — see .env.example. Important ones: MCP_TOKENS (hashes only), MCP_PUBLIC_URL (must be https:// once exposed), ALLOWED_HOSTS, ALLOWED_ORIGINS, RATE_LIMIT_*, TRUST_PROXY.

Project layout

src/
  index.ts            # Bun.serve entry point, graceful shutdown
  server.ts           # request pipeline: host/origin → IP limit → body size → auth → client limit → MCP
  config.ts           # zod-validated env, fail-closed checks
  security/auth.ts    # hashed static bearer tokens (OAuthTokenVerifier)
  security/rateLimit.ts
  security/logger.ts  # redacting JSON logger
  tools/index.ts      # your tools
scripts/new-token.ts  # token generator
scripts/smoke.ts      # end-to-end check against a running server
test/                 # bun test

Scaling notes

The server is stateless (one MCP server instance per request, as recommended by SDK v2), so it scales horizontally. The in-memory rate limiter is per instance: with several replicas, move limits to Redis/Valkey or your gateway.

Need more? → SecureMCP Starter Pro

The Pro edition adds what you need before going to production:

  • OAuth 2.1 with a real identity provider (JWT/JWKS verification, RFC 9728 protected-resource metadata, ready-made Keycloak / Auth0 / Microsoft Entra ID setups)

  • Per-tool permission scopes and allow-list policy (read-only by default)

  • Quotas on top of rate limits

  • JSONL audit log (who called what, when, result)

  • Prompt-injection guard for tool outputs (untrusted-content marking + sanitising)

  • Docker (non-root, read-only) + Debian hardening script

  • GitHub Actions CI

  • mcp-audit CLI to check any MCP server or client config

  • 20-point "before you ship an MCP server" checklist (MD + PDF) and a deployment guide

👉 Gumroad link coming soon.

Version française (résumé)

SecureMCP Starter est un modèle de serveur MCP distant en Bun + TypeScript, sécurisé par défaut : authentification par jeton Bearer (jetons stockés hachés, comparaison en temps constant), validation des entrées avec zod, limitation de débit par client et par IP, journaux JSON sans secrets, protections Host/Origin, limite de taille des requêtes, et tests bun test.

Démarrage : bun install, bun test, bun run token:new mon-poste, copier .env.example en .env, coller la ligne de hachage dans MCP_TOKENS, puis bun start. Le serveur écoute sur http://127.0.0.1:3000/mcp. En production, l'URL publique doit être en https://.

La version Pro ajoute OAuth 2.1 avec un vrai fournisseur d'identité, des permissions par outil, des quotas, un journal d'audit, une protection contre l'injection de prompt, Docker, un script de durcissement Debian, la CI GitHub Actions, l'outil mcp-audit et une checklist de 20 points.

License

MIT — see LICENSE. Not affiliated with Anthropic or the Model Context Protocol project.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    Related MCP Connectors

    Related MCP Servers

    • F
      license
      Not graded
      quality
      D
      maintenance
      An MCP server that executes TypeScript/JavaScript code in a sandboxed Bun environment with permission-based security controls, code snippets, and a web management UI.
      -
    • A
      license
      A
      quality
      D
      maintenance
      A production-ready foundation for building secure, observable MCP servers with built-in authentication, rate limiting, and reference tools like database-query and semantic-search.
      15
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      A lightweight HTTP-based MCP server built with Bun, enabling tool discovery and execution via JSON-RPC 2.0 over HTTP.
      MIT
    • A
      license
      A
      quality
      F
      maintenance
      A production-shaped starter for building MCP servers in TypeScript, featuring stdio and streamable HTTP transport, bearer auth, and example tools including ping and http_get_json with SSRF guards.
      2
      MIT