优秀的编程知识分享平台

网站首页 > 技术文章 正文

三行代码让 React 全面拥抱 MCP,开发者效率要起飞了?

nanyue 2025-08-05 20:16:19 技术文章 2 ℃

大家好,很高兴又见面了,我是"高级前端进阶",由我带着大家一起关注前端前沿、深入前端底层技术,大家一起进步,也欢迎大家关注、点赞、收藏、转发!

什么是 use-mcp

use-mcp 是一个轻量级的 React Hook,用于连接模型上下文协议 (MCP) 服务器,简化了实现 MCP 标准的 AI 系统的身份验证和工具调用。

典型特征包括:

  • 自动连接管理,支持重新连接和重试
  • OAuth 身份验证流程处理,支持弹出窗口和回退
  • 简单的 React hook 接口,用于 MCP 集成
  • TypeScript 类型,用于编辑器辅助和类型检查
  • 全面的日志记录,方便调试
  • 支持 HTTP 和 SSE(服务器发送事件)传输

目前 use-mcp 在 Github 通过 MIT 协议开源,短短几周已经有超过 0.6k 的 star,是一个值得关注的前端开源项目。

如何使用 use-mcp

首先需要安装相应的依赖:

npm install use-mcp
# or
pnpm add use-mcp
# or
yarn add use-mcp

接着从 use-mcp/react 导入相应的 useMcp Hooks :

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>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>
  }
  // 可用的工具
  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)
    }
  }
  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>
  )
}

如果要处理 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>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>
  )
}

下面是使用 Next.js Pages Router:

// pages/oauth/callback.tsx
import {useEffect} from 'react'
import {onMcpAuthorization} from 'use-mcp'
export default function OAuthCallbackPage() {
  useEffect(() => {
    onMcpAuthorization()
  }, [])
  return (
    <div>
      <h1>Authenticating...</h1>
      <p>This window should close automatically.</p>
    </div>
  )
}

更多关于 use-mcp 的示例可以参考文末资料,本文不再过多展开。

参考资料

https://github.com/modelcontextprotocol/use-mcp

https://dev.to/michael_watson_8780e10ad7/model-context-protocol-mcp-is-the-react-moment-for-ai-3nhg

https://dev.to/noah-00/modern-ui-development-with-ai-coding-figma-designs-via-cursor-mcp-server-155m

https://www.latent.space/p/why-mcp-won

Tags:

最近发表
标签列表