Logto で MCP 対応アプリに認証 (Authentication) を有効化
このガイドでは、 mcp-auth を使用して MCP サーバーと Logto を統合し、標準の OpenID Connect フローを利用してユーザーを認証 (Authentication) し、アイデンティティ情報を安全に取得する方法を説明します。
このガイドで学べること:
- MCP サーバーの認可 (Authorization) サーバーとして Logto を設定する方法
- MCP サーバーに「whoami」ツールをセットアップし、現在のユーザーのクレーム (Claims) を返す方法
- MCP Inspector(MCP クライアント)でフローをテストする方法
このチュートリアル完了後、MCP サーバーは次のことが可能になります:
- Logto テナントでユーザーを認証 (Authentication)
- 「whoami」ツールの呼び出し時に、
sub
、username
、name
、email
などのアイデンティティクレーム (Claims) を返す
統合が完了したら、MCP Inspector の代わりに独自の MCP クライアント(Web アプリなど)を利用して、MCP サーバーが公開するツールやリソースにアクセスできます。
前提条件
- Logto Cloud (またはセルフホスト型)テナント
- Node.js または Python 環境
アーキテクチャの理解
- MCP サーバー:MCP クライアントにツールやリソースを提供するサーバー。
- MCP クライアント:認証 (Authentication) フローを開始し、統合をテストするために使用されるクライアント。このガイドでは MCP Inspector をクライアントとして使用します。
- Logto:OpenID Connect プロバイダー(認可 (Authorization) サーバー)として機能し、ユーザーアイデンティティを管理します。
規範的でないシーケンス図でプロセス全体の流れを示します:
MCP は急速に進化しているため、上記の図は最新の状態ではない場合があります。最新情報は mcp-auth ドキュメントを参照してください。
Logto でアプリをセットアップ
- Logto コンソールにサインインします。
- アプリケーション → アプリケーションの作成 → フレームワークなしでアプリを作成 を選択します。
- タイプを「シングルページアプリ」に設定します。
- アプリ名やその他の必須項目を入力し、アプリケーションの作成 をクリックします。
- App ID と Issuer エンドポイント を保存してコピーします。
MCP サーバーのセットアップ
プロジェクトの作成と依存関係のインストール
- Python
- Node.js
mkdir mcp-server
cd mcp-server
uv init # または独自のプロジェクト構成を使用
uv add "mcp[cli]" starlette uvicorn mcpauth # または任意のパッケージマネージャーを使用
mkdir mcp-server
cd mcp-server
npm init -y
npm install @modelcontextprotocol/sdk express mcp-auth # または任意のパッケージマネージャーを使用
Logto で MCP 認証 (Authentication) を構成する
先ほどコピーした発行者 (Issuer) エンドポイント <your-logto-issuer-endpoint>
を忘れずに置き換えてください。
- Python
- Node.js
whoami.py
内:
from mcpauth import MCPAuth
from mcpauth.config import AuthServerType
from mcpauth.utils import fetch_server_config
auth_issuer = '<your-logto-issuer-endpoint>'
auth_server_config = fetch_server_config(auth_issuer, type=AuthServerType.OIDC)
mcp_auth = MCPAuth(server=auth_server_config)
whoami.js
内:
import { MCPAuth, fetchServerConfig } from 'mcp-auth';
const authIssuer = '<your-logto-issuer-endpoint>';
const mcpAuth = new MCPAuth({
server: await fetchServerConfig(authIssuer, { type: 'oidc' }),
});
トークン検証の実装
アクセス トークン (Access token) を検証しユーザー情報を取得するため、次のようにアクセス トークン (Access token) 検証を実装します:
- Python
- Node.js
import requests
from mcpauth.types import AuthInfo
def verify_access_token(token: str) -> AuthInfo:
endpoint = auth_server_config.metadata.userinfo_endpoint
response = requests.get(
endpoint,
headers={"Authorization": f"Bearer {token}"},
)
response.raise_for_status()
data = response.json()
return AuthInfo(
token=token,
subject=data.get("sub"),
issuer=auth_server_config.metadata.issuer,
claims=data,
)
const verifyToken = async (token) => {
const { userinfoEndpoint, issuer } = mcpAuth.config.server.metadata;
const response = await fetch(userinfoEndpoint, {
headers: { Authorization: `Bearer ${token}` },
});
if (!response.ok) throw new Error('Token verification failed');
const userInfo = await response.json();
return {
token,
issuer,
subject: userInfo.sub,
claims: userInfo,
};
};
"whoami" ツールの実装
次に、クライアントから送信されたアクセス トークン (Access token) を使用して userinfo エンドポイントにリクエストし、現在のユーザーのアイデンティティ クレーム (Claims) を返す "whoami" ツールを実装します。
現時点の SDK バージョンでは Streamable HTTP トランスポートの公式サポートがないため、例として SSE トランスポートを使用しています。理論的には、HTTP 互換の任意のトランスポートを利用できます。
- Python
- Node.js
from mcp.server.fastmcp import FastMCP
from starlette.applications import Starlette
from starlette.routing import Mount
from starlette.middleware import Middleware
mcp = FastMCP("WhoAmI")
@mcp.tool()
def whoami() -> dict:
"""
現在のユーザーのアイデンティティ情報を返します。
"""
return (
mcp_auth.auth_info.claims
if mcp_auth.auth_info
else {"error": "Not authenticated"}
)
bearer_auth = Middleware(mcp_auth.bearer_auth_middleware(verify_access_token))
app = Starlette(
routes=[
mcp_auth.metadata_route(), # 発見用の OIDC メタデータを提供
Mount('/', app=mcp.sse_app(), middleware=[bearer_auth]),
],
)
サーバーの起動:
uvicorn whoami:app --host 0.0.0.0 --port 3001
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import express from 'express';
// MCP サーバーを作成し、whoami ツールを登録
const server = new McpServer({ name: 'WhoAmI', version: '0.0.0' });
server.tool('whoami', ({ authInfo }) => ({
content: [
{ type: 'text', text: JSON.stringify(authInfo?.claims ?? { error: 'Not authenticated' }) },
],
}));
// Express アプリ & MCP Auth ミドルウェア
const app = express();
app.use(mcpAuth.delegatedRouter());
app.use(mcpAuth.bearerAuth(verifyToken));
// SSE トランスポート(SDK ドキュメント通り)
const transports = {};
app.get('/sse', async (_req, res) => {
const transport = new SSEServerTransport('/messages', res);
transports[transport.sessionId] = transport;
res.on('close', () => delete transports[transport.sessionId]);
await server.connect(transport);
});
app.post('/messages', async (req, res) => {
const sessionId = String(req.query.sessionId);
const transport = transports[sessionId];
if (transport) await transport.handlePostMessage(req, res, req.body);
else res.status(400).send('No transport found for sessionId');
});
app.listen(3001);
サーバーの起動:
node whoami.js
統合をテストする
-
MCP サーバーを起動します。
-
MCP Inspector を起動します。
現在の MCP Inspector 実装の制限により、mcp-auth のフォーク版を使用する必要があります:
git clone https://github.com/mcp-auth/inspector.git
cd inspector
npm install
npm run devその後、ターミナルに表示された URL を開きます。
-
MCP Inspector で次のように設定します:
- Transport Type:
SSE
- URL:
http://localhost:3001/sse
- OAuth Client ID: Logto の App ID を貼り付け
- Auth Params:
{"scope": "openid profile email"}
- Redirect URI: この URL は自動で入力されます。コピーしてください。
- Transport Type:
-
Logto コンソールで先ほど作成したアプリケーションを見つけ、詳細ページを開き、設定 / リダイレクト URI セクションにリダイレクト URI を貼り付けて保存します。
-
MCP Inspector に戻り、Connect をクリックします。Logto のサインイン体験にリダイレクトされます。
サインインが完了すると、MCP Inspector にリダイレクトされます。Tools → List Tools → whoami → Run Tool に進みます。
次のようなユーザークレーム (Claims) が表示されます:
{
"sub": "user_XXXX",
"username": "alice",
"name": "Alice Smith",
"email": "[email protected]"
}
- Python
- Node.js
完全な MCP サーバーコードは mcp-auth/python リポジトリで確認できます。
完全な MCP サーバーコードは mcp-auth/js リポジトリで確認できます。