mcp-builder
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseMCP Server Builder
MCP 服务器构建指南
Build production-ready MCP servers with the mcp-use framework. This Skill provides quick-start instructions and best practices for creating MCP servers.
使用mcp-use框架构建可用于生产环境的MCP服务器。本Skill提供了创建MCP服务器的快速入门指南和最佳实践。
Quick Start
快速入门
Always bootstrap with :
npx create-mcp-use-appbash
npx create-mcp-use-app my-mcp-server
cd my-mcp-serverChoose template based on needs:
- - Full-featured with all MCP primitives (tools, resources, prompts) + example widgets
--template starter - - Optimized for ChatGPT widgets with product search example
--template mcp-apps - - Minimal starting point for custom implementation
--template blank
bash
undefined始终使用初始化项目:
npx create-mcp-use-appbash
npx create-mcp-use-app my-mcp-server
cd my-mcp-server根据需求选择模板:
- - 全功能模板,包含所有MCP原语(工具、资源、提示词)+ 示例组件
--template starter - - 针对ChatGPT组件优化,包含商品搜索示例
--template mcp-apps - - 极简起始模板,适用于自定义实现
--template blank
bash
undefinedExample: MCP Apps template
示例:MCP Apps模板
npx create-mcp-use-app my-server --template mcp-apps
cd my-server
yarn install
**Template Details:**
- **starter**: Best for learning - includes all MCP features plus widgets
- **mcp-apps**: Best for ChatGPT apps - includes product carousel/accordion example
- **blank**: Best for experts - minimal boilerplatenpx create-mcp-use-app my-server --template mcp-apps
cd my-server
yarn install
**模板详情:**
- **starter**:最适合学习 - 包含所有MCP功能及组件
- **mcp-apps**:最适合ChatGPT应用 - 包含商品轮播/折叠面板示例
- **blank**:最适合专家 - 仅含必要的基础代码MCP Apps Structure
MCP Apps 项目结构
Automatic Widget Registration
组件自动注册
The mcp-apps and starter templates automatically discover and register React widgets from the folder:
resources/Single-file widget pattern:
resources/
└── weather-display.tsx # Widget name becomes "weather-display"Folder-based widget pattern:
resources/
└── product-search/ # Widget name becomes "product-search"
├── widget.tsx # Entry point (required name!)
├── components/ # Sub-components
├── hooks/ # Custom hooks
├── types.ts
└── constants.tsWhat happens automatically:
- Server scans folder at startup
resources/ - Finds files or
.tsxin folderswidget.tsx - Extracts from each component
widgetMetadata - Registers as MCP Tool (e.g., )
weather-display - Registers as MCP Resource (e.g., )
ui://widget/weather-display.html - Builds widget bundles with Vite
No manual registration needed! Just export and a default component.
widgetMetadatamcp-apps和starter模板会自动发现并注册文件夹中的React组件:
resources/单文件组件模式:
resources/
└── weather-display.tsx # 组件名称为"weather-display"文件夹式组件模式:
resources/
└── product-search/ # 组件名称为"product-search"
├── widget.tsx # 入口文件(必须为此名称!)
├── components/ # 子组件
├── hooks/ # 自定义hooks
├── types.ts
└── constants.ts自动执行流程:
- 服务器启动时扫描文件夹
resources/ - 查找文件或文件夹中的
.tsxwidget.tsx - 从每个组件中提取
widgetMetadata - 注册为MCP工具(例如:)
weather-display - 注册为MCP资源(例如:)
ui://widget/weather-display.html - 使用Vite构建组件包
无需手动注册! 只需导出和默认组件即可。
widgetMetadataDefining Tools
定义工具
Tools are executable functions that AI models can call:
typescript
import { MCPServer, text, object } from "mcp-use/server";
import { z } from "zod";
const server = new MCPServer({
name: "my-server",
version: "1.0.0",
description: "My MCP server"
});
// Simple tool
server.tool(
{
name: "greet-user",
description: "Greet a user by name",
schema: z.object({
name: z.string().describe("The user's name"),
formal: z.boolean().optional().describe("Use formal greeting")
})
},
async ({ name, formal }) => {
const greeting = formal ? `Good day, ${name}` : `Hey ${name}!`;
return text(greeting);
}
);Key points:
- Use Zod for schema validation
- Add to all parameters
.describe() - Return appropriate response types (text, object, widget)
工具是AI模型可调用的可执行函数:
typescript
import { MCPServer, text, object } from "mcp-use/server";
import { z } from "zod";
const server = new MCPServer({
name: "my-server",
version: "1.0.0",
description: "My MCP server"
});
// 简单工具
server.tool(
{
name: "greet-user",
description: "Greet a user by name",
schema: z.object({
name: z.string().describe("The user's name"),
formal: z.boolean().optional().describe("Use formal greeting")
})
},
async ({ name, formal }) => {
const greeting = formal ? `Good day, ${name}` : `Hey ${name}!`;
return text(greeting);
}
);关键点:
- 使用Zod进行 Schema 验证
- 为所有参数添加
.describe() - 返回合适的响应类型(text、object、widget)
Defining Resources
定义资源
Resources expose data that clients can read:
typescript
import { object, text, markdown } from "mcp-use/server";
// Static resource
server.resource(
{
uri: "config://settings",
name: "Application Settings",
description: "Current configuration",
mimeType: "application/json"
},
async () => {
return object({
theme: "dark",
version: "1.0.0"
});
}
);
// Dynamic resource
server.resource(
{
uri: "stats://current",
name: "Current Stats",
description: "Real-time statistics",
mimeType: "application/json"
},
async () => {
const stats = await getStats();
return object(stats);
}
);
// Markdown resource
server.resource(
{
uri: "docs://guide",
name: "User Guide",
description: "Documentation",
mimeType: "text/markdown"
},
async () => {
return markdown("# Guide\n\nWelcome!");
}
);Response helpers available:
- - Plain text
text(string) - - JSON objects
object(data) - - Markdown content
markdown(string) - - HTML content
html(string) - - Binary images
image(buffer, mimeType) - - Audio files
audio(buffer, mimeType) - - Binary data
binary(buffer, mimeType) - - Combine multiple content types
mix(...contents)
Advanced response examples:
typescript
// Audio response
import { audio } from 'mcp-use/server';
// From base64 data
return audio(base64Data, "audio/wav");
// From file path (async)
return await audio("/path/to/audio.mp3");
// Binary data (PDFs, etc.)
import { binary } from 'mcp-use/server';
return binary(pdfBuffer, "application/pdf");
// Mix multiple content types
import { mix, text, object, resource } from 'mcp-use/server';
return mix(
text("Analysis complete:"),
object({ score: 95, status: "pass" }),
resource("report://analysis-123", text("Full report..."))
);资源用于暴露客户端可读取的数据:
typescript
import { object, text, markdown } from "mcp-use/server";
// 静态资源
server.resource(
{
uri: "config://settings",
name: "Application Settings",
description: "Current configuration",
mimeType: "application/json"
},
async () => {
return object({
theme: "dark",
version: "1.0.0"
});
}
);
// 动态资源
server.resource(
{
uri: "stats://current",
name: "Current Stats",
description: "Real-time statistics",
mimeType: "application/json"
},
async () => {
const stats = await getStats();
return object(stats);
}
);
// Markdown资源
server.resource(
{
uri: "docs://guide",
name: "User Guide",
description: "Documentation",
mimeType: "text/markdown"
},
async () => {
return markdown("# Guide\n\nWelcome!");
}
);可用响应辅助函数:
- - 纯文本
text(string) - - JSON对象
object(data) - - Markdown内容
markdown(string) - - HTML内容
html(string) - - 二进制图片
image(buffer, mimeType) - - 音频文件
audio(buffer, mimeType) - - 二进制数据
binary(buffer, mimeType) - - 组合多种内容类型
mix(...contents)
高级响应示例:
typescript
// 音频响应
import { audio } from 'mcp-use/server';
// 从base64数据创建
return audio(base64Data, "audio/wav");
// 从文件路径创建(异步)
return await audio("/path/to/audio.mp3");
// 二进制数据(PDF等)
import { binary } from 'mcp-use/server';
return binary(pdfBuffer, "application/pdf");
// 组合多种内容类型
import { mix, text, object, resource } from 'mcp-use/server';
return mix(
text("Analysis complete:"),
object({ score: 95, status: "pass" }),
resource("report://analysis-123", text("Full report..."))
);Defining Prompts
定义提示词
Prompts are reusable templates for AI interactions:
typescript
server.prompt(
{
name: "code-review",
description: "Generate a code review template",
schema: z.object({
language: z.string().describe("Programming language"),
focusArea: z.string().optional().describe("Specific focus area")
})
},
async ({ language, focusArea }) => {
const focus = focusArea ? ` with focus on ${focusArea}` : "";
return {
messages: [
{
role: "user",
content: {
type: "text",
text: `Please review this ${language} code${focus}.`
}
}
]
};
}
);提示词是可复用的AI交互模板:
typescript
server.prompt(
{
name: "code-review",
description: "Generate a code review template",
schema: z.object({
language: z.string().describe("Programming language"),
focusArea: z.string().optional().describe("Specific focus area")
})
},
async ({ language, focusArea }) => {
const focus = focusArea ? ` with focus on ${focusArea}` : "";
return {
messages: [
{
role: "user",
content: {
type: "text",
text: `Please review this ${language} code${focus}.`
}
}
]
};
}
);Testing Locally
本地测试
Development mode (hot reload):
bash
yarn devProduction mode:
bash
yarn build
yarn startInspector UI:
Access at to test tools, view resources, and try prompts.
http://localhost:3000/inspectorTunneling (test with ChatGPT before deploying):
Option 1 - Auto-tunnel:
bash
mcp-use start --port 3000 --tunnelOption 2 - Separate tunnel:
bash
yarn start # Terminal 1
npx @mcp-use/tunnel 3000 # Terminal 2You'll get a public URL like
https://happy-cat.local.mcp-use.run/mcpTunnel details:
- Expires after 24 hours
- Closes after 1 hour of inactivity
- Rate limit: 10 creations/hour, max 5 active per IP
Learn more: https://mcp-use.com/docs/tunneling
开发模式(热重载):
bash
yarn dev生产模式:
bash
yarn build
yarn start检查器UI:
访问测试工具、查看资源、试用提示词。
http://localhost:3000/inspector隧道(部署前与ChatGPT测试):
选项1 - 自动隧道:
bash
mcp-use start --port 3000 --tunnel选项2 - 独立隧道:
bash
yarn start # 终端1
npx @mcp-use/tunnel 3000 # 终端2你将获得一个公共URL,例如
https://happy-cat.local.mcp-use.run/mcp隧道详情:
- 24小时后过期
- 1小时无活动后关闭
- 速率限制:每小时最多创建10个,每个IP最多5个活跃隧道
Deployment
部署
Deploy to mcp-use Cloud (recommended):
bash
undefined部署到mcp-use Cloud(推荐):
bash
undefinedLogin first (if not already)
先登录(如果尚未登录)
npx mcp-use login
npx mcp-use login
Deploy
部署
yarn deploy
**If authentication error:**
```bash
npx mcp-use login
yarn deployAfter deployment:
- Public URL provided (e.g., )
https://your-server.mcp-use.com/mcp - Auto-scaled and monitored
- HTTPS enabled
- Zero-downtime deployments
yarn deploy
**如果出现认证错误:**
```bash
npx mcp-use login
yarn deploy部署后:
- 提供公共URL(例如:)
https://your-server.mcp-use.com/mcp - 自动扩缩容和监控
- 启用HTTPS
- 零停机部署
Best Practices
最佳实践
Tool Design:
- ✅ One tool = one focused capability
- ✅ Descriptive names and descriptions
- ✅ Use on all Zod fields
.describe() - ✅ Handle errors gracefully
- ✅ Return helpful error messages
Resource Design:
- ✅ Use clear URI schemes (config://, docs://, stats://)
- ✅ Choose appropriate MIME types
- ✅ Use response helpers for cleaner code
- ✅ Make resources dynamic when needed
Prompt Design:
- ✅ Keep prompts reusable
- ✅ Use system messages for context
- ✅ Parameterize with Zod schemas
- ✅ Include clear instructions
Testing:
- ✅ Test with Inspector UI first
- ✅ Use tunneling to test with real clients before deploying
- ✅ Verify all tools, resources, and prompts work as expected
Deployment:
- ✅ Test locally and with tunneling first
- ✅ Run if deploy fails
npx mcp-use login - ✅ Version your server semantically
- ✅ Document breaking changes
工具设计:
- ✅ 一个工具对应一个聚焦的功能
- ✅ 使用描述性的名称和说明
- ✅ 为所有Zod字段添加
.describe() - ✅ 优雅处理错误
- ✅ 返回有帮助的错误信息
资源设计:
- ✅ 使用清晰的URI方案(config://、docs://、stats://)
- ✅ 选择合适的MIME类型
- ✅ 使用响应辅助函数简化代码
- ✅ 必要时将资源设为动态
提示词设计:
- ✅ 保持提示词可复用
- ✅ 使用系统消息提供上下文
- ✅ 使用Zod Schema参数化
- ✅ 包含清晰的指令
测试:
- ✅ 先使用检查器UI测试
- ✅ 部署前使用隧道与真实客户端测试
- ✅ 验证所有工具、资源和提示词按预期工作
部署:
- ✅ 先在本地和隧道环境测试
- ✅ 如果部署失败,运行
npx mcp-use login - ✅ 为服务器使用语义化版本
- ✅ 记录破坏性变更
Widget Support
组件支持
Automatic Widget Registration
组件自动注册
When using the or template, widgets in the folder are automatically registered:
mcp-appsstarterresources/tsx
// resources/weather-display.tsx
import { useWidget, McpUseProvider, type WidgetMetadata } from 'mcp-use/react';
import { z } from 'zod';
const propSchema = z.object({
city: z.string(),
temperature: z.number()
});
// Required: Export widget metadata
export const widgetMetadata: WidgetMetadata = {
description: "Display weather information",
props: propSchema, // Use 'props', not 'schema'!
};
// Required: Export default component
export default function WeatherDisplay() {
const { props, isPending } = useWidget<z.infer<typeof propSchema>>();
// Always handle loading state
if (isPending) return <div>Loading...</div>;
return (
<McpUseProvider autoSize>
<div>
<h2>{props.city}</h2>
<p>{props.temperature}°C</p>
</div>
</McpUseProvider>
);
}Widget automatically becomes available as:
- MCP Tool:
weather-display - MCP Resource:
ui://widget/weather-display.html
使用或模板时,文件夹中的组件会自动注册:
mcp-appsstarterresources/tsx
// resources/weather-display.tsx
import { useWidget, McpUseProvider, type WidgetMetadata } from 'mcp-use/react';
import { z } from 'zod';
const propSchema = z.object({
city: z.string(),
temperature: z.number()
});
// 必填:导出组件元数据
export const widgetMetadata: WidgetMetadata = {
description: "Display weather information",
props: propSchema, // 使用'props',而非'schema'!
};
// 必填:导出默认组件
export default function WeatherDisplay() {
const { props, isPending } = useWidget<z.infer<typeof propSchema>>();
// 始终处理加载状态
if (isPending) return <div>Loading...</div>;
return (
<McpUseProvider autoSize>
<div>
<h2>{props.city}</h2>
<p>{props.temperature}°C</p>
</div>
</McpUseProvider>
);
}组件会自动变为以下可用资源:
- MCP工具:
weather-display - MCP资源:
ui://widget/weather-display.html
Content Security Policy (CSP)
内容安全策略(CSP)
Control what external resources widgets can access:
typescript
export const widgetMetadata: WidgetMetadata = {
description: "Weather widget",
props: z.object({ city: z.string() }),
metadata: {
csp: {
// APIs to call
connectDomains: ["https://api.weather.com"],
// Static assets to load
resourceDomains: ["https://cdn.weather.com"],
// Iframes to embed
frameDomains: ["https://embed.weather.com"],
// Script directives
scriptDirectives: ["'unsafe-inline'"],
},
},
};Alternatively, set at server level:
typescript
server.uiResource({
type: "mcpApps",
name: "my-widget",
htmlTemplate: `...`,
metadata: {
csp: {
connectDomains: ["https://api.example.com"],
resourceDomains: ["https://cdn.example.com"],
},
},
});控制组件可访问的外部资源:
typescript
export const widgetMetadata: WidgetMetadata = {
description: "Weather widget",
props: z.object({ city: z.string() }),
metadata: {
csp: {
// 可调用的API
connectDomains: ["https://api.weather.com"],
// 可加载的静态资源
resourceDomains: ["https://cdn.weather.com"],
// 可嵌入的Iframe
frameDomains: ["https://embed.weather.com"],
// 脚本指令
scriptDirectives: ["'unsafe-inline'"],
},
},
};或者在服务器级别设置:
typescript
server.uiResource({
type: "mcpApps",
name: "my-widget",
htmlTemplate: `...`,
metadata: {
csp: {
connectDomains: ["https://api.example.com"],
resourceDomains: ["https://cdn.example.com"],
},
},
});Dual-Protocol Widget Support
双协议组件支持
mcp-use supports the MCP Apps standard (SEP-1865) with automatic dual-protocol support:
typescript
import { MCPServer } from 'mcp-use/server';
const server = new MCPServer({
name: 'my-server',
version: '1.0.0',
baseUrl: process.env.MCP_URL || 'http://localhost:3000', // Required for widgets
});
// Register a dual-protocol widget
server.uiResource({
type: "mcpApps", // Works with BOTH MCP Apps clients AND ChatGPT
name: "weather-display",
htmlTemplate: `<!DOCTYPE html>...`,
metadata: {
csp: { connectDomains: ["https://api.weather.com"] },
prefersBorder: true,
autoResize: true,
},
});What happens automatically:
- MCP Apps clients (Claude, Goose) receive: with
text/html;profile=mcp-app_meta.ui.* - ChatGPT receives: with
text/html+skybridge_meta.openai/* - Same widget code works everywhere!
mcp-use支持MCP Apps标准(SEP-1865),并自动提供双协议支持:
typescript
import { MCPServer } from 'mcp-use/server';
const server = new MCPServer({
name: 'my-server',
version: '1.0.0',
baseUrl: process.env.MCP_URL || 'http://localhost:3000', // 组件必填
});
// 注册双协议组件
server.uiResource({
type: "mcpApps", // 同时兼容MCP Apps客户端和ChatGPT
name: "weather-display",
htmlTemplate: `<!DOCTYPE html>...`,
metadata: {
csp: { connectDomains: ["https://api.weather.com"] },
prefersBorder: true,
autoResize: true,
},
});自动执行流程:
- MCP Apps客户端(Claude、Goose)接收:及
text/html;profile=mcp-app_meta.ui.* - ChatGPT接收:及
text/html+skybridge_meta.openai/* - 同一组件代码可在所有平台运行!
Custom OpenAI Metadata
自定义OpenAI元数据
Need ChatGPT-specific features? Combine both metadata fields:
typescript
server.uiResource({
type: "mcpApps",
name: "my-widget",
htmlTemplate: `...`,
// Unified metadata (dual-protocol)
metadata: {
csp: { connectDomains: ["https://api.example.com"] },
prefersBorder: true,
},
// ChatGPT-specific overrides
appsSdkMetadata: {
"openai/widgetDescription": "ChatGPT-specific description",
"openai/customFeature": "some-value", // Any custom OpenAI metadata
},
});需要ChatGPT特定功能?可结合两种元数字段:
typescript
server.uiResource({
type: "mcpApps",
name: "my-widget",
htmlTemplate: `...`,
// 统一元数据(双协议)
metadata: {
csp: { connectDomains: ["https://api.example.com"] },
prefersBorder: true,
},
// ChatGPT特定覆盖配置
appsSdkMetadata: {
"openai/widgetDescription": "ChatGPT-specific description",
"openai/customFeature": "some-value", // 任意自定义OpenAI元数据
},
});Project Structure
项目结构
my-mcp-server/
├── resources/ # React widgets (apps-sdk)
│ └── widget.tsx
├── public/ # Static assets
├── index.ts # Server entry point
├── package.json
├── tsconfig.json
└── README.mdmy-mcp-server/
├── resources/ # React组件(apps-sdk)
│ └── widget.tsx
├── public/ # 静态资源
├── index.ts # 服务器入口文件
├── package.json
├── tsconfig.json
└── README.mdCommon Patterns
常见模式
Tool with dual-protocol widget:
typescript
import { MCPServer, widget, text } from 'mcp-use/server';
import { z } from 'zod';
const server = new MCPServer({
name: 'my-server',
version: '1.0.0',
baseUrl: process.env.MCP_URL || 'http://localhost:3000',
});
server.tool(
{
name: "show-data",
description: "Display data with visualization",
schema: z.object({
query: z.string()
}),
widget: {
name: "data-display", // Must exist in resources/
invoking: "Loading...",
invoked: "Data loaded"
}
},
async ({ query }) => {
const data = await fetchData(query);
return widget({
props: { data },
output: text(`Found ${data.length} results`)
});
}
);Resource template (parameterized):
typescript
server.resourceTemplate(
{
uriTemplate: "user://{userId}/profile",
name: "User Profile",
description: "Get user by ID",
mimeType: "application/json"
},
async ({ userId }) => {
const user = await fetchUser(userId);
return object(user);
}
);Error handling:
typescript
server.tool(
{
name: "divide",
schema: z.object({
a: z.number(),
b: z.number()
})
},
async ({ a, b }) => {
if (b === 0) {
return text("Error: Cannot divide by zero");
}
return text(`Result: ${a / b}`);
}
);带双协议组件的工具:
typescript
import { MCPServer, widget, text } from 'mcp-use/server';
import { z } from 'zod';
const server = new MCPServer({
name: 'my-server',
version: '1.0.0',
baseUrl: process.env.MCP_URL || 'http://localhost:3000',
});
server.tool(
{
name: "show-data",
description: "Display data with visualization",
schema: z.object({
query: z.string()
}),
widget: {
name: "data-display", // 必须在resources/中存在
invoking: "Loading...",
invoked: "Data loaded"
}
},
async ({ query }) => {
const data = await fetchData(query);
return widget({
props: { data },
output: text(`Found ${data.length} results`)
});
}
);参数化资源模板:
typescript
server.resourceTemplate(
{
uriTemplate: "user://{userId}/profile",
name: "User Profile",
description: "Get user by ID",
mimeType: "application/json"
},
async ({ userId }) => {
const user = await fetchUser(userId);
return object(user);
}
);错误处理:
typescript
server.tool(
{
name: "divide",
schema: z.object({
a: z.number(),
b: z.number()
})
},
async ({ a, b }) => {
if (b === 0) {
return text("Error: Cannot divide by zero");
}
return text(`Result: ${a / b}`);
}
);Detailed Examples
详细示例
For comprehensive examples and advanced patterns, connect to the mcp-use MCP server which provides:
- Complete example resources for all primitives
- Full working server examples
- Detailed documentation
- Interactive widgets showcase
如需完整示例和高级模式,可连接到mcp-use MCP服务器,它提供:
- 所有原语的完整示例资源
- 完整的可运行服务器示例
- 详细文档
- 交互式组件展示
Learn More
了解更多
- Documentation: https://docs.mcp-use.com
- MCP Apps Standard: https://docs.mcp-use.com/typescript/server/mcp-apps (dual-protocol guide)
- Templates: https://docs.mcp-use.com/typescript/server/templates (template comparison)
- Widget Guide: https://docs.mcp-use.com/typescript/server/ui-widgets
- Examples: https://github.com/mcp-use/mcp-use/tree/main/examples
- Tunneling Guide: https://mcp-use.com/docs/tunneling
- Discord: https://mcp-use.com/discord
- GitHub: https://github.com/mcp-use/mcp-use
- 文档:https://docs.mcp-use.com
- MCP Apps标准:https://docs.mcp-use.com/typescript/server/mcp-apps(双协议指南)
- 模板:https://docs.mcp-use.com/typescript/server/templates(模板对比)
- 组件指南:https://docs.mcp-use.com/typescript/server/ui-widgets
- 示例:https://github.com/mcp-use/mcp-use/tree/main/examples
- 隧道指南:https://mcp-use.com/docs/tunneling
- Discord:https://mcp-use.com/discord
- GitHub:https://github.com/mcp-use/mcp-use
Quick Reference
快速参考
Commands:
- - Bootstrap
npx create-mcp-use-app my-server - - Development mode
yarn dev - - Build for production
yarn build - - Run production server
yarn start - - Start with tunnel
mcp-use start --tunnel - - Authenticate
npx mcp-use login - - Deploy to cloud
yarn deploy
Response helpers:
- ,
text(str),object(data),markdown(str)html(str) - ,
image(buf, mime),audio(buf, mime)binary(buf, mime) - - Combine multiple content types
mix(...) - - Return widget with data
widget({ props, output })
Server methods:
- - Define executable tool
server.tool() - - Define static/dynamic resource
server.resource() - - Define parameterized resource
server.resourceTemplate() - - Define prompt template
server.prompt() - - Define widget resource
server.uiResource() - - Start server
server.listen()
Widget metadata fields:
- - Widget description
description - - Zod schema for widget props
props - - Unified config (dual-protocol)
metadata - - Content Security Policy
metadata.csp - - ChatGPT-specific overrides
appsSdkMetadata
Available templates:
- - Full-featured (tools, resources, prompts, widgets)
starter - - ChatGPT-optimized with product example
mcp-apps - - Minimal boilerplate
blank
命令:
- - 初始化项目
npx create-mcp-use-app my-server - - 开发模式
yarn dev - - 构建生产版本
yarn build - - 运行生产服务器
yarn start - - 启动带隧道的服务器
mcp-use start --tunnel - - 认证
npx mcp-use login - - 部署到云端
yarn deploy
响应辅助函数:
- ,
text(str),object(data),markdown(str)html(str) - ,
image(buf, mime),audio(buf, mime)binary(buf, mime) - - 组合多种内容类型
mix(...) - - 返回带数据的组件
widget({ props, output })
服务器方法:
- - 定义可执行工具
server.tool() - - 定义静态/动态资源
server.resource() - - 定义参数化资源
server.resourceTemplate() - - 定义提示词模板
server.prompt() - - 定义组件资源
server.uiResource() - - 启动服务器
server.listen()
组件元数字段:
- - 组件描述
description - - 组件属性的Zod Schema
props - - 统一配置(双协议)
metadata - - 内容安全策略
metadata.csp - - ChatGPT特定覆盖配置
appsSdkMetadata
可用模板:
- - 全功能(工具、资源、提示词、组件)
starter - - 针对ChatGPT优化,含商品示例
mcp-apps - - 极简基础代码
blank