
dzhng/mcp-client-auth
Developer toolsЭта страница переведена автоматически. Технические детали смотрите в оригинале. Открыть оригинал
Библиотека TypeScript, предоставляющая утилиты аутентификации OAuth2 для клиентов Model Context Protocol (MCP).
Обзор
Библиотека TypeScript, предоставляющая утилиты аутентификации OAuth2 для клиентов Model Context Protocol (MCP). Эта библиотека упрощает процесс добавления аутентификации OAuth к реализациям клиентов MCP. MCP OAuth является более сложным, потому что динамические этапы регистрации клиентов и обнаружения метаданных не поддерживаются типичными реализациями oauth. Эта библиотека упрощает все до 2 функциональных вызовов. Если вам нравится этот проект, пожалуйста, подумайте о том, чтобы снять его в главной роли и дать мне подписку на X / Twitter. Проект спонсируется компанией Aomni.
Обзор (машинный перевод)
Библиотека TypeScript, предоставляющая утилиты аутентификации OAuth2 для клиентов Model Context Protocol (MCP). Эта библиотека упрощает процесс добавления аутентификации OAuth к реализациям клиентов MCP.
MCP OAuth является более сложным, потому что динамические этапы регистрации клиентов и обнаружения метаданных не поддерживаются типичными реализациями oauth. Эта библиотека упрощает все до 2 функциональных вызовов.
Если вам нравится этот проект, пожалуйста, подумайте о том, чтобы снять его в главной роли и дать мне подписку на X / Twitter. Проект спонсируется компанией Aomni.
Особенности
Ключевые возможности:
Полный поток OAuth2 : Реализует стандартный поток кода авторизации OAuth2 с помощью PKCE ** Интеграция клиентов MCP: поддержка MCP-клиентов
- ** Нулевая конфигурация**: Автоматическое обнаружение метаданных сервера и динамическая регистрация клиентов Умный выбор транспорта: автоматический запасной вариант от StreamableHTTP до SSE для максимальной совместимости ** Управление токенами**: автоматическое обновление и безопасное хранение токенов (через подключаемый интерфейс хранения) TypeScript First: полная безопасность и поддержка IntelliSense
##Установка
Быстрый старт
Использование MCP-клиента высокого уровня
Эта страница переведена автоматически. Технические детали смотрите в оригинале.
README
Показан фрагмент оригинального README. Открыть оригинал.
MCP Client Auth
A TypeScript library providing OAuth2 authentication utilities for Model Context Protocol (MCP) clients. This library simplifies the process of adding OAuth authentication to MCP client implementations.
MCP OAuth is extra tricky because the dynamic client registration and metadata discovery steps are not supported by typical oauth implementations. This library simplifies everything to 2 function calls.
If you like this project, please consider starring it and giving me a follow on X/Twitter. This project is sponsored by Aomni.
Features
Key capabilities:
- 🔐 Complete OAuth2 Flow: Implements the standard OAuth2 authorization code flow with PKCE
- 🚀 MCP Client Integration: Drop-in OAuth support for MCP clients
- 📦 Zero Configuration: Automatic server metadata discovery and dynamic client registration
- 🌐 Smart Transport Selection: Automatic fallback from StreamableHTTP to SSE transport for maximum compatibility
- 🔄 Token Management: Automatic token refresh and secure storage (via pluggable storage interface)
- 🎯 TypeScript First: Full type safety and IntelliSense support
Installation
npm install mcp-client-auth
Quick Start
Using the High-Level MCP Client
Init the client
import { McpClient } from 'mcp-client-auth';
const client = new McpClient({
url: 'https://mcp.example.com',
oauthRedirectUri: 'localhost:3000/mcp/oauth/callback',
// store: -- add your own database store here --
});
There are only 2 methods that are needed to connect to a MCP server (and handle OAuth if needed).
Checking for auth status
The isAuthRequired() method returns an AuthStatus object that indicates the authentication state. This status can be one of three types:
-
{ isRequired: true, isAuthenticated: false, authorizationRequest: AuthorizationRequest }- Authentication is required and not yet completed. TheauthorizationRequestcontains the URL and state needed to start the OAuth flow. -
{ isRequired: false, isAuthenticated: true }- No authentication is needed for this server. -
{ isRequired: true, isAuthenticated: true }- Authentication is required and has already been completed successfully.
This status object helps you determine whether to redirect the user to the OAuth authorization page or proceed with using the client directly.
// Check if authentication is required
const authStatus = await client.isAuthRequired();
if (authStatus.isRequired && !authStatus.isAuthenticated) {
console.log('Please visit:', authStatus.authorizationRequest.url);
// ... REDIRECT USER ...
}
Note you should save the AuthorizationRequest object for the next step.
Handling the OAuth callback
The handleAuthByCode method is used to complete the OAuth flow by exchanging the authorization code for access tokens. It takes two parameters:
Установка
This server does not publish a one-line install command.
Open the repository installation guide Новичок в MCP? Начните с руководства на mcpskill.org →