use-mcp 是一個輕量級的 React 鉤子庫,專門用於連接 Model Context Protocol (MCP) 伺服器。該項目簡化了 AI 系統中 MCP 標準的認證和工具調用過程,為開發者提供了一個易於使用的前端集成解決方案。
npm install use-mcp
# 或者
pnpm add use-mcp
# 或者
yarn add use-mcp
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 認證流程,需要在應用中設定回調端點。
// 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>
)
}
// 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>
)
}
function useMcp(options: UseMcpOptions): UseMcpResult
選項 | 類型 | 描述 |
---|---|---|
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) |
屬性 | 類型 | 描述 |
---|---|---|
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 標準的使用門檻。