mcp-builder

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

MCP 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-app
:
bash
npx create-mcp-use-app my-mcp-server
cd my-mcp-server
Choose template based on needs:
  • --template starter
    - Full-featured with all MCP primitives (tools, resources, prompts) + example widgets
  • --template mcp-apps
    - Optimized for ChatGPT widgets with product search example
  • --template blank
    - Minimal starting point for custom implementation
bash
undefined
始终使用
npx create-mcp-use-app
初始化项目:
bash
npx create-mcp-use-app my-mcp-server
cd my-mcp-server
根据需求选择模板:
  • --template starter
    - 全功能模板,包含所有MCP原语(工具、资源、提示词)+ 示例组件
  • --template mcp-apps
    - 针对ChatGPT组件优化,包含商品搜索示例
  • --template blank
    - 极简起始模板,适用于自定义实现
bash
undefined

Example: 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 boilerplate
npx 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
resources/
folder:
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.ts
What happens automatically:
  1. Server scans
    resources/
    folder at startup
  2. Finds
    .tsx
    files or
    widget.tsx
    in folders
  3. Extracts
    widgetMetadata
    from each component
  4. Registers as MCP Tool (e.g.,
    weather-display
    )
  5. Registers as MCP Resource (e.g.,
    ui://widget/weather-display.html
    )
  6. Builds widget bundles with Vite
No manual registration needed! Just export
widgetMetadata
and a default component.
mcp-apps和starter模板会自动发现并注册
resources/
文件夹中的React组件:
单文件组件模式:
resources/
└── weather-display.tsx  # 组件名称为"weather-display"
文件夹式组件模式:
resources/
└── product-search/      # 组件名称为"product-search"
    ├── widget.tsx       # 入口文件(必须为此名称!)
    ├── components/      # 子组件
    ├── hooks/           # 自定义hooks
    ├── types.ts
    └── constants.ts
自动执行流程:
  1. 服务器启动时扫描
    resources/
    文件夹
  2. 查找
    .tsx
    文件或文件夹中的
    widget.tsx
  3. 从每个组件中提取
    widgetMetadata
  4. 注册为MCP工具(例如:
    weather-display
  5. 注册为MCP资源(例如:
    ui://widget/weather-display.html
  6. 使用Vite构建组件包
无需手动注册! 只需导出
widgetMetadata
和默认组件即可。

Defining 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
    .describe()
    to all parameters
  • 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:
  • text(string)
    - Plain text
  • object(data)
    - JSON objects
  • markdown(string)
    - Markdown content
  • html(string)
    - HTML content
  • image(buffer, mimeType)
    - Binary images
  • audio(buffer, mimeType)
    - Audio files
  • binary(buffer, mimeType)
    - Binary data
  • mix(...contents)
    - Combine multiple content types
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)
    - 纯文本
  • object(data)
    - JSON对象
  • markdown(string)
    - Markdown内容
  • html(string)
    - HTML内容
  • 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 dev
Production mode:
bash
yarn build
yarn start
Inspector UI: Access at
http://localhost:3000/inspector
to test tools, view resources, and try prompts.
Tunneling (test with ChatGPT before deploying):
Option 1 - Auto-tunnel:
bash
mcp-use start --port 3000 --tunnel
Option 2 - Separate tunnel:
bash
yarn start  # Terminal 1
npx @mcp-use/tunnel 3000  # Terminal 2
You'll get a public URL like
https://happy-cat.local.mcp-use.run/mcp
Tunnel details:
  • Expires after 24 hours
  • Closes after 1 hour of inactivity
  • Rate limit: 10 creations/hour, max 5 active per IP
开发模式(热重载):
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
undefined

Login first (if not already)

先登录(如果尚未登录)

npx mcp-use login
npx mcp-use login

Deploy

部署

yarn deploy

**If authentication error:**
```bash
npx mcp-use login
yarn deploy
After 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
    .describe()
    on all Zod fields
  • ✅ 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
    npx mcp-use login
    if deploy fails
  • ✅ 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
mcp-apps
or
starter
template, widgets in the
resources/
folder are automatically registered:
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-apps
starter
模板时,
resources/
文件夹中的组件会自动注册:
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:
    text/html;profile=mcp-app
    with
    _meta.ui.*
  • ChatGPT receives:
    text/html+skybridge
    with
    _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.md
my-mcp-server/
├── resources/           # React组件(apps-sdk)
│   └── widget.tsx
├── public/             # 静态资源
├── index.ts            # 服务器入口文件
├── package.json
├── tsconfig.json
└── README.md

Common 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

了解更多

Quick Reference

快速参考

Commands:
  • npx create-mcp-use-app my-server
    - Bootstrap
  • yarn dev
    - Development mode
  • yarn build
    - Build for production
  • yarn start
    - Run production server
  • mcp-use start --tunnel
    - Start with tunnel
  • npx mcp-use login
    - Authenticate
  • yarn deploy
    - Deploy to cloud
Response helpers:
  • text(str)
    ,
    object(data)
    ,
    markdown(str)
    ,
    html(str)
  • image(buf, mime)
    ,
    audio(buf, mime)
    ,
    binary(buf, mime)
  • mix(...)
    - Combine multiple content types
  • widget({ props, output })
    - Return widget with data
Server methods:
  • server.tool()
    - Define executable tool
  • server.resource()
    - Define static/dynamic resource
  • server.resourceTemplate()
    - Define parameterized resource
  • server.prompt()
    - Define prompt template
  • server.uiResource()
    - Define widget resource
  • server.listen()
    - Start server
Widget metadata fields:
  • description
    - Widget description
  • props
    - Zod schema for widget props
  • metadata
    - Unified config (dual-protocol)
  • metadata.csp
    - Content Security Policy
  • appsSdkMetadata
    - ChatGPT-specific overrides
Available templates:
  • starter
    - Full-featured (tools, resources, prompts, widgets)
  • mcp-apps
    - ChatGPT-optimized with product example
  • blank
    - Minimal boilerplate
命令:
  • 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
    - 组件描述
  • props
    - 组件属性的Zod Schema
  • metadata
    - 统一配置(双协议)
  • metadata.csp
    - 内容安全策略
  • appsSdkMetadata
    - ChatGPT特定覆盖配置
可用模板:
  • starter
    - 全功能(工具、资源、提示词、组件)
  • mcp-apps
    - 针对ChatGPT优化,含商品示例
  • blank
    - 极简基础代码