use-mcp 是一个 React 库,它大大简化了构建 MCP 客户端的所有复杂性。将 useMCP()
钩子添加到任何 React 应用程序中,即可连接到用户可以交互的远程 MCP 服务器。
仅需几行代码,你就能轻松连接各种远程 MCP 服务器:
import { useMcp } from 'use-mcp/react'
function MyComponent() {
const { state, tools, callTool } = useMcp({
url: 'https://mcp-server.example.com'
})
return <div>Your UI code</div>
}
use-mcp 负责处理传输协议(Streamable HTTP 和 Server-Sent Events)、身份验证流和会话管理。它还包含大量功能,可帮助您构建可靠、可扩展和可投入生产的 MCP 客户端。
use-mcp 的特点
- 🌐 支持 HTTP 和 SSE 传输协议
- 📝 调试友好,支持全面的日志
- 🧰 开发友好,内置编辑器辅助和类型检查的 TS 类型
- 🔄 具有重新连接和重试功能的自动连接管理
- 📦 提供简单的 React 钩子,轻松集成 MCP 服务器
- 🔐 支持 popup 和 fallback 的 OAuth 身份验证流处理
use-mcp 在线示例
通过 https://inspector.use-mcp.dev/ 地址,你可以快速体验 use-mcp 的功能:
图片
use-mcp 快速入门
1.安装 use-mcp
npm install use-mcp
# or
pnpm add use-mcp
# or
yarn add use-mcp
2.使用 useMcp Hook
function MyMcpComponent() {
const {
state,
tools,
error,
callTool,
retry,
authenticate,
clearStorage,
} = useMcp({
url: 'https://your-mcp-server.com',
clientName: 'My App',
autoReconnect: true,
})
}
- state(链接):'discovering' | 'authenticating' | 'connecting' | 'loading' | 'ready' | 'failed'
- tools:MCP 服务器所有可用的工具
- error:连接失败的错误信息
- callTool:调用 MCP 服务器所支持的工具
- retry:用于手动重试链接
- authenticate:手动触发认证流程
- clearStorage:用于清理已存储的 tokens 和 credentials 凭证
通过 state
属性,我们就可以处理各种不同的状态。当失败时,引导用户手动重试。
// Handle different states
if (state === 'failed') {
return (
<div>
<p>Connection failed: {error}</p>
<button onClick={retry}>Retry</button>
<button onClick={authenticate}>Authenticate Manually</button>
</div>
)
}
if (state !== 'ready') {
return <div>Connecting to AI service...</div>
}
当成功链接后,使用 tools
属性,就可以向用户展示当前 MCP 服务器所有可用的工具:
return (
<div>
<h2>Available Tools: {tools.length}</h2>
<ul>
{tools.map(tool => (
<li key={tool.name}>{tool.name}</li>
))}
</ul>
<button onClick={handleSearch}>Search</button>
</div>
)
在以上代码中,点击 Search 按钮时,会调用 handleSearch
方法。在该方法内部,通过 useMcp
函数返回的 callTool
函数来调用当前 MCP 服务器所支持的服务。
const handleSearch = async () => {
try {
const result = await callTool('search', { query: 'example search' })
console.log('Search results:', result)
} catch (err) {
console.error('Tool call failed:', err)
}
}
设置 OAuth 回调
要处理 OAuth 身份验证流程,您需要在应用程序中设置一个回调端点。
1.在 React Router 中设置 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>Authenticating...</h1>
<p>This window should close automatically.</p>
</div>
)
}
function App() {
return (
<Router>
<Routes>
<Route path="/oauth/callback" element={<OAuthCallback />} />
<Route path="/" element={<YourMainComponent />} />
</Routes>
</Router>
)
}
2.在 Next.js Pages Router 中设置 OAuth 回调
// pages/oauth/callback.tsx
import { useEffect } from'react'
import { onMcpAuthorization } from'use-mcp'
exportdefaultfunction OAuthCallbackPage() {
useEffect(() => {
onMcpAuthorization()
}, [])
return (
<div>
<h1>Authenticating...</h1>
<p>This window should close automatically.</p>
</div>
)
}
如果你对 MCP 感兴趣,赶紧试试 use-mcp 这个功能超强的 React 库。