MCP サーバーで Bearer 認証を設定する
MCP Auth では、MCP サーバーで Bearer 認可 (Authorization) を設定するためのさまざまな方法を提供しています:
- JWT (JSON Web Token) モード:クレーム (Claims) アサーションで JWT を検証する組み込みの認可 (Authorization) 方法。
- カスタムモード:独自の認可 (Authorization) ロジックを実装できます。
JWT モードで Bearer 認証を設定する
OAuth / OIDC プロバイダーが認可 (Authorization) 用に JWT を発行する場合、MCP Auth の組み込み JWT モードを利用できます。JWT の署名、有効期限、および指定した他のクレーム (Claims) を検証し、その後、認証 (Authentication) 情報をリクエストコンテキストに格納して MCP 実装で利用できるようにします。
スコープ (Scope) 検証
基本的なスコープ (Scope) 検証の例は以下の通りです:
- Python
- Node.js
from mcpauth import MCPAuth
from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.routing import Mount
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("MyMCPServer")
mcp_auth = MCPAuth(
# Initialize with your auth server config
)
bearer_auth = mcp_auth.bearer_auth_middleware("jwt", required_scopes=["read", "write"])
app = Starlette(
routes=[Mount('/', app=mcp.sse_app(), middleware=[Middleware(bearer_auth)])]
)
import express from 'express';
import { MCPAuth } from 'mcp-auth';
const app = express();
const mcpAuth = new MCPAuth({
/* ... */
});
const bearerAuth = mcpAuth.bearerAuth('jwt', { requiredScopes: ['read', 'write'] });
app.use('/mcp', bearerAuth, (req, res) => {
// Now `req.auth` contains the auth info
console.log(req.auth);
});
上記の例では、JWT に read
および write
スコープ (Scope) が必要であることを指定しています。JWT にこれらのスコープ (Scope) の いずれか が含まれていない場合、リクエストは 403 Forbidden エラーで拒否されます。
リソースインジケーター (Resource indicator) 検証 (RFC 8707)
プロバイダーが OIDC ベース、または Resource Indicator 拡張をサポートしている場合、audience
オプションを指定して JWT の aud
(オーディエンス (Audience))クレーム (Claim) を検証できます。これは、JWT が MCP サーバー向けであることを保証するのに役立ちます。
プロバイダーのドキュメントを確認し、Resource Indicator 拡張をサポートしているか、またその設定方法を確認してください。一部のプロバイダーでは「audience」「API リソース」「API indicator」など、同じ概念を指す他の用語を使用する場合があります。
リソースインジケーター (Resource indicator) を設定したら、bearerAuth
ミドルウェアで指定できます:
- Python
- Node.js
bearer_auth = mcp_auth.bearer_auth_middleware(
"jwt",
audience="https://api.example.com/mcp", # JWT の期待されるオーディエンス (Audience)
required_scopes=["read", "write"]
)
const bearerAuth = mcpAuth.bearerAuth('jwt', {
audience: 'https://api.example.com/mcp', // JWT の期待されるオーディエンス (Audience)
requiredScopes: ['read', 'write'],
});
上記の例では、MCP Auth は JWT の aud
クレーム (Claim) と必要なスコープ (Scope) の 両方 を検証します。
JWT 検証へのカスタムオプションの指定
基盤となる JWT 検証ライブラリにカスタムオプションを指定することもできます:
- Python
- Node.js
Python SDK では、JWT 検証に PyJWT を使用しています。次のオプションが利用できます:
leeway
: JWT の有効期限検証時に許容する猶予時間(秒単位)。デフォルトは 60 秒です。
bearer_auth = mcp_auth.bearer_auth_middleware(
"jwt",
audience="https://api.example.com/mcp",
required_scopes=["read", "write"]
leeway=10, # 10 秒の猶予で時計のずれを許容
)
Node.js SDK では、JWT 検証に jose ライブラリを使用しています。次のオプションが利用できます:
jwtVerify
: JWT 検証プロセスのオプション(jose
のjwtVerify
関数)。remoteJwtSet
: リモート JWT セット取得のオプション(jose
のcreateRemoteJWKSet
関数)。
const bearerAuth = mcpAuth.bearerAuth('jwt', {
audience: 'https://api.example.com/mcp',
requiredScopes: ['read', 'write'],
jwtVerify: {
clockTolerance: 60, // 60 秒の時計のずれを許容
},
remoteJwtSet: {
timeoutDuration: 10 * 1000, // リモート JWT セット取得のタイムアウト 10 秒
},
});
カスタム検証による Bearer 認証の設定
OAuth / OIDC プロバイダーが JWT を発行しない場合や、独自の認可 (Authorization) ロジックを実装したい場合、MCP Auth ではカスタム検証関数を作成できます:
Bearer 認証ミドルウェアは、発行者 (iss
)、オーディエンス (aud
)、必要なスコープ (scope
) を検証結果と照合するため、これらのチェックをカスタム検証関数で実装する必要はありません。トークンの有効性(例:署名、有効期限など)の検証と認証 (Authentication) 情報オブジェクトの返却に集中できます。
- Python
- Node.js
from mcpauth.exceptions import MCPAuthJwtVerificationException, MCPAuthJwtVerificationExceptionCode
from mcpauth.types import AuthInfo
async def custom_verification(token: str) -> AuthInfo:
# ここでカスタム検証ロジックを実装
info = await verify_token(token)
if not info:
raise MCPAuthJwtVerificationException(
MCPAuthJwtVerificationExceptionCode.JWT_VERIFICATION_FAILED
)
return info # 認証 (Authentication) 情報オブジェクトを返却
bearer_auth = mcp_auth.bearer_auth_middleware(
custom_verification,
required_scopes=["read", "write"]
)
const bearerAuth = mcpAuth.bearerAuth(
async (token) => {
// ここでカスタム検証ロジックを実装
const info = await verifyToken(token);
if (!info) {
throw new MCPAuthJwtVerificationError('jwt_verification_failed');
}
return info; // 認証 (Authentication) 情報オブジェクトを返却
},
{ requiredScopes: ['read', 'write'] }
);
MCP サーバーで Bearer 認証を適用する
MCP サーバーを Bearer 認証で保護するには、MCP サーバーインスタンスに Bearer 認証ミドルウェアを適用する必要があります。
- Python
- Node.js
bearer_auth = mcp_auth.bearer_auth_middleware("jwt", required_scopes=["read", "write"])
app = Starlette(
routes=[Mount('/', app=mcp.sse_app(), middleware=[Middleware(bearer_auth)])]
)
const app = express();
app.use(mcpAuth.bearerAuth('jwt', { requiredScopes: ['read', 'write'] }));
これにより、すべての受信リクエストが設定された Bearer 認証に従って認証 (Authentication) および認可 (Authorization) され、認証 (Authentication) 情報がリクエストコンテキストで利用できるようになります。
その後、MCP サーバー実装内で情報にアクセスできます:
- Python
- Node.js
@mcp.tool()
async def whoami() -> dict:
# `mcp_auth.auth_info` は現在のリクエストのコンテキストオブジェクト
auth_info = mcp_auth.auth_info
print(f"Authenticated user: {auth_info.subject}")
return {"subject": auth_info.subject}
// `authInfo` は `req.auth` オブジェクトから渡されます
server.tool('whoami', ({ authInfo }) => {
console.log(`Authenticated user: ${authInfo.subject}`);
return { subject: authInfo.subject };
});