generate-mcp-server

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

generate-mcp-server

生成MCP服务器

Generate a Model Context Protocol (MCP) server from an OpenAPI spec using Speakeasy. The MCP server exposes API operations as tools that AI assistants like Claude can call directly.
使用Speakeasy从OpenAPI规范生成Model Context Protocol(MCP)服务器。MCP服务器会将API操作以工具形式暴露,供Claude等AI助手直接调用。

When to Use

适用场景

  • User wants to create an MCP server from their API
  • User asks about Model Context Protocol integration
  • User wants AI assistants to interact with their API
  • User says: "generate MCP server", "create MCP server", "speakeasy MCP"
  • User asks: "How do I make my API available to Claude?"
  • User mentions: "mcp-typescript", "AI assistant tools", "Claude tools"
  • 用户希望从自身API创建MCP服务器
  • 用户询问Model Context Protocol集成相关问题
  • 用户希望AI助手能与自身API交互
  • 用户提及:"generate MCP server"、"create MCP server"、"speakeasy MCP"
  • 用户提问:"如何让我的API对Claude可用?"
  • 用户提到:"mcp-typescript"、"AI assistant tools"、"Claude tools"

Inputs

输入参数

InputRequiredDescription
OpenAPI specYesPath or URL to the OpenAPI specification
Package nameYesnpm package name for the MCP server (e.g.,
my-api-mcp
)
Auth methodYesHow the API authenticates (bearer token, API key, etc.)
Env var prefixNoPrefix for environment variables (e.g.,
MYAPI
)
Scope strategyNoHow to map operations to scopes (default: read/write by HTTP method)
输入项是否必填描述
OpenAPI规范OpenAPI规范的路径或URL
包名称MCP服务器的npm包名称(例如:
my-api-mcp
认证方式API的认证方式(Bearer令牌、API密钥等)
环境变量前缀环境变量的前缀(例如:
MYAPI
权限范围策略操作与权限范围的映射方式(默认:按HTTP方法分为读/写)

Outputs

输出内容

OutputDescription
MCP serverTypeScript MCP server with one tool per API operation
CLI entry pointCommand-line interface with stdio and SSE transports
Scope definitionsScope-based access control for filtering tools
Docker supportDockerfile and compose config for containerized deployment
Workflow config
.speakeasy/workflow.yaml
configured for MCP generation
输出项描述
MCP服务器每个API操作对应一个工具的TypeScript MCP服务器
CLI入口支持stdio和SSE传输的命令行界面
权限范围定义基于权限范围的访问控制,用于过滤工具
Docker支持用于容器化部署的Dockerfile和compose配置
工作流配置已配置MCP生成的
.speakeasy/workflow.yaml

Prerequisites

前置条件

  1. Speakeasy CLI installed and authenticated:
bash
speakeasy auth login
  1. 已安装并认证Speakeasy CLI:
bash
speakeasy auth login

Or for CI/AI agents:

针对CI/AI代理的方式:

export SPEAKEASY_API_KEY="<your-api-key>"

2. Node.js 20+ installed (for the generated MCP server).

3. A valid OpenAPI spec (3.0 or 3.1). Validate first:
```bash
speakeasy lint openapi --non-interactive -s ./openapi.yaml
Run
speakeasy auth login
to authenticate interactively, or set the
SPEAKEASY_API_KEY
environment variable.
export SPEAKEASY_API_KEY="<your-api-key>"

2. 已安装Node.js 20+(用于运行生成的MCP服务器)。

3. 拥有有效的OpenAPI规范(3.0或3.1版本)。请先验证:
```bash
speakeasy lint openapi --non-interactive -s ./openapi.yaml
运行
speakeasy auth login
进行交互式认证,或设置
SPEAKEASY_API_KEY
环境变量。

Command

命令

The generation uses
speakeasy run
after configuring the workflow, overlays, and gen.yaml. There is no single command -- follow the step-by-step workflow below.
bash
undefined
生成操作需在配置好工作流、覆盖文件和gen.yaml后使用
speakeasy run
。没有单一的命令,请遵循以下分步工作流。
bash
undefined

After all config files are in place:

所有配置文件准备就绪后:

speakeasy run
undefined
speakeasy run
undefined

Step-by-Step Workflow

分步操作流程

Step 1: Create the Scopes Overlay

步骤1:创建权限范围覆盖文件

Create
mcp-scopes-overlay.yaml
in the project root. This controls which API operations become MCP tools and what scopes they require:
yaml
undefined
在项目根目录创建
mcp-scopes-overlay.yaml
。该文件控制哪些API操作会成为MCP工具,以及它们需要的权限范围:
yaml
undefined

mcp-scopes-overlay.yaml

mcp-scopes-overlay.yaml

openapi: 3.1.0 overlay: 1.0.0 info: title: Add MCP scopes version: 0.0.0 actions:

Enable read operations

  • target: $.paths.*["get","head"] update: x-speakeasy-mcp: scopes: [read] disabled: false

Enable write operations

  • target: $.paths.*["post","put","delete","patch"] update: x-speakeasy-mcp: scopes: [write] disabled: false

Disable specific sensitive endpoints (customize as needed)

- target: $.paths["/admin/danger-zone"]["delete"]

update:

x-speakeasy-mcp:

disabled: true

undefined
openapi: 3.1.0 overlay: 1.0.0 info: title: 添加MCP权限范围 version: 0.0.0 actions:

启用读操作

  • target: $.paths.*["get","head"] update: x-speakeasy-mcp: scopes: [read] disabled: false

启用写操作

  • target: $.paths.*["post","put","delete","patch"] update: x-speakeasy-mcp: scopes: [write] disabled: false

禁用特定敏感端点(根据需要自定义)

- target: $.paths["/admin/danger-zone"]["delete"]

update:

x-speakeasy-mcp:

disabled: true

undefined

Step 2: Create the Workflow Configuration

步骤2:创建工作流配置

Create
.speakeasy/workflow.yaml
:
yaml
undefined
创建
.speakeasy/workflow.yaml
yaml
undefined

.speakeasy/workflow.yaml

.speakeasy/workflow.yaml

workflowVersion: 1.0.0 speakeasyVersion: latest sources: My-API: inputs: - location: ./openapi.yaml overlays: - location: mcp-scopes-overlay.yaml output: openapi.yaml targets: mcp-server: target: mcp-typescript source: My-API

Replace `./openapi.yaml` with the actual spec path or URL.

> **Important:** Use the standalone `mcp-typescript` target, not `typescript` with `enableMCPServer: true`. The embedded approach (`enableMCPServer` flag) is deprecated.
workflowVersion: 1.0.0 speakeasyVersion: latest sources: My-API: inputs: - location: ./openapi.yaml overlays: - location: mcp-scopes-overlay.yaml output: openapi.yaml targets: mcp-server: target: mcp-typescript source: My-API

将`./openapi.yaml`替换为实际的规范路径或URL。

> **重要提示:** 使用独立的`mcp-typescript`目标,而非带有`enableMCPServer: true`的`typescript`目标。嵌入方式(`enableMCPServer`标志)已被弃用。

Step 3: Configure gen.yaml

步骤3:配置gen.yaml

Create
.speakeasy/gen.yaml
:
yaml
undefined
创建
.speakeasy/gen.yaml
yaml
undefined

.speakeasy/gen.yaml

.speakeasy/gen.yaml

configVersion: 2.0.0 generation: sdkClassName: MyApiMcp maintainOpenAPIOrder: true devContainers: enabled: true schemaPath: ./openapi.yaml typescript: version: 1.0.0 packageName: my-api-mcp envVarPrefix: MYAPI

Key settings:
- `target: mcp-typescript` in `workflow.yaml` -- this is what triggers MCP server generation
- `packageName` -- the npm package name users will `npx`
- `envVarPrefix` -- prefix for auto-generated env var names
configVersion: 2.0.0 generation: sdkClassName: MyApiMcp maintainOpenAPIOrder: true devContainers: enabled: true schemaPath: ./openapi.yaml typescript: version: 1.0.0 packageName: my-api-mcp envVarPrefix: MYAPI

关键设置:
- `workflow.yaml`中的`target: mcp-typescript`——这是触发MCP服务器生成的配置
- `packageName`——用户将通过`npx`调用的npm包名称
- `envVarPrefix`——自动生成的环境变量名称前缀

Step 4: Generate

步骤4:生成

bash
speakeasy run
For AI-friendly output:
bash
speakeasy run --output console 2>&1 | tail -50
bash
speakeasy run
如需适合AI的输出:
bash
speakeasy run --output console 2>&1 | tail -50

Using the Generated MCP Server

使用生成的MCP服务器

CLI Usage

CLI使用方法

bash
undefined
bash
undefined

Start with stdio transport (default, for local AI assistants)

启动stdio传输(默认,适用于本地AI助手)

npx my-api-mcp mcp start --bearer-auth "YOUR_TOKEN"
npx my-api-mcp mcp start --bearer-auth "YOUR_TOKEN"

Start with SSE transport (for networked deployment)

启动SSE传输(适用于网络部署)

npx my-api-mcp mcp start --transport sse --port 3000 --bearer-auth "YOUR_TOKEN"
npx my-api-mcp mcp start --transport sse --port 3000 --bearer-auth "YOUR_TOKEN"

Filter by scope (only expose read operations)

按权限范围过滤(仅暴露读操作)

npx my-api-mcp mcp start --scope read --bearer-auth "YOUR_TOKEN"
npx my-api-mcp mcp start --scope read --bearer-auth "YOUR_TOKEN"

Mount specific tools only

仅挂载特定工具

npx my-api-mcp mcp start --tool users-get-users --tool users-create-user --bearer-auth "YOUR_TOKEN"
undefined
npx my-api-mcp mcp start --tool users-get-users --tool users-create-user --bearer-auth "YOUR_TOKEN"
undefined

CLI Options

CLI选项

FlagDescriptionDefault
--transport
Transport type:
stdio
or
sse
stdio
--port
Port for SSE transport
2718
--bearer-auth
API authentication tokenRequired
--server-url
Override API base URLFrom spec
--scope
Filter by scope (repeatable)All scopes
--tool
Mount specific tools (repeatable)All tools
--log-level
Logging level
info
标志描述默认值
--transport
传输类型:
stdio
sse
stdio
--port
SSE传输的端口
2718
--bearer-auth
API认证令牌必填
--server-url
覆盖API基础URL来自规范
--scope
按权限范围过滤(可重复使用)所有权限范围
--tool
仅挂载特定工具(可重复使用)所有工具
--log-level
日志级别
info

Claude Desktop Configuration

Claude Desktop配置

Add to
claude_desktop_config.json
:
json
{
  "mcpServers": {
    "my-api": {
      "command": "npx",
      "args": [
        "-y", "--package", "my-api-mcp",
        "--",
        "mcp", "start",
        "--bearer-auth", "<API_TOKEN>"
      ]
    }
  }
}
添加到
claude_desktop_config.json
json
{
  "mcpServers": {
    "my-api": {
      "command": "npx",
      "args": [
        "-y", "--package", "my-api-mcp",
        "--",
        "mcp", "start",
        "--bearer-auth", "<API_TOKEN>"
      ]
    }
  }
}

Claude Code Configuration

Claude Code配置

Add to
.claude/settings.json
or use
claude mcp add
:
json
{
  "mcpServers": {
    "my-api": {
      "command": "npx",
      "args": [
        "-y", "--package", "my-api-mcp",
        "--",
        "mcp", "start",
        "--bearer-auth", "<API_TOKEN>"
      ]
    }
  }
}
添加到
.claude/settings.json
或使用
claude mcp add
json
{
  "mcpServers": {
    "my-api": {
      "command": "npx",
      "args": [
        "-y", "--package", "my-api-mcp",
        "--",
        "mcp", "start",
        "--bearer-auth", "<API_TOKEN>"
      ]
    }
  }
}

Docker Deployment

Docker部署

For production, use SSE transport with Docker:
bash
undefined
生产环境中,使用SSE传输结合Docker:
bash
undefined

Build and run

构建并运行

docker-compose up -d
docker-compose up -d

Configure MCP client to use SSE endpoint

配置MCP客户端以使用SSE端点


The generated project includes a Dockerfile and docker-compose.yaml.

生成的项目包含Dockerfile和docker-compose.yaml。

Example

示例

Full example generating an MCP server for a pet store API:
bash
undefined
为宠物商店API生成MCP服务器的完整示例:
bash
undefined

1. Validate the spec

1. 验证规范

speakeasy lint openapi --non-interactive -s ./petstore.yaml
speakeasy lint openapi --non-interactive -s ./petstore.yaml

2. Create scopes overlay

2. 创建权限范围覆盖文件

cat > mcp-scopes-overlay.yaml << 'EOF' openapi: 3.1.0 overlay: 1.0.0 info: title: Add MCP scopes version: 0.0.0 actions:
  • target: $.paths.*["get","head"] update: x-speakeasy-mcp: scopes: [read] disabled: false
  • target: $.paths.*["post","put","delete","patch"] update: x-speakeasy-mcp: scopes: [write] disabled: false EOF
cat > mcp-scopes-overlay.yaml << 'EOF' openapi: 3.1.0 overlay: 1.0.0 info: title: Add MCP scopes version: 0.0.0 actions:
  • target: $.paths.*["get","head"] update: x-speakeasy-mcp: scopes: [read] disabled: false
  • target: $.paths.*["post","put","delete","patch"] update: x-speakeasy-mcp: scopes: [write] disabled: false EOF

3. Create workflow (assumes .speakeasy/ dir exists)

3. 创建工作流(假设.speakeasy/目录已存在)

mkdir -p .speakeasy cat > .speakeasy/workflow.yaml << 'EOF' workflowVersion: 1.0.0 speakeasyVersion: latest sources: petstore: inputs: - location: ./petstore.yaml overlays: - location: mcp-scopes-overlay.yaml output: openapi.yaml targets: mcp-server: target: mcp-typescript source: petstore EOF
mkdir -p .speakeasy cat > .speakeasy/workflow.yaml << 'EOF' workflowVersion: 1.0.0 speakeasyVersion: latest sources: petstore: inputs: - location: ./petstore.yaml overlays: - location: mcp-scopes-overlay.yaml output: openapi.yaml targets: mcp-server: target: mcp-typescript source: petstore EOF

4. Create gen.yaml

4. 创建gen.yaml

cat > .speakeasy/gen.yaml << 'EOF' configVersion: 2.0.0 generation: sdkClassName: PetStoreMcp maintainOpenAPIOrder: true typescript: version: 1.0.0 packageName: petstore-mcp envVarPrefix: PETSTORE EOF
cat > .speakeasy/gen.yaml << 'EOF' configVersion: 2.0.0 generation: sdkClassName: PetStoreMcp maintainOpenAPIOrder: true typescript: version: 1.0.0 packageName: petstore-mcp envVarPrefix: PETSTORE EOF

5. Generate

5. 生成

speakeasy run
speakeasy run

6. Test locally

6. 本地测试

npx petstore-mcp mcp start --bearer-auth "test-token"
undefined
npx petstore-mcp mcp start --bearer-auth "test-token"
undefined

Expected Output

预期输出

Workflow completed successfully.
Generated TypeScript MCP server in ./
The generated project contains:
  • src/mcp-server/server.ts
    -- Main MCP server factory
  • src/mcp-server/tools/
    -- One tool per API operation
  • src/mcp-server/mcp-server.ts
    -- CLI entry point
  • src/mcp-server/scopes.ts
    -- Scope definitions
Workflow completed successfully.
Generated TypeScript MCP server in ./
生成的项目包含:
  • src/mcp-server/server.ts
    -- 主MCP服务器工厂
  • src/mcp-server/tools/
    -- 每个API操作对应一个工具
  • src/mcp-server/mcp-server.ts
    -- CLI入口点
  • src/mcp-server/scopes.ts
    -- 权限范围定义

Best Practices

最佳实践

  1. Use overlays for MCP config -- never edit the source OpenAPI spec directly
  2. Enhance descriptions for AI -- add documentation overlays so AI assistants understand tool purpose
  3. Filter tools at runtime -- use
    --scope
    and
    --tool
    flags to limit what is exposed
  4. Use environment variables -- never hardcode tokens in config files
  5. Start with read-only scopes -- add write scopes only when needed
  6. Create a dedicated MCP package -- keep MCP separate from your main SDK
  1. 使用覆盖文件配置MCP -- 切勿直接编辑源OpenAPI规范
  2. 为AI优化描述 -- 添加文档覆盖文件,让AI助手理解工具用途
  3. 运行时过滤工具 -- 使用
    --scope
    --tool
    标志限制暴露的内容
  4. 使用环境变量 -- 切勿在配置文件中硬编码令牌
  5. 从只读权限范围开始 -- 仅在需要时添加写权限范围
  6. 创建专用MCP包 -- 将MCP与主SDK分开

What NOT to Do

注意事项

  • Do NOT modify the source OpenAPI spec to add
    x-speakeasy-mcp
    -- use overlays instead
  • Do NOT hardcode API tokens in Claude Desktop or Claude Code config files -- use environment variables or secrets managers
  • Do NOT expose all operations without reviewing them -- disable sensitive admin endpoints
  • Do NOT skip spec validation -- invalid specs produce broken MCP servers
  • Do NOT use the deprecated
    enableMCPServer: true
    flag in gen.yaml -- use the standalone
    mcp-typescript
    target in workflow.yaml instead
  • Do NOT generate without a scopes overlay -- tools will lack scope definitions
  • Do NOT use the generated MCP server as a general SDK -- it is purpose-built for AI assistant integration
  • 请勿修改源OpenAPI规范以添加
    x-speakeasy-mcp
    -- 请使用覆盖文件
  • 请勿在Claude Desktop或Claude Code配置文件中硬编码API令牌 -- 使用环境变量或密钥管理器
  • 请勿未经审核就暴露所有操作 -- 禁用敏感的管理端点
  • 请勿跳过规范验证 -- 无效规范会生成损坏的MCP服务器
  • 请勿使用已弃用的
    enableMCPServer: true
    标志 -- 在workflow.yaml中使用独立的
    mcp-typescript
    目标
  • 请勿在没有权限范围覆盖文件的情况下生成 -- 工具会缺少权限范围定义
  • 请勿将生成的MCP服务器用作通用SDK -- 它是专为AI助手集成设计的

Troubleshooting

问题排查

MCP server fails to start

MCP服务器启动失败

Symptom:
npx my-api-mcp mcp start
errors immediately.
Cause: Missing or invalid authentication flags.
Fix:
bash
undefined
症状:
npx my-api-mcp mcp start
立即报错。
原因: 缺少或无效的认证标志。
解决方法:
bash
undefined

Ensure auth flag matches your API's auth scheme

确保认证标志与API的认证方案匹配

npx my-api-mcp mcp start --bearer-auth "YOUR_TOKEN"
npx my-api-mcp mcp start --bearer-auth "YOUR_TOKEN"

Check --help for available auth flags

查看--help获取可用的认证标志

npx my-api-mcp mcp start --help
undefined
npx my-api-mcp mcp start --help
undefined

No tools appear in AI assistant

AI助手中未显示工具

Symptom: MCP server starts but AI assistant shows no tools.
Cause: Missing
x-speakeasy-mcp
extensions or all operations disabled.
Fix: Verify the scopes overlay is listed in
workflow.yaml
under
overlays:
and that operations have
disabled: false
.
症状: MCP服务器启动,但AI助手中没有显示工具。
原因: 缺少
x-speakeasy-mcp
扩展或所有操作已被禁用。
解决方法: 验证权限范围覆盖文件是否在
workflow.yaml
overlays:
中列出,且操作的
disabled: false

Generation fails with mcp-typescript target

使用mcp-typescript目标时生成失败

Symptom:
speakeasy run
fails when using
target: mcp-typescript
.
Cause: Usually a spec validation issue, missing workflow config, or using the deprecated
enableMCPServer
flag instead of the
mcp-typescript
target.
Fix:
bash
undefined
症状: 使用
target: mcp-typescript
speakeasy run
失败。
原因: 通常是规范验证问题、缺少工作流配置,或使用了已弃用的
enableMCPServer
标志而非
mcp-typescript
目标。
解决方法:
bash
undefined

Validate spec first

先验证规范

speakeasy lint openapi --non-interactive -s ./openapi.yaml
speakeasy lint openapi --non-interactive -s ./openapi.yaml

Ensure workflow.yaml uses target: mcp-typescript (NOT target: typescript with enableMCPServer)

确保workflow.yaml使用target: mcp-typescript(而非target: typescript搭配enableMCPServer)

cat .speakeasy/workflow.yaml
cat .speakeasy/workflow.yaml

Remove enableMCPServer from gen.yaml if present -- it is deprecated

如果gen.yaml中存在enableMCPServer,请移除 -- 该标志已被弃用

undefined
undefined

Tools missing expected operations

工具缺少预期操作

Symptom: Some API operations are not available as MCP tools.
Cause: Operations not targeted by the scopes overlay or explicitly disabled.
Fix: Review
mcp-scopes-overlay.yaml
target selectors. Ensure paths and methods match your spec.
症状: 部分API操作未作为MCP工具提供。
原因: 操作未被权限范围覆盖文件选中,或被显式禁用。
解决方法: 检查
mcp-scopes-overlay.yaml
的目标选择器,确保路径和方法与规范匹配。