{"id":50082490,"url":"https://github.com/ankitvirdi4/mcp-helmet","last_synced_at":"2026-05-22T16:03:40.141Z","repository":{"id":355727755,"uuid":"1229335276","full_name":"ankitvirdi4/mcp-helmet","owner":"ankitvirdi4","description":"Production middleware for MCP servers. Auth, sessions, health checks, graceful shutdown, transport ergonomics. Wraps the official Model Context Protocol SDK.","archived":false,"fork":false,"pushed_at":"2026-05-16T16:51:20.000Z","size":219,"stargazers_count":4,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-05-16T18:44:05.877Z","etag":null,"topics":["ai-agents","anthropic","claude","llm","mcp","middleware","model-context-protocol","server","tool-calling","typescript"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/mcp-helmet","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ankitvirdi4.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2026-05-05T00:05:47.000Z","updated_at":"2026-05-16T16:51:24.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/ankitvirdi4/mcp-helmet","commit_stats":null,"previous_names":["ankitvirdi4/mcp-helmet"],"tags_count":4,"template":false,"template_full_name":null,"purl":"pkg:github/ankitvirdi4/mcp-helmet","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ankitvirdi4%2Fmcp-helmet","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ankitvirdi4%2Fmcp-helmet/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ankitvirdi4%2Fmcp-helmet/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ankitvirdi4%2Fmcp-helmet/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ankitvirdi4","download_url":"https://codeload.github.com/ankitvirdi4/mcp-helmet/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ankitvirdi4%2Fmcp-helmet/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":33352420,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-21T12:23:38.849Z","status":"online","status_checked_at":"2026-05-22T02:00:06.671Z","response_time":265,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ai-agents","anthropic","claude","llm","mcp","middleware","model-context-protocol","server","tool-calling","typescript"],"created_at":"2026-05-22T16:03:36.157Z","updated_at":"2026-05-22T16:03:40.130Z","avatar_url":"https://github.com/ankitvirdi4.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# mcp-helmet\n\n[![npm](https://img.shields.io/npm/v/mcp-helmet.svg)](https://www.npmjs.com/package/mcp-helmet)\n[![CI](https://github.com/ankitvirdi4/mcp-helmet/actions/workflows/ci.yml/badge.svg)](https://github.com/ankitvirdi4/mcp-helmet/actions/workflows/ci.yml)\n[![License](https://img.shields.io/npm/l/mcp-helmet.svg)](./LICENSE)\n[![Types](https://img.shields.io/npm/types/mcp-helmet.svg)](https://www.npmjs.com/package/mcp-helmet)\n\n\u003e Production middleware for MCP servers. Auth, sessions, health checks, graceful shutdown, transport ergonomics. Composable middleware borrowed in spirit from Express's `helmet`.\n\n`mcp-helmet` wraps the official [@modelcontextprotocol/sdk](https://github.com/modelcontextprotocol/typescript-sdk) with the things it doesn't ship: auto transport detection, content wrapping, health checks, graceful shutdown, session management, and auth middleware. One package. Composable. Drop what you don't need. Go from hello world to production in minutes, not days.\n\n```bash\nnpm install mcp-helmet @modelcontextprotocol/sdk zod\n```\n\n\u003e **Alpha note.** Until `0.1.0` stable cuts, the `latest` dist-tag points at the most recent alpha (currently `0.1.0-alpha.7`). `npm install mcp-helmet` resolves there; pin a specific version if you prefer to opt out of alpha churn. Once the [ROADMAP](./ROADMAP.md) gates clear, `latest` moves to the stable release.\n\n\u003e **Peer dependencies:** `@modelcontextprotocol/sdk` ^1.29.0, `zod` ^3.22.0 or ^3.25 (v4). `zod-to-json-schema` is an optional peer for Zod v3 users.\n\n## Quickstart\n\nThe fastest way is the scaffolder:\n\n```bash\nnpx mcp-helmet init my-server --transport http --auth bearer\ncd my-server\nnpm install\nnpm run dev\n```\n\nYou get a working MCP server with `healthCheck()`, `gracefulShutdown()`, optional auth, a multistage `Dockerfile`, a typechecked `tsconfig`, a passing test, and a CI workflow. Drop flags to skip pieces (`--no-docker`, `--no-health`, `--no-rate-limit`, `--no-tests`, `--no-ci`) or customise after the fact.\n\nWant richer worked examples with auth, rate limiting, and audit logging? See [`examples/`](./examples).\n\nOr wire it manually:\n\n```typescript\nimport { createServer } from \"mcp-helmet\";\nimport { z } from \"zod\";\n\nconst server = createServer({ name: \"hello\", version: \"1.0.0\" });\n\nserver.tool(\"greet\", { name: z.string() }, async ({ name }) =\u003e {\n  return `Hello, ${name}!`;\n});\n\nawait server.start();\n```\n\nThat's it. No transport wiring, no content array construction, no signal handlers. Run it:\n\n```bash\n# Local development (stdio, the default)\nnpx tsx src/index.ts\n\n# Production (HTTP)\nMCP_TRANSPORT=http PORT=3000 node dist/index.js\n```\n\nSame code, both modes.\n\n## Auth in 6 lines\n\nBearer token verification, with the verified principal available inside any tool handler:\n\n```typescript\nimport { createServer, bearerAuth, getAuthContext } from \"mcp-helmet\";\n\nconst server = createServer({ name: \"secure\", version: \"1.0.0\" });\n\nserver.use(bearerAuth({\n  verify: async (token) =\u003e {\n    const claims = await verifyJwt(token); // your call\n    return { user: claims.sub, scopes: claims.scope?.split(\" \") ?? [] };\n  },\n}));\n\nserver.tool(\"whoami\", {}, async () =\u003e {\n  const auth = getAuthContext();\n  return { user: auth?.user, scopes: auth?.scopes };\n});\n\nawait server.start();\n```\n\nThe single-argument tool handler signature stays the same — `getAuthContext()` reads from AsyncLocalStorage, so it works from any depth in the async chain.\n\n## Why this exists\n\nWe audited 30 production MCP servers and 320 GitHub issues across the official SDKs. Three patterns kept showing up:\n\n1. **Every server rewrites the same 20-40 lines of setup.** Transport selection, content wrapping, error formatting, signal handling. The SDK gives you the building blocks; this gives you the house.\n\n2. **Servers that work locally break in production.** Docker containers exit after one response, Kubernetes pods lose sessions, no health check for load balancers to probe. 52% of remote MCP endpoints in a recent survey were dead.\n\n3. **Nobody can figure out auth.** \"How do I access the bearer token inside my tool?\" is the most asked question across both SDK repos.\n\n`mcp-helmet` solves these with composable middleware that extends the SDK without replacing it.\n\n## Status\n\n**v0.1.0-alpha — feature complete.** Currently shipped:\n\n- ✅ `createServer()` with auto content wrapping (string, object, Content[])\n- ✅ Auto transport detection via `MCP_TRANSPORT` env var\n- ✅ Zod v3 + v4 compatibility shim\n- ✅ Composable middleware system (`server.use(mw)`)\n- ✅ `healthCheck()` middleware\n- ✅ `gracefulShutdown()` middleware\n- ✅ `bearerAuth()` and `apiKeyAuth()` middleware with AsyncLocalStorage-based `getAuthContext()`\n- ✅ `rateLimiter()` middleware (sliding window, IP- or key-based, standard 429 headers)\n- ✅ `requestLog()` middleware (one JSON line per request, captures auth principal automatically)\n- ✅ `npx mcp-helmet init` CLI scaffolder + Docker template\n- ✅ `examples/` directory with three runnable scenarios\n\nv0.1.0 stable will follow once the alpha cycle has 30+ days of real-world usage and a small set of confirmed users. The full plan, including v0.2 scope, gates, forcing events, and a kill switch, lives in [ROADMAP.md](./ROADMAP.md).\n\n## Performance\n\nPer-request overhead is below the measurement noise floor. Numbers from\na single Node 20 run on Apple M1; expect 5-15% variance across runs.\n\n| Scenario | p50 (ms) | p95 (ms) | p99 (ms) | mean (ms) | req/s |\n|---|---|---|---|---|---|\n| bare | 0.16 | 0.21 | 0.41 | 0.18 | 5663 |\n| +requestLog | 0.15 | 0.18 | 0.28 | 0.16 | 6113 |\n| +bearerAuth | 0.16 | 0.20 | 0.31 | 0.17 | 5776 |\n| +rateLimiter | 0.16 | 0.21 | 0.36 | 0.18 | 5468 |\n| full stack | 0.16 | 0.21 | 0.33 | 0.17 | 5805 |\n\n`full stack / bare = 0.98x mean latency`, ie middleware cost is below\nwhat this benchmark can measure at the per-request scale. p99 stays\nsub-millisecond. Run `npm run bench` to reproduce on your hardware;\nthe script exits non-zero if a future change pushes the ratio above 5x.\n\nSee [`benchmarks/README.md`](./benchmarks/README.md) for tunables and\nmethodology.\n\n## Migrate from the raw SDK\n\nIf you already have an MCP server using `@modelcontextprotocol/sdk` directly, mcp-helmet drops in without rewriting your tools. Three concrete swaps:\n\n```typescript\n// Before\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\n\nconst server = new McpServer({ name: \"x\", version: \"1.0.0\" });\nserver.tool(\"greet\", { name: z.string() }, async ({ name }) =\u003e ({\n  content: [{ type: \"text\", text: `Hello, ${name}!` }],\n}));\nconst transport = new StdioServerTransport();\nawait server.connect(transport);\n\n// After\nimport { createServer } from \"mcp-helmet\";\n\nconst server = createServer({ name: \"x\", version: \"1.0.0\" });\nserver.tool(\"greet\", { name: z.string() }, async ({ name }) =\u003e `Hello, ${name}!`);\nawait server.start();\n```\n\nThe handler returns a string and gets auto wrapped into `TextContent`. The transport is selected from `MCP_TRANSPORT` (defaults to stdio). The underlying `McpServer` is still available as `server.raw` if you need it.\n\nAdding middleware afterwards is one line per concern:\n\n```typescript\nserver.use(healthCheck());\nserver.use(requestLog());\nserver.use(rateLimiter({ max: 100, windowMs: 60_000 }));\nserver.use(bearerAuth({ verify: myVerifier }));\nserver.use(gracefulShutdown());\n```\n\n## Troubleshooting\n\n**`getAuthContext()` returns undefined inside my tool handler.**\nThe auth middleware that populates the context (`bearerAuth` or `apiKeyAuth`) must be installed via `server.use(...)` before `server.start()`. The toolkit reads `getAuthContext()` from AsyncLocalStorage scoped to each HTTP request. If you call it from a stdio server (no HTTP request lifecycle), it always returns `undefined`.\n\n**Graceful shutdown does not fire.**\n`gracefulShutdown()` only listens for SIGTERM / SIGINT in the toolkit's HTTP path. In stdio mode the parent process owns the lifecycle (Claude Desktop, Inspector, your spawn parent), so the toolkit does not need to register signal handlers.\n\n**`tools/list` is empty.**\nCall `server.tool(...)` before `server.start()`. Tool registration is captured at start time; tools registered afterwards are not advertised.\n\n**The rate limiter never triggers.**\n`rateLimiter()` only runs in HTTP mode because stdio has no per-request HTTP lifecycle for the middleware to hook. Including it in a stdio server is a harmless no-op.\n\n**Zod v3 vs v4 imports look weird.**\nThe toolkit detects which Zod major you have and adapts at runtime. If you are on Zod 3.22+ on the v3 line, just `import { z } from \"zod\"`. If you are on Zod 4 and want the new APIs, use `import * as z from \"zod/v4\"`. The toolkit accepts schemas from either.\n\n**`StreamableHTTPClientTransport` returns 401.**\nYou have an auth middleware in the chain. Pass the right `Authorization` header in `requestInit.headers` when constructing the client transport. See [`examples/02-http-bearer-rate-limit.ts`](./examples/02-http-bearer-rate-limit.ts).\n\n**Testing a tool that calls `getAuthContext()`.**\n`InMemoryTransport` bypasses the HTTP request lifecycle, which is the layer that normally wraps each request with `runWithAuthContext`. So tools that read the auth principal via `getAuthContext()` return `undefined` under in-memory tests by default. Inject auth manually by wrapping the `callTool` invocation:\n\n```typescript\nimport { runWithAuthContext } from \"mcp-helmet\";\n\nconst result = await runWithAuthContext(\n  { user: \"test-user\", scopes: [\"read\", \"write\"] },\n  () =\u003e client.callTool({ name: \"whoami\", arguments: {} }),\n);\n```\n\nThis is the pattern used in [`mcp-helmet-fs-example`](https://github.com/ankitvirdi4/mcp-helmet-fs-example/blob/main/src/server.test.ts) to test scope-based authorization without going through HTTP.\n\n## How it relates to the official SDK\n\n`mcp-helmet` is **not** a fork, an alternative, or a replacement. It's a convenience layer.\n\n| Concern | Official SDK | mcp-helmet |\n|---|---|---|\n| Protocol implementation | Yes | No, delegates to SDK |\n| Transport classes | Yes | No, wraps SDK transports |\n| Tool/resource/prompt registration | Yes | Yes, thinner API |\n| OAuth server flows | Yes (in v2 dev) | No, out of scope |\n| Bearer/API-key middleware | Express-coupled in v2 | Transport-agnostic, composable |\n| Health checks | No | Yes, planned |\n| Session externalization | No | Stopgap until upstream SEP |\n| Docker/deployment templates | No | Yes, planned |\n\nThe SDK is a peer dependency. You bring your own version. If the SDK adds features that overlap, mcp-helmet middleware becomes a thin pass-through.\n\n## Requirements\n\n- Node.js 20+\n- `@modelcontextprotocol/sdk` ^1.29.0\n- TypeScript 5.4+ (recommended, not required)\n- Zod 3.22+ or 3.25+ (v4 via `zod/v4` subpath)\n\n## Contributing\n\nPRs and issues welcome. See [CONTRIBUTING.md](./CONTRIBUTING.md) for setup, test, and PR conventions.\n\n## Security\n\nSee [SECURITY.md](./SECURITY.md) for the responsible disclosure path.\n\n## License\n\nMIT\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fankitvirdi4%2Fmcp-helmet","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fankitvirdi4%2Fmcp-helmet","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fankitvirdi4%2Fmcp-helmet/lists"}