超强 useMCP() 钩子来了,三行代码搞定各种 MCP 服务器!

服务器 服务器产品
use-mcp 负责处理传输协议(Streamable HTTP 和 Server-Sent Events)、身份验证流和会话管理。它还包含大量功能,可帮助您构建可靠、可扩展和可投入生产的 MCP 客户端。

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 库。


责任编辑:武晓燕 来源: 全栈修仙之路
相关推荐

2020-05-20 12:50:32

代码线性方程开发

2021-12-17 12:12:22

Python 开发数据

2020-05-06 22:01:52

Excel代码Python

2023-07-31 08:02:28

2019-10-09 15:51:45

Python 开发编程语言

2021-11-18 10:20:22

代码PDFPython

2011-07-28 17:33:02

服务器WindowsServ

2012-08-24 09:25:21

服务器虚拟化刀片服务器

2020-08-12 09:14:45

Python验证码工具

2009-11-24 15:34:41

DNS服务器组建

2025-05-29 08:20:00

漏洞web安全网络攻击

2024-01-18 15:18:48

数据模型

2009-02-16 15:35:00

2009-11-26 11:19:52

NIS服务器

2009-11-10 15:12:55

多台DHCP服务器的管

2018-10-07 05:27:03

Python代码机器学习

2010-04-02 13:31:58

戴尔PowerEdge服务器

2010-04-23 14:33:34

邮件服务器加密

2014-07-16 16:23:41

浪潮服务器

2017-08-31 13:50:53

Python编程语言
点赞
收藏

51CTO技术栈公众号