TypeScript模型上下文协议框架

MCP-Use是一个全面的TypeScript框架,用于构建和使用模型上下文协议(MCP)应用程序,支持创建AI代理、构建MCP服务器和调试工具。

  • by mcp-use
  • TypeScript
  • 本地部署
  • 175 星标
  • 更新于
在 GitHub 查看 zandko/mcp-use

使用说明

MCP-Use: The Complete TypeScript Framework for Model Context Protocol

Build powerful AI agents, create MCP servers with UI widgets, and debug with built-in inspector - all in TypeScript


🎯 什么是MCP-Use?

MCP-Use 是一个用于构建和使用的全面 TypeScript 框架 模型上下文协议(MCP) 应用程序。它提供了您创建能够使用工具的AI代理所需的一切,支持构建带有丰富用户界面(UI)的MCP服务器,并提供强大的开发者工具来调试您的应用程序。

📦 包概述

包 描述 版本 下载量
中文翻译 (此处为对应中文翻译,原表中无具体内容) (此处为对应中文翻译,原表中无具体内容) (此处为对应中文翻译,原表中无具体内容)
**[ ](#mcp-use-cli)** @mcp-use/cli(注:这通常是一个命令行界面或命令行工具的名称,直接翻译为中文可能保持原样,因为这不是一个有具体含义的短语,而是特定工具的标识符。) 带有热重载和自动检查器的构建工具
**[ ](#mcp-use-inspector)** @mcp-use/inspector 翻译为中文是:“@mcp-use/检查器” 或 “@mcp-use/监察器”(具体翻译可能根据上下文有所调整,但基本意思是表示一个用于检查或监察的工具或功能) 基于Web的MCP服务器调试器
**[ ](#create-mcp-use-app)** 创建-MCP-使用应用 项目脚手架工具

|

🚀 快速入门

# Create a new MCP application
npx create-mcp-use-app my-mcp-app

# Navigate to your project
cd my-mcp-app

# Start development with hot reload and auto-inspector
npm run dev

在不到一分钟内开始使用MCP: http://localhost:3000 您的MCP服务器现已运行在


浏览器中自动打开检查器!

📚 包文档

mcp-use: 核心框架

MCP-Use生态系统的核心——一个强大的框架,用于构建MCP客户端和服务器。

作为MCP客户端

import { MCPClient, MCPAgent } from 'mcp-use'
import { ChatOpenAI } from '@langchain/openai'

// Configure MCP servers
const client = MCPClient.fromDict({
  mcpServers: {
    filesystem: {
      command: 'npx',
      args: ['@modelcontextprotocol/server-filesystem']
    },
    github: {
      command: 'npx',
      args: ['@modelcontextprotocol/server-github'],
      env: { GITHUB_TOKEN: process.env.GITHUB_TOKEN }
    }
  }
})

// Create an AI agent
const agent = new MCPAgent({
  llm: new ChatOpenAI({ model: 'gpt-4' }),
  client,
  maxSteps: 10
})

// Use the agent with natural language
const result = await agent.run(
  'Search for TypeScript files in the project and create a summary'
)

将任意大型语言模型(LLM)连接到任意MCP服务器,并构建智能代理:

  • 关键客户功能: 机器人与大型语言模型(LLM)无关的
  • 与OpenAI、Anthropic、Google或任何LangChain支持的大型语言模型(LLM)兼容 **🔄(这个符号本身在中文中没有直接对应的翻译,它通常表示“循环”、“重复”或“刷新”的意思,具体含义需结合上下文理解。)**流媒体支持 stream() 实时流媒体播放 streamEvents() 并且
  • 方法 **🌐(表示“互联网”或“世界”的符号,无直接中文对应词汇,可理解为“网络”或“全球”)**多服务器
  • 同时连接到多个MCP服务器 **🔒(锁形图标,通常表示安全、保密或锁定状态)**工具控制
  • 限制对特定工具的访问以确保安全 📊 表格/数据图表可观测性
  • 内置Langfuse集成以进行监控 **🎯(目标、靶心)**服务器管理器

基于可用工具的自动服务器选择

作为MCP服务器框架

import { createMCPServer } from 'mcp-use/server'
import { z } from 'zod'

// Create your MCP server
const server = createMCPServer('weather-server', {
  version: '1.0.0',
  description: 'Weather information MCP server'
})

// Define tools with Zod schemas
server.tool('get_weather', {
  description: 'Get current weather for a city',
  parameters: z.object({
    city: z.string().describe('City name'),
    units: z.enum(['celsius', 'fahrenheit']).optional()
  }),
  execute: async ({ city, units = 'celsius' }) => {
    const weather = await fetchWeather(city, units)
    return {
      temperature: weather.temp,
      condition: weather.condition,
      humidity: weather.humidity
    }
  }
})

// Define resources
server.resource('weather_map', {
  description: 'Interactive weather map',
  uri: 'weather://map',
  mimeType: 'text/html',
  fetch: async () => {
    return generateWeatherMapHTML()
  }
})

// Start the server
server.listen(3000)
// 🎉 Inspector automatically available at http://localhost:3000/inspector
// 🚀 MCP endpoint at http://localhost:3000/mcp

构建您自己的MCP服务器,具备自动检测器和用户界面功能:

  • 关键服务器功能: **🔍 看起来像是一个放大镜的符号,通常用于表示搜索、查看细节或调查等意思。在中文里,可以简单地翻译为“🔍 放大镜”或者根据上下文翻译为“🔍 搜索”、“🔍 查看细节”等。但如果没有具体上下文,最直接的翻译就是“🔍 放大镜”。**汽车检查员 /inspector
  • 调试用户界面会自动挂载在 **🎨 表示“美术”或“绘画”的意思,可以翻译为“🎨(美术/绘画)”。**用户界面小部件(或用户界面控件)
  • 构建与MCP工具一同提供的React组件 **🔐**OAuth 支持
  • 内置的身份验证流程处理 **📡(天线/卫星天线/信号发射器等,具体含义根据上下文而定)**多种运输方式
  • 支持HTTP/SSE和WebSocket **🛠️(工具箱或修理工具的符号,可译为“工具”或根据上下文具体描述为某种修理或工具相关的行为/物品)**TypeScript 首选
  • 完全类型安全和推断 **♻️ 代表“循环”或“回收”(Recycling)的符号。**热重载

带自动重启的开发模式

高级功能

import { streamEventsToAISDKWithTools } from 'mcp-use'
import { LangChainAdapter } from 'ai'

// In your Next.js API route
export async function POST(req: Request) {
  const { prompt } = await req.json()

  const streamEvents = agent.streamEvents(prompt)
  const enhancedStream = streamEventsToAISDKWithTools(streamEvents)
  const readableStream = createReadableStreamFromGenerator(enhancedStream)

  return LangChainAdapter.toDataStreamResponse(readableStream)
}

集成AI SDK的流媒体传输:

// resources/analytics-dashboard.tsx
import { useMcp } from 'mcp-use/react'

export default function AnalyticsDashboard() {
  const { callTool, status } = useMcp()
  const [data, setData] = useState(null)

  useEffect(() => {
    callTool('get_analytics', { period: '7d' })
      .then(setData)
  }, [])

  return (
    <div>
      <h1>Analytics Dashboard</h1>
      {/* Your dashboard UI */}
    </div>
  )
}

自定义UI控件:


完整的MCP使用文档 →

@mcp-use/cli(注:这通常是一个命令行界面(CLI)工具的名称,直接翻译为中文可能不具有实际意义,因此保持原样。若需解释,可译为“@mcp-use 命令行接口”或根据具体上下文进行调整。)

# Development with hot reload
mcp-use dev

# Production build
mcp-use build

# Start production server
mcp-use start

针对MCP应用程序的强大构建与开发工具,集成了检查器功能。

  • 它的功能是:
  • 🚀 在开发模式下自动打开检查器
  • ♻️ 服务器和UI小部件均可进行热重载
  • 📦 将React小部件打包成独立的HTML页面
  • 🏗️ 优化生产构建,使用资源哈希

🛠️ 使用监视模式进行 TypeScript 编译

# Start development
mcp-use dev
# Server running at http://localhost:3000
# Inspector opened at http://localhost:3000/inspector
# Watching for changes...

# Make changes to your code
# Server automatically restarts
# UI widgets hot reload
# Inspector updates in real-time

示例工作流程:


完整的CLI文档 →

@mcp-use/inspector 翻译为中文是:“@mcp-use/检查器” 或者根据具体上下文,也可以翻译为“@mcp-use/监控器/审查器”等,具体取决于该词在实际应用中的功能和用途

基于Web的MCP服务器调试工具——类似于Swagger UI,但专为MCP设计。

  • 特点:
  • 🔍 与实时执行交互的测试工具
  • 📊 监控连接状态和服务器健康状况
  • 🔐 自动处理OAuth流程
  • 💾 使用localStorage实现持久会话

🎨 美观、响应迅速的用户界面

  1. 三种使用方法: 自动的
server.listen(3000)
// Inspector at http://localhost:3000/inspector
  1. **(使用mcp-use服务器):**独立的命令行界面(CLI)
npx mcp-inspect --url https://mcp.example.com/sse
  1. **:**定制安装
import { mountInspector } from '@mcp-use/inspector'
mountInspector(app, '/debug')

:


完整的检查员文档 →

创建MCP并使用应用程序

# Interactive mode
npx create-mcp-use-app

# Direct mode
npx create-mcp-use-app my-app --template advanced

针对MCP应用程序的零配置项目脚手架。

  • 你将获得:
  • ✅ 完成 TypeScript 设置
  • ✅ 预配置的构建脚本
  • ✅ 示例工具和小部件
  • ✅ 开发环境已准备就绪

✅ Docker 和 CI/CD 配置(高级模板)


完整的创建-MCP-使用应用程序文档 →

💡 现实世界中的例子

// Create an agent that can manage files
const agent = new MCPAgent({
  llm: new ChatOpenAI(),
  client: MCPClient.fromDict({
    mcpServers: {
      filesystem: {
        command: 'npx',
        args: ['@modelcontextprotocol/server-filesystem', '/Users/me/documents']
      }
    }
  })
})

// Natural language file operations
await agent.run('Organize all PDF files into a "PDFs" folder sorted by date')
await agent.run('Find all TypeScript files and create a project summary')
await agent.run('Delete all temporary files older than 30 days')

示例1:基于人工智能的文件管理器

// Connect multiple MCP servers
const client = MCPClient.fromDict({
  mcpServers: {
    browser: { command: 'npx', args: ['@playwright/mcp'] },
    search: { command: 'npx', args: ['@mcp/server-search'] },
    memory: { command: 'npx', args: ['@mcp/server-memory'] }
  }
})

const researcher = new MCPAgent({
  llm: new ChatAnthropic(),
  client,
  useServerManager: true // Auto-select appropriate server
})

// Complex research task
const report = await researcher.run(`
  Research the latest developments in quantum computing.
  Search for recent papers, visit official websites,
  and create a comprehensive summary with sources.
`)

示例2:多功能研究助手

const server = createMCPServer('db-admin', {
  version: '1.0.0'
})

server.tool('execute_query', {
  description: 'Execute SQL query safely',
  parameters: z.object({
    query: z.string(),
    database: z.string()
  }),
  execute: async ({ query, database }) => {
    // Validate and execute query
    const results = await db.query(query, { database })
    return { rows: results, count: results.length }
  }
})

// Create an AI-powered DBA
const dba = new MCPAgent({
  llm: new ChatOpenAI({ model: 'gpt-4' }),
  client: new MCPClient({ url: 'http://localhost:3000/mcp' })
})

await dba.run('Show me all users who signed up this week')
await dba.run('Optimize the slow queries in the performance log')

示例3:数据库管理员助手

🏗️ 项目结构

my-mcp-app/
├── src/
│   └── index.ts          # MCP server definition
├── resources/            # UI widgets (React components)
│   ├── dashboard.tsx     # Main dashboard widget
│   └── settings.tsx      # Settings panel widget
├── package.json         # Dependencies and scripts
├── tsconfig.json        # TypeScript configuration
├── .env                 # Environment variables
└── dist/               # Build output
    ├── index.js        # Compiled server
    └── resources/      # Compiled widgets

典型的MCP-Use项目结构:

🛠️ 开发工作流程

# 1. Create your project
npx create-mcp-use-app my-project

# 2. Start development
cd my-project
npm run dev

# 3. Make changes - hot reload handles the rest
# 4. Test with the auto-opened inspector

本地开发

# Build for production
npm run build

# Deploy with Docker
docker build -t my-mcp-server .
docker run -p 3000:3000 my-mcp-server

# Or deploy to any Node.js host
npm run start

生产部署

  • 🤝 社区与支持Discord(一款即时通讯软件) :
  • 加入我们的社区GitHub Issues(在GitHub上用于讨论和跟踪问题的板块) :
  • 报告错误或请求功能文档 :

完整文档

📊 发布与版本管理

这个单体仓库使用了现代的工具进行包管理:

# Create a changeset for your changes
pnpm changeset

# Version packages based on changesets
pnpm changeset version

# Publish all changed packages
pnpm changeset publish

使用更改集(推荐)

# Publish individual packages
pnpm --filter mcp-use publish --access public
pnpm --filter @mcp-use/cli publish --access public
pnpm --filter @mcp-use/inspector publish --access public
pnpm --filter create-mcp-use-app publish --access public

# Or publish all at once
pnpm -r publish --access public

手动发布

🧑‍💻 贡献(或参与贡献) 我们欢迎投稿!请查看我们的 贡献指南

开始吧。

# Clone the repository
git clone https://github.com/mcp-use/mcp-use-ts.git
cd mcp-use-ts

# Install dependencies
pnpm install

# Build all packages
pnpm build

# Run tests
pnpm test

# Start development
pnpm dev

开发环境设置

📜 许可证 麻省理工学院 ©


Built with ❤️ by the MCP-Use team