Home
Login

用於連接 Model Context Protocol (MCP) 伺服器的輕量級 React 鉤子庫

MITTypeScript 0.6kmodelcontextprotocoluse-mcp Last Updated: 2025-06-24

use-mcp 項目詳細介紹

項目概述

use-mcp 是一個輕量級的 React 鉤子庫,專門用於連接 Model Context Protocol (MCP) 伺服器。該項目簡化了 AI 系統中 MCP 標準的認證和工具調用過程,為開發者提供了一個易於使用的前端集成解決方案。

項目特性

🔄 自動連接管理

  • 支援自動重連和重試機制
  • 智能處理連接狀態和異常情況

🔐 OAuth 認證流程

  • 完整的 OAuth 認證流程處理
  • 支援彈窗和回退認證方式
  • 自動處理認證令牌儲存

📦 簡潔的 React Hook 介面

  • 提供直觀的 React Hook API
  • 狀態管理自動化
  • 易於集成到現有 React 應用

🧰 TypeScript 支援

  • 完整的 TypeScript 類型定義
  • 編輯器智能提示和類型檢查
  • 提高開發效率和代碼品質

📝 全面的日誌記錄

  • 詳細的除錯日誌功能
  • 便於問題排查和開發除錯

🌐 多傳輸協定支援

  • 支援 HTTP 傳輸
  • 支援 SSE (Server-Sent Events) 傳輸

安裝方式

npm install use-mcp
# 或者
pnpm add use-mcp
# 或者
yarn add use-mcp

基本使用方法

主要 Hook 使用

import { useMcp } from 'use-mcp/react'

function MyAIComponent() {
  const {
    state,        // 連接狀態: 'discovering' | 'authenticating' | 'connecting' | 'loading' | 'ready' | 'failed'
    tools,        // MCP 伺服器提供的可用工具
    error,        // 連接失敗時的錯誤訊息
    callTool,     // 調用 MCP 伺服器工具的函數
    retry,        // 手動重試連接
    authenticate, // 手動觸發認證
    clearStorage, // 清除儲存的令牌和憑據
  } = useMcp({
    url: 'https://your-mcp-server.com',
    clientName: 'My App',
    autoReconnect: true,
  })

  // 處理不同的連接狀態
  if (state === 'failed') {
    return (
      <div>
        <p>連接失敗: {error}</p>
        <button onClick={retry}>重試</button>
        <button onClick={authenticate}>手動認證</button>
      </div>
    )
  }

  if (state !== 'ready') {
    return <div>正在連接到 AI 服務...</div>
  }

  // 使用可用的工具
  const handleSearch = async () => {
    try {
      const result = await callTool('search', { query: 'example search' })
      console.log('搜索結果:', result)
    } catch (err) {
      console.error('工具調用失敗:', err)
    }
  }

  return (
    <div>
      <h2>可用工具數量: {tools.length}</h2>
      <ul>
        {tools.map(tool => (
          <li key={tool.name}>{tool.name}</li>
        ))}
      </ul>
      <button onClick={handleSearch}>搜索</button>
    </div>
  )
}

OAuth 認證回調設定

為了處理 OAuth 認證流程,需要在應用中設定回調端點。

React Router 配置

// App.tsx with React Router
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom'
import { useEffect } from 'react'
import { onMcpAuthorization } from 'use-mcp'

function OAuthCallback() {
  useEffect(() => {
    onMcpAuthorization()
  }, [])

  return (
    <div>
      <h1>正在認證...</h1>
      <p>此視窗應該會自動關閉。</p>
    </div>
  )
}

function App() {
  return (
    <Router>
      <Routes>
        <Route path="/oauth/callback" element={<OAuthCallback />} />
        <Route path="/" element={<YourMainComponent />} />
      </Routes>
    </Router>
  )
}

Next.js 配置

// pages/oauth/callback.tsx
import { useEffect } from 'react'
import { onMcpAuthorization } from 'use-mcp'

export default function OAuthCallbackPage() {
  useEffect(() => {
    onMcpAuthorization()
  }, [])

  return (
    <div>
      <h1>正在認證...</h1>
      <p>此視窗應該會自動關閉。</p>
    </div>
  )
}

API 參考

useMcp Hook

function useMcp(options: UseMcpOptions): UseMcpResult

配置選項 (UseMcpOptions)

選項 類型 描述
url string 必需。MCP 伺服器的 URL
clientName string OAuth 註冊時的客戶端名稱
clientUri string OAuth 註冊時的客戶端 URI
callbackUrl string OAuth 重定向的自定義回調 URL(默認為當前域名的 /oauth/callback
storageKeyPrefix string localStorage 中 OAuth 數據的儲存鍵前綴(默認為 "mcp:auth"
clientConfig object MCP 客戶端身份的自定義配置
debug boolean 是否啟用詳細的除錯日誌
autoRetry boolean | number 初始連接失敗時的自動重試,可設定延遲毫秒數
autoReconnect boolean | number 已建立連接丟失時的自動重連,可設定延遲毫秒數(默認:3000)

返回值 (UseMcpResult)

屬性 類型 描述
state string 當前連接狀態:'discovering', 'authenticating', 'connecting', 'loading', 'ready', 'failed'
tools Tool[] MCP 伺服器提供的可用工具
error string | undefined 連接失敗時的錯誤訊息
authUrl string | undefined 彈窗被阻止時的手動認證 URL
log LogEntry[] 日誌訊息陣列
callTool (name: string, args?: Record<string, unknown>) => Promise<any> 調用 MCP 伺服器工具的函數
retry () => void 手動嘗試重新連接
disconnect () => void 斷開與 MCP 伺服器的連接
authenticate () => void 手動觸發認證
clearStorage () => void 清除所有儲存的認證數據

實際應用示例

線上演示

總結

use-mcp 為 React 開發者提供了一個強大而簡潔的解決方案,用於集成 Model Context Protocol 伺服器。通過其直觀的 Hook 介面、完善的認證流程處理和強大的連接管理功能,開發者可以輕鬆地在 React 應用中實現 AI 工具集成,大大降低了 MCP 標準的使用門檻。

Star History Chart