MCP Auth 36f1aa4e

MCP开发工具

提供方 prmichaelsen

开发工具 未标注 API Key 社区 / 第三方

为MCP服务器提供可插拔的认证系统,支持多租户、多种认证方式和传输协议。

一句话选型结论

按资料字段整理

MCP Auth 36f1aa4e 属于开发工具类 MCP 服务器,传输方式未标注,API Key,没有现成安装命令,需按官方文档接入。接入前先确认权限范围;涉及写入、删除或付款的操作,建议先在测试环境验证。

分类开发工具 传输方式未标注 鉴权API Key 部署方式未标注
GitHub 星标 0 仓库热度,无公开仓库时显示未标注
工具数 未标注 暴露给模型的工具数量
资源 / 提示词 0 / 0 资源与提示词模板数量
维护方 社区 / 第三方 核验等级 仅资料核对

工具与能力

开发工具
数量来自来源目录的标注,具体工具清单以官方文档为准
工具数量未标注暴露给模型可调用的工具个数
资源数量0可读取的资源条目
提示词数量0内置提示词模板数量

能力标签

适用场景

Shell本地部署认证系统多租户JWTAPI安全TypeScript

安装与配置

未标注 API Key
上游未给出传输方式
  1. 1
    准备运行环境

    按官方文档确认运行环境(常见为 Node.js 或 Python),装好后再执行安装命令。

  2. 2
    安装服务

    复制上面的安装命令执行;命令里带占位符的位置,换成自己的密钥或路径。

  3. 3
    写入客户端配置

    在客户端的 MCP 配置里填好启动命令和参数,保存后完全退出客户端再打开,让新配置生效。

  4. 4
    验证是否可用

    连接成功后随便调一个只读工具,确认能返回结果,再接入正式流程。

典型使用场景

3 类
按分类与标签整理的常见用法,具体以官方文档为准
代码与仓库操作

在对话里直接查代码、提 issue、走 PR,省掉来回切工具。

本地命令与脚本

把构建、测试、格式化这类重复命令交给模型执行。

接口联调与测试

让模型调你的接口、跑一遍用例,快速定位问题。

选择建议

选之前先看这几条
按条目字段给出的判断,不替你决定用不用

值得选的地方

  • 基础信息齐全,可以先按官方文档接入试跑。

先想清楚的地方

  • 没有现成安装命令,需要按官方文档自己填启动命令和参数。
  • 使用前要准备好API Key对应的凭据,并按最小权限配置。
  • 资料没标注工具数量,实际能力要装好后确认。
  • 版本更新与行为细节以官方仓库为准。

更适合

  • 需要在开发工具场景里让模型直接调用外部能力的人。
  • 想先快速试一下、能接受在本地或自有环境跑服务的人。

不太适合

  • 不方便管理密钥或第三方授权的人。
  • 需要厂商级 SLA 和技术支持的生产环境。

同类对比

6 个同类
同分类里挑最接近的几条,字段以各自详情页为准
MCP 服务器工具数传输方式部署方式安装命令最后核验
MCP Auth 36f1aa4e当前 未标注 未标注 未标注 无 2026-05-17
Git 838e2ec1 12 stdio · 本地进程 本地部署 有 2026-05-17
Markitdown MCP 2c653a5f 1 stdio · 本地进程 本地部署 有 2026-05-17
JavaGuide 未标注 stdio · 本地进程 本地部署 有 2026-04-11
awesome-claude-skills 未标注 stdio · 本地进程 本地部署 有 2026-04-26
Context7 831acf40 未标注 stdio · 本地进程 本地部署 有 2026-05-17

服务器档案

开发工具
字段来自项目仓库与公开索引,中文说明由本站标注
提供方prmichaelsen上游标注的维护方 prmichaelsen
分类开发工具本站按上游分类展示
连接方式未标注上游未给出传输方式
鉴权方式API Key远程服务建议用最小权限凭据
维护方社区 / 第三方核验等级 仅资料核对
包名 / 运行时未标注 · 未标注本地安装时用到的包标识与运行时
部署类型未标注上游给出的部署形态
最近核验2026-05-17上游最后核验时间

详细介绍

14.7 KB
来自项目仓库与上游目录的原文,未做删改

@prmichaelsen/mcp-auth

Authentication and multi-tenancy framework for MCP (Model Context Protocol) servers.

Overview

@prmichaelsen/mcp-auth provides a pluggable authentication system for MCP servers, enabling:

  • Zero modification: Wrap existing MCP servers without code changes
  • Multi-tenancy: Multiple users with separate resource tokens
  • Auth-agnostic: Support for JWT, environment variables, or custom auth schemes
  • Transport-agnostic: Works with stdio, HTTP, and SSE transports
  • Type-safe: Full TypeScript support
  • Composable: Middleware for rate limiting, logging, timeouts, retries

Two Patterns

Pattern 1: Server Wrapping (Recommended for Production)

Wrap existing MCP servers without modification:```typescript
import { wrapServer, JWTAuthProvider, APITokenResolver } from '@prmichaelsen/mcp-auth';
import { createServer } from '@myorg/my-mcp-server';

const wrapped = wrapServer({
serverFactory: createServer,

// Validates JWT from tenant manager
authProvider: new JWTAuthProvider({
jwtSecret: process.env.JWT_SECRET
}),

// Resolves tokens via tenant manager API (recommended)
tokenResolver: new APITokenResolver({
tenantManagerUrl: process.env.TENANT_MANAGER_URL,
serviceToken: process.env.SERVICE_TOKEN
}),

resourceType: 'myapi',
transport: { type: 'sse', port: 3000 }
});

await wrapped.start();


### Pattern 2: Tool-Level Auth

Build new servers with integrated authentication:```typescript
import { AuthenticatedMCPServer, withAuth, EnvAuthProvider, SimpleTokenResolver } from '@prmichaelsen/mcp-auth';

const server = new AuthenticatedMCPServer({
  name: 'my-server',
  authProvider: new EnvAuthProvider(),
  tokenResolver: new SimpleTokenResolver({ tokenEnvVar: 'API_TOKEN' }),
  resourceType: 'myapi',
  transport: { type: 'stdio' }
});

server.registerTool('get_data', withAuth(async (args, accessToken, userId) => {
  const client = new MyAPIClient(accessToken);
  return client.getData(args);
}));

await server.start();

Installation```bash

Core package

npm install @prmichaelsen/mcp-auth @modelcontextprotocol/sdk

For JWT support

npm install jsonwebtoken

For SSE/HTTP transports

npm install express cors


## Authentication Providers

### EnvAuthProvider (Single-User)

For local development and single-user scenarios:```typescript
import { EnvAuthProvider, SimpleTokenResolver } from '@prmichaelsen/mcp-auth';

const authProvider = new EnvAuthProvider({
  userIdEnvVar: 'MCP_USER_ID',
  defaultUserId: 'local-user'
});

const tokenResolver = new SimpleTokenResolver({
  tokenEnvVar: 'API_TOKEN'
});

JWTAuthProvider + APITokenResolver (Multi-Tenant Production) ⭐ RECOMMENDED

For production multi-tenant deployments:```typescript
import { JWTAuthProvider, APITokenResolver } from '@prmichaelsen/mcp-auth';

// Validates JWT tokens from tenant manager
const authProvider = new JWTAuthProvider({
jwtSecret: process.env.JWT_SECRET,
userIdClaim: 'sub'
});

// Resolves tokens via tenant manager API
const tokenResolver = new APITokenResolver({
tenantManagerUrl: 'https://tenant-manager.example.com',
serviceToken: process.env.SERVICE_TOKEN,
cacheTokens: true, // Cache for performance
cacheTtl: 300000 // 5 minutes
});


**Why API-Based is Better:**
- ✅ Automatic token refresh (no new JWT needed)
- ✅ Immediate token revocation
- ✅ Tokens not exposed in JWT
- ✅ Small JWT size (~200 bytes)
- ✅ Centralized token management

### JWTAuthProvider + JWTTokenResolver (MVP/Prototyping)

For quick setup with JWT-embedded tokens:```typescript
import { JWTAuthProvider, JWTTokenResolver } from '@prmichaelsen/mcp-auth';

const authProvider = new JWTAuthProvider({
  jwtSecret: process.env.JWT_SECRET,
  extractTokens: true // Extract tokens from JWT
});

const tokenResolver = new JWTTokenResolver({ authProvider });

Trade-offs:
- ✅ Zero API calls (faster)
- ✅ Simpler to implement
- ❌ Token rotation requires new JWT
- ❌ Larger JWT size
- ❌ Tokens exposed in JWT payload

JWTAuthProvider (Static Servers) ⭐ NEW

For servers that manage their own data and only need user identification:```typescript
import { wrapServer, JWTAuthProvider } from '@prmichaelsen/mcp-auth';

const wrapped = wrapServer({
serverFactory: (accessToken, userId) => {
// accessToken will be empty string - use userId only
return createMyStaticServer(userId);
},

authProvider: new JWTAuthProvider({
jwtSecret: process.env.JWT_SECRET
}),

// No tokenResolver needed! ✨

resourceType: 'my-service',
transport: {
type: 'sse',
port: 3000,
cors: true,
corsOrigin: process.env.CORS_ORIGIN
}
});


**Perfect for:**
- ✅ Multi-tenant SaaS with own database
- ✅ User-scoped services
- ✅ Internal tools without external APIs
- ✅ Static data management servers

**Benefits:**
- ✅ Simplest configuration
- ✅ No external credential management
- ✅ JWT validation only (userId extraction)
- ✅ Complete user isolation via ephemeral instances

### APITokenResolver (API-Based)

For resolving tokens via tenant manager API:```typescript
import { JWTAuthProvider, APITokenResolver } from '@prmichaelsen/mcp-auth';

const authProvider = new JWTAuthProvider({
  jwtSecret: process.env.JWT_SECRET
});

const tokenResolver = new APITokenResolver({
  tenantManagerUrl: 'https://tenant-manager.example.com',
  serviceToken: process.env.SERVICE_TOKEN,
  endpointPath: '/api/credentials/:userId/:resourceType'
});

Custom Provider

Implement your own authentication logic:```typescript
import { AuthProvider, AuthResult, RequestContext } from '@prmichaelsen/mcp-auth';

class CustomAuthProvider implements AuthProvider {
async authenticate(context: RequestContext): Promise<AuthResult> {
const apiKey = context.headers?.['x-api-key'];

if (!apiKey) {
  return { authenticated: false, error: &#x27;No API key&#x27; };
}

// Your validation logic
return {
  authenticated: true,
  userId: &#x27;user-123&#x27;
};

}
}


## Middleware Composition```typescript
import { compose, withAuth, withRateLimit, withLogging, withTimeout } from &#x27;@prmichaelsen/mcp-auth&#x27;;

const getTool = compose(
  withLogging({ logArgs: true }),
  withRateLimit({ maxRequests: 100, windowMs: 60000 }),
  withTimeout(5000),
  withAuth(),
  async (args, accessToken, userId) =&gt; {
    // Your tool logic
  }
);

server.registerTool(&#x27;get_data&#x27;, getTool);

Transports

Stdio (Local)```typescript

transport: { type: 'stdio' }


### SSE (Remote Multi-Tenant)```typescript
transport: {
  type: &#x27;sse&#x27;,
  port: 3000,
  host: &#x27;0.0.0.0&#x27;,
  basePath: &#x27;/mcp&#x27;,
  cors: true,
  corsOrigin: &#x27;https://your-app.example.com&#x27;  // REQUIRED when cors: true
}

Endpoints created:
- GET /mcp - Server info and available endpoints
- POST /mcp/message - MCP protocol messages (requires JWT)
- GET /mcp/health - Health check endpoint

⚠️ CORS Security

When enabling CORS, you MUST specify corsOrigin with explicit origins:```typescript
// ✅ SECURE - Single origin
transport: {
type: 'sse',
cors: true,
corsOrigin: 'https://app.example.com'
}

// ✅ SECURE - Multiple origins
transport: {
type: 'sse',
cors: true,
corsOrigin: ['https://app1.example.com', 'https://app2.example.com']
}

// ❌ INSECURE - Wildcard blocked in production
transport: {
type: 'sse',
cors: true,
corsOrigin: '*' // ConfigurationError in production!
}

// ❌ INSECURE - Missing corsOrigin
transport: {
type: 'sse',
cors: true // ConfigurationError: corsOrigin required!
}


**Security Requirements:**
- `corsOrigin` is **REQUIRED** when `cors: true`
- Wildcard (`*`) is **ONLY** allowed in development (`NODE_ENV !== &#x27;production&#x27;`)
- In production, wildcard throws `ConfigurationError` to prevent CSRF attacks
- Use specific origins to ensure only your applications can access the MCP server

### HTTP (Remote)```typescript
transport: {
  type: &#x27;http&#x27;,
  port: 3000,
  host: &#x27;0.0.0.0&#x27;
}

Progress Streaming

mcp-auth supports MCP progress notifications, allowing wrapped servers to stream progress updates to clients during long-running operations.

How It Works

When a client provides a progressToken in the request, mcp-auth automatically:
1. Extracts the progress token from the request
2. Passes it through to the wrapped MCP server
3. The wrapped server can send progress notifications back to the client
4. Progress is isolated per user (multi-tenant safe)

Client-Side Usage```typescript

import { Client } from '@modelcontextprotocol/sdk/client/index.js';

const client = new Client({
name: 'my-client',
version: '1.0.0'
});

// Call tool with progress support
const result = await client.request({
method: 'tools/call',
params: {
name: 'long_running_operation',
arguments: { / ... / }
}
}, {
progressToken: 'operation-123',
onprogress: (progress) => {
console.log(Progress: ${progress.progress}/${progress.total});
console.log(Message: ${progress.message});
}
});


### Server-Side Implementation

Wrapped MCP servers can send progress notifications:```typescript
// In your MCP server tool handler
export async function handleLongOperation(
  args: any,
  extra?: { progressToken?: string | number }
): Promise&lt;any&gt; {
  const progressToken = extra?.progressToken;

  if (progressToken) {
    // Send progress notifications
    server.notification({
      method: &#x27;notifications/progress&#x27;,
      params: {
        progressToken,
        progress: 50,
        total: 100,
        message: &#x27;Processing...&#x27;
      }
    });
  }

  // ... perform operation
}

Features

  • ✅ Automatic Pass-Through: Progress tokens automatically forwarded to wrapped servers
  • ✅ Multi-Tenant Safe: Progress notifications isolated per user
  • ✅ Backward Compatible: Works with or without progress token (graceful degradation)
  • ✅ Zero Configuration: No additional setup required

Monitoring

Monitor active progress streams via authenticated endpoints:

User Stats (shows your own progress streams):```bash
GET /mcp/progress/stats
Authorization: Bearer <jwt>


**Response**:```json
{
  &quot;user&quot;: {
    &quot;userId&quot;: &quot;user123&quot;,
    &quot;activeStreams&quot;: 2,
    &quot;totalMessages&quot;: 1543,
    &quot;totalBytes&quot;: 45231,
    &quot;oldestStreamAge&quot;: 120000
  },
  &quot;global&quot;: {
    &quot;activeStreams&quot;: 15,
    &quot;totalMessages&quot;: 8234,
    &quot;userCount&quot;: 8
  },
  &quot;timestamp&quot;: &quot;2026-02-23T21:00:00.000Z&quot;
}

All Metrics (detailed stream information):```bash
GET /mcp/progress/metrics
Authorization: Bearer <jwt>


**Response**:```json
{
  &quot;metrics&quot;: [
    {
      &quot;userId&quot;: &quot;user123&quot;,
      &quot;progressToken&quot;: &quot;op-456&quot;,
      &quot;startTime&quot;: 1708725600000,
      &quot;lastUpdate&quot;: 1708725650000,
      &quot;duration&quot;: 50000,
      &quot;messageCount&quot;: 125,
      &quot;bytesTransferred&quot;: 45231,
      &quot;averageMessageSize&quot;: 361.8,
      &quot;messagesPerSecond&quot;: 2.5
    }
  ],
  &quot;health&quot;: {
    &quot;healthy&quot;: true,
    &quot;issues&quot;: [],
    &quot;warnings&quot;: []
  },
  &quot;timestamp&quot;: &quot;2026-02-23T21:00:00.000Z&quot;
}

Performance

  • Memory: ~1KB per active stream
  • Network: ~100-500 bytes per progress notification
  • CPU: <1% overhead for typical workloads
  • Cleanup: Stale streams (>5 minutes idle) automatically removed every minute

Notes

  • Progress streaming requires SSE or HTTP transport (not available with stdio)
  • Progress tokens are automatically cleaned up after request completion
  • Wrapped servers must implement progress notification support to send updates
  • Health checks detect stale streams and high message rates
  • Monitoring endpoints require authentication

MCP Server Contract

To make your MCP server compatible with wrapServer(), export a factory function:```typescript
import { Server } from '@modelcontextprotocol/sdk/server/index.js';

export function createServer(accessToken: string, userId?: string): Server {
const server = new Server({ name: 'my-server', version: '1.0.0' });
const client = new MyAPIClient(accessToken);

// Register your tool handlers...

return server;
}
```

That's it! No mcp-auth imports needed in your server.

Architecture

Three-Tier Deployment

  1. Chat Platform - Sends MCP requests with JWT
  2. Tenant Manager - Issues JWTs, manages user credentials
  3. MCP Server Instance - Uses mcp-auth to wrap MCP servers

Token Resolution Approaches

Approach 1: JWT with Embedded Tokens (Recommended)
- Tenant manager includes resource tokens in JWT
- Zero external calls
- Fastest performance

Approach 2: API-Based Resolution
- Tenant manager provides API for token lookup
- Better separation of concerns
- Easier token rotation

See agent/token-resolution-approaches.md for details.

Documentation

Comprehensive architecture documentation in agent/:

  • server-wrapping-pattern.md - Server wrapping architecture
  • server-contract.md - MCP server compatibility guide
  • dual-pattern-architecture.md - Both patterns explained
  • token-resolution-approaches.md - Token resolution strategies
  • why-two-steps.md - AuthProvider vs TokenResolver
  • INTEGRATION.md - Integration guide for MCP server authors

Examples

Working examples coming soon in examples/:

  • simple-stdio/ - Single-user stdio server
  • wrapped-server/ - Server wrapping with JWT
  • tool-level-auth/ - Tool-level authentication
  • jwt-multi-tenant/ - Multi-tenant JWT deployment

API Reference

Core Functions

  • wrapServer(config) - Wrap MCP server with authentication
  • withAuth(handler) - Add auth to function-based tools
  • compose(...middlewares) - Compose middleware functions

Classes

  • AuthenticatedMCPServer - MCP server with integrated auth
  • AuthenticatedTool - Wrapper for class-based tools
  • BaseAuthProvider - Base class for auth providers

Providers

  • EnvAuthProvider - Environment variable authentication
  • SimpleTokenResolver - Environment variable token resolution
  • JWTAuthProvider - JWT validation with token extraction
  • JWTTokenResolver - JWT-embedded token resolution
  • APITokenResolver - API-based token resolution

Middleware

  • withAuth() - Authentication
  • withLogging() - Request/response logging
  • withRateLimit() - Rate limiting per user
  • withTimeout() - Request timeout
  • withRetry() - Automatic retry on failure

Example Projects

Real-world projects using @prmichaelsen/mcp-auth:

@prmichaelsen/agentbase-mcp-server

Multi-tenant Instagram MCP server with JWT authentication
- Pattern: Server Wrapping (Dynamic Mode)
- Auth: JWT + API-based token resolution
- Use Case: External API credentials (Instagram)
- Transport: SSE over HTTP

@prmichaelsen/remember-mcp-server

Multi-tenant MCP server for remember-mcp with Platform JWT authentication
- Pattern: Server Wrapping (Static Mode)
- Auth: JWT only (no tokenResolver)
- Use Case: User-scoped data in own database
- Transport: SSE over HTTP

License

MIT

Contributing

Contributions welcome! Please open an issue or PR on GitHub.

常见问题

5 问
答案由本站依据条目字段整理,不引用上游原文
MCP Auth 36f1aa4e 怎么安装?

资料没有给出安装命令,请到官方仓库或文档按说明接入;这类条目多数是生态应用,或尚未发布可安装包。

MCP Auth 36f1aa4e 怎么在客户端里配置?

它的传输方式未标注,在客户端 MCP 配置里按官方文档填写启动命令和参数,保存后重启客户端生效。

MCP Auth 36f1aa4e 收费吗?

本站不代收费用,也没有标注具体价格。是否收费取决于服务本身和背后的接口额度,正式使用前按官方说明确认。

MCP Auth 36f1aa4e 需要 API Key 吗?

资料标注需要API Key认证,使用前准备好对应凭据,并按最小权限配置。

MCP Auth 36f1aa4e 能提供哪些能力?

资料显示能力标签包括 多租户、Shell、TypeScript。具体工具清单以官方文档为准。

热门专题

按标签挑服务器
全部专题 →

服务器信息以作者仓库与官方文档为准;分类、传输方式与鉴权方式的中文说明为中文整理,最近核验 2026-05-17。