内容
# MCP 服务器模板
适用于使用 Next.js 和 `mcp-handler` 适配器的模型上下文协议(MCP)服务器的生产就绪模板。
[](https://vercel.com/new/clone?repository-url=https://github.com/RitualChain/mcp-server-template)
## 概述
该模板提供了一种简化的方式来创建 MCP 服务器,可以被 ChatGPT、Claude、Cursor 等 AI 代理以及其他兼容 MCP 的客户端使用。部署一次,连接无处不在。
### 主要功能
- 🚀 **一键部署** 到 Vercel
- 🔧 **轻松创建工具** 使用 Zod 模式进行类型安全输入
- 🌐 **可流式传输的 HTTP 传输** 实现高效的实时通信
- 📦 **预配置** 包含 TypeScript、Tailwind CSS 和 Next.js 16
- 🎨 **内置着陆页** 包含设置说明
---
## 架构
```
┌─────────────────────────────────────────────────────────────────┐
│ MCP 客户端 │
│ (ChatGPT, Claude, Cursor, 自定义代理) │
└──────────────────────────┬──────────────────────────────────────┘
│
│ HTTP(可流式传输的 HTTP 传输)
▼
┌─────────────────────────────────────────────────────────────────┐
│ Next.js 应用程序 │
│ ┌───────────────────────────────────────────────────────────┐ │
│ │ /mcp 端点 │ │
│ │ ┌─────────────────────────────────────────────────────┐ │ │
│ │ │ mcp-handler 适配器 │ │ │
│ │ │ • 工具注册 │ │ │
│ │ │ • 请求/响应处理 │ │ │
│ │ │ • 模式验证(Zod) │ │ │
│ │ └─────────────────────────────────────────────────────┘ │ │
│ │ │ │ │
│ │ ┌──────────────┴──────────────┐ │ │
│ │ ▼ ▼ │ │
│ │ ┌────────────┐ ┌────────────────┐ │ │
│ │ │ 回声 │ │ 获取服务器时间│ │ │
│ │ │ 工具 │ │ 工具 │ │ │
│ │ └────────────┘ └────────────────┘ │ │
│ └───────────────────────────────────────────────────────────┘ │
│ │
│ ┌───────────────────────────────────────────────────────────┐ │
│ │ /(着陆页) │ │
│ │ 设置指南和 MCP URL 显示 │ │
│ └───────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────┘
```
---
## 项目结构
```
mcp-server-template/
├── app/
│ ├── globals.css # 全局样式
│ ├── layout.tsx # 根布局
│ ├── page.tsx # 带有设置说明的着陆页
│ └── mcp/
│ └── route.ts # ⭐ MCP 服务器端点(在此处添加工具)
├── components/
│ ├── theme-provider.tsx # 暗色/亮色主题支持
│ └── ui/ # 可重用的 UI 组件(shadcn/ui)
├── scripts/
│ └── test-streamable-http-client.ts # 用于本地开发的测试客户端
├── public/
│ └── images/ # 设置指南截图
├── package.json
└── README.md
```
---
## 快速入门
### 1. 克隆和安装
```bash
git clone https://github.com/RitualChain/mcp-server-template.git
cd mcp-server-template
bun install
```
### 2. 在本地运行
```bash
bun dev
```
访问 [http://localhost:3030](http://localhost:3030) 查看着陆页。
### 3. 部署到 Vercel
[](https://vercel.com/new/clone?repository-url=https://github.com/RitualChain/mcp-server-template)
或手动部署:
```bash
npx vercel
```
---
## 添加工具
工具在 `app/mcp/route.ts` 中定义。`createMcpHandler` 函数接受三个参数:
1. **工具注册函数** - 异步函数,您在其中使用 `server.tool()` 注册工具
2. **功能** - 服务器功能配置
3. **选项** - 运行时选项,如 `maxDuration` 和 `basePath`
### 工具定义
每个工具需要四个参数:
| 参数 | 类型 | 描述 |
| --------------- | -------- | ---------------------------------------------- |
| `name` | 字符串 | 工具的唯一标识符 |
| `description` | 字符串 | 工具的作用(显示给 AI 代理) |
| `schema` | 对象 | 定义输入参数的 Zod 模式 |
| `handler` | 函数 | 执行工具的异步函数 |
### 当前实现
以下是完整的 `app/mcp/route.ts` 结构:
```typescript
import { createMcpHandler } from "mcp-handler";
import { z } from "zod";
// 流式 HTTP 服务器
const handler = createMcpHandler(
// 1. 工具注册函数
async (server) => {
server.tool(
"echo",
"回声消息以验证输入/输出通信",
{
message: z.string(),
},
async ({ message }) => ({
content: [{ type: "text", text: `工具回声:${message}` }],
})
);
server.tool(
"get_server_time",
"返回当前服务器时间和时区信息",
{},
async () => ({
content: [
{
type: "text",
text: JSON.stringify(
{
serverTime: new Date().toISOString(),
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
timestamp: Date.now(),
},
null,
2
),
},
],
})
);
},
// 2. 功能 - 声明服务器支持工具
{
capabilities: {
tools: {},
},
},
// 3. 选项 - 运行时配置
{
basePath: "",
verboseLogs: true,
maxDuration: 60,
disableSse: true,
}
);
export { handler as GET, handler as POST, handler as DELETE };
```
### 示例:添加新工具
要添加新工具,请在工具注册函数中插入:
```typescript
server.tool(
"get_pokemon",
"从 PokeAPI 获取 Pokemon 数据",
{
name: z.string().describe("Pokemon 名称"),
},
async ({ name }) => {
const response = await fetch(
`https://pokeapi.co/api/v2/pokemon/${name}`
);
const data = await response.json();
return {
content: [
{
type: "text",
text: JSON.stringify(
{
name: data.name,
types: data.types.map((t: { type: { name: string } }) => t.type.name),
height: data.height,
weight: data.weight,
},
null,
2
),
},
],
};
}
);
```
### Zod 模式
使用 Zod 为工具定义类型安全的输入模式:
```typescript
import { z } from "zod";
// 必需字符串
{ message: z.string() }
// 带有描述的字符串(显示给 AI)
{ name: z.string().describe("用户的全名") }
// 可选参数
{ limit: z.number().optional() }
// 默认值
{ count: z.number().default(10) }
// 枚举选择
{ format: z.enum(["json", "text", "markdown"]) }
// 无参数
{}
```
### 工具响应格式
工具必须返回一个带有 `content` 数组的对象。每个内容项都有一个 `type` 和相应的数据:
```typescript
// 文本响应
return {
content: [{ type: "text", text: "您的响应在此处" }],
};
// JSON 响应(字符串化以提高可读性)
return {
content: [
{
type: "text",
text: JSON.stringify({ key: "value" }, null, 2),
},
],
};
// 多个内容项
return {
content: [
{ type: "text", text: "第一部分" },
{ type: "text", text: "第二部分" },
],
};
```
### 内置工具
| 工具 | 描述 |
| ----------------- | ------------------------------------------------------- |
| `echo` | 回声消息(用于测试连接) |
| `get_server_time` | 返回当前服务器时间和时区 |
### 端点发现
在浏览器中访问 `/mcp`(GET 请求)会以 JSON 形式返回服务器信息:
```json
{
"name": "MCP 服务器模板",
"version": "0.1.0",
"protocol": "模型上下文协议(MCP)",
"transport": "流式 HTTP",
"status": "running",
"tools": [...],
"usage": {
"note": "此端点使用 POST 进行 MCP 通信",
"test": "npx tsx scripts/test-streamable-http-client.ts <origin>",
"docs": "https://modelcontextprotocol.io"
}
}
```
MCP 客户端通过 **POST** 请求与此端点通信。
---
## 连接 MCP 客户端
### ChatGPT
1. 进入 **设置** → **应用程序和连接器**
2. 点击 **创建** 添加新的连接器
3. 输入您的 MCP URL:`https://your-app.vercel.app/mcp`
4. 选择“无身份验证”并确认
参见 [着陆页](/) 了解带有截图的详细逐步说明。
### Cursor
添加到您的 `.cursor/mcp.json`:
```json
{
"mcpServers": {
"my-mcp-server": {
"url": "https://your-app.vercel.app/mcp"
}
}
}
```
### Claude 桌面版
添加到您的 Claude 配置文件:
```json
{
"mcpServers": {
"my-mcp-server": {
"command": "npx",
"args": ["-y", "mcp-remote", "https://your-app.vercel.app/mcp"]
}
}
}
```
---
## 测试
### 使用测试客户端
```bash
npx tsx scripts/test-streamable-http-client.ts https://your-app.vercel.app
```
这将连接到您的 MCP 服务器并列出可用的工具。
添加 `--verbose` 或 `-v` 以获取详细的输出,包括工具模式:
```bash
npx tsx scripts/test-streamable-http-client.ts https://your-app.vercel.app --verbose
```
### 本地开发
```bash
# 终端 1:启动开发服务器
bun dev
# 终端 2:测试 MCP 端点
npx tsx scripts/test-streamable-http-client.ts http://localhost:3030
```
---
## 配置参考
### 处理程序选项
`createMcpHandler` 的第三个参数配置运行时行为:
```typescript
{
basePath: "", // MCP 路由的基本路径(空 = /mcp)
verboseLogs: true, // 启用详细的调试日志记录
maxDuration: 60, // 最大执行时间(秒)
disableSse: true, // 使用流式 HTTP 而不是 SSE
}
```
| 选项 | 类型 | 默认值 | 描述 |
| ------------- | ------- | ------- | ------------------------------------------------ |
| `basePath` | 字符串 | `""` | MCP 端点的基本路径前缀 |
| `verboseLogs` | 布尔值 | `false` | 启用详细的调试日志记录 |
| `maxDuration` | 数字 | `60` | 最大函数执行时间(秒) |
| `disableSse` | 布尔值 | `false` | 使用流式 HTTP 传输代替 SSE |
### Vercel 配置
对于 Vercel 上的最佳性能:
1. **启用 Fluid Compute** 在您的项目设置中以实现高效执行
2. **调整 `maxDuration`** 根据您的计划:
| 计划 | 最大时长 |
| ---------- | ------------ |
| 休闲 | 60 秒 |
| 专业 | 800 秒 |
| 企业 | 800 秒 |
```typescript
// 适用于 Pro/Enterprise 账户
{
basePath: "",
verboseLogs: true,
maxDuration: 800, // 从默认值 60 增加
disableSse: true,
}
```
---
## 环境变量
| 变量 | 描述 | 必需 |
| --------------------- | ---------------------------------------------- | -------- |
| `NEXT_PUBLIC_APP_URL` | 您的生产 URL(用于着陆页显示) | 可选 |
---
## 技术栈
- **框架**: [Next.js 16](https://nextjs.org/)
- **MCP 适配器**: [mcp-handler](https://www.npmjs.com/package/mcp-handler)
- **MCP SDK**: [@modelcontextprotocol/sdk](https://github.com/modelcontextprotocol/typescript-sdk)
- **验证**: [Zod](https://zod.dev/)
- **样式**: [Tailwind CSS 4](https://tailwindcss.com/)
- **组件**: [shadcn/ui](https://ui.shadcn.com/)
---
## 资源
- [MCP TypeScript SDK 文档](https://github.com/modelcontextprotocol/typescript-sdk)
- [模型上下文协议规范](https://modelcontextprotocol.io/)
- [Vercel MCP 模板](https://vercel.com/templates/next.js/model-context-protocol-mcp-with-next-js)
- [mcp-handler npm 包](https://www.npmjs.com/package/mcp-handler)
---
## 许可证
MIT © [Ritual Chain](https://github.com/RitualChain)
MCP 配置
以下是此 MCP Server 的配置信息,可直接复制到 Cursor 或其他 MCP 客户端中使用。
mcp.json
连接信息
猜你喜欢
暂无推荐服务器