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 标准的使用门槛。