メインコンテンツにスキップ

MCP サーバーでの MCP Auth の設定

MCP サーバーを OAuth 2.1 または OpenID Connect プロバイダーに接続するには、MCP Auth インスタンスの設定が必要です。これには、プロバイダーの認可サーバーメタデータでインスタンスを初期化し、必要な認可フローをセットアップする作業が含まれます。

MCP Auth の初期化

メタデータの自動取得

MCP Auth インスタンスを初期化する最も簡単な方法は、well-known URL からメタデータを取得する組み込み関数を利用することです。プロバイダーが次のいずれかの標準に準拠している場合:

fetchServerConfig を使い、issuer の URL を指定することでメタデータを自動取得できます:

from mcpauth import MCPAuth
from mcpauth.config import AuthServerType, fetch_server_config

mcp_auth = MCPAuth(
    server=fetch_server_config(
        '<auth-server-url>',
        type=AuthServerType.OIDC  # または AuthServerType.OAUTH
    )
)

issuer にパスが含まれている場合、OAuth 2.0 と OpenID Connect で挙動が少し異なります:

  • OAuth 2.0:well-known URL は issuer の ドメイン に追加されます。例:issuer が https://my-project.logto.app/oauth の場合、well-known URL は https://auth.logto.io/.well-known/oauth-authorization-server/oauth となります。
  • OpenID Connect:well-known URL は issuer に直接追加されます。例:issuer が https://my-project.logto.app/oidc の場合、well-known URL は https://auth.logto.io/oidc/.well-known/openid-configuration となります。

その他の MCP Auth 初期化方法

カスタムデータ変換

場合によっては、プロバイダーから返されるメタデータが期待される形式に準拠していないことがあります。プロバイダーが準拠していると確信できる場合は、transpile_data オプションを使ってメタデータを使用前に修正できます:

from mcpauth import MCPAuth
from mcpauth.config import AuthServerType
from mcpauth.utils import fetch_server_config

mcp_auth = MCPAuth(
    server=fetch_server_config(
        '<auth-server-url>',
        type=AuthServerType.OIDC,
        transpile_data=lambda data: {**data, 'response_types_supported': ['code']} 
    )
)

これにより、MCP Auth で使用する前にメタデータオブジェクトを修正できます。たとえば、フィールドの追加や削除、値の変更、別の形式への変換などが可能です。

特定の URL からメタデータを取得

プロバイダーが標準以外の特定のメタデータ URL を持っている場合も、同様に利用できます:

from mcpauth import MCPAuth
from mcpauth.config import AuthServerType
from mcpauth.utils import fetch_server_config_by_well_known_url

mcp_auth = MCPAuth(
    server=fetch_server_config_by_well_known_url(
        '<metadata-url>',
        type=AuthServerType.OIDC # または AuthServerType.OAUTH
    )
)

特定の URL からカスタムデータ変換付きでメタデータを取得

場合によっては、プロバイダーのレスポンスが不正または期待されるメタデータ形式に準拠していないことがあります。プロバイダーが準拠していると確信できる場合は、設定オプションでメタデータを変換できます:

from mcpauth import MCPAuth
from mcpauth.config import AuthServerType, fetch_server_config_by_well_known_url

mcp_auth = MCPAuth(
    server=fetch_server_config_by_well_known_url(
        '<metadata-url>',
        type=AuthServerType.OIDC,
        transpile_data=lambda data: {**data, 'response_types_supported': ['code']} 
    )
)

メタデータを手動で指定

プロバイダーがメタデータの取得をサポートしていない場合は、メタデータオブジェクトを手動で指定できます:

from mcpauth import MCPAuth
from mcpauth.config import AuthServerConfig, AuthServerType, AuthorizationServerMetadata

mcp_auth = MCPAuth(
    server=AuthServerConfig(
        type=AuthServerType.OIDC,  # または AuthServerType.OAUTH
        metadata=AuthorizationServerMetadata(
            issuer='<issuer-url>',
            authorization_endpoint='<authorization-endpoint-url>',
            # ... 他のメタデータフィールド
        ),
    )
)