Skip to main content
Glama

knife4j-mcp

一个基于 Node.js + TypeScript 的标准 MCP server(stdio),用于读取 Knife4j / Swagger 多模块接口文档,并为 Agent 提供结构化接口查询能力。

它适合这样的场景:

  • 文档入口不是单个 OpenAPI spec,而是 Knife4j 聚合页

  • 需要先从 /swagger-resources 获取模块列表

  • 每个模块再去拉自己的 /v2/api-docs

  • 文档可能受 Basic Auth 或自定义 Header 保护

  • Agent 需要根据路径、关键词、tag、字段线索快速定位接口

使用方式

SWAGGER_RESOURCES_URL=http://127.0.0.1:3301/swagger-resources \
npx -y @chaselen/knife4j-mcp

如果文档受保护,也可以一起传认证信息:

SWAGGER_RESOURCES_URL=http://127.0.0.1:3301/swagger-resources \
SWAGGER_BASIC_AUTH=demo:demo \
npx -y @chaselen/knife4j-mcp

说明:

  • 已发布到 npm,可直接通过 npx 启动

  • 要求 Node.js >= 20

  • 这是一个 stdio MCP server,通常由 MCP Client 拉起,而不是手动长期在终端里交互运行

Related MCP server: swagger-json-mcp

MCP Client 接入

这个包不只支持 Codex,也支持 Claude Code、OpenCode,以及其他支持本地 stdio MCP 的客户端。

本质上都可以抽象成下面这组启动参数:

{
  "command": "npx",
  "args": ["-y", "@chaselen/knife4j-mcp"],
  "env": {
    "SWAGGER_RESOURCES_URL": "http://127.0.0.1:3301/swagger-resources",
    "SWAGGER_BASIC_AUTH": "demo:demo"
  }
}

Codex CLI

codex mcp add knife4j-swagger \
  --env SWAGGER_RESOURCES_URL=http://127.0.0.1:3301/swagger-resources \
  --env SWAGGER_BASIC_AUTH=demo:demo \
  -- npx -y @chaselen/knife4j-mcp

Claude Code

CLI 添加方式:

claude mcp add knife4j-swagger \
  --env SWAGGER_RESOURCES_URL=http://127.0.0.1:3301/swagger-resources \
  --env SWAGGER_BASIC_AUTH=demo:demo \
  -- npx -y @chaselen/knife4j-mcp

如果你偏好项目级配置,也可以在项目根目录放一个 .mcp.json

{
  "mcpServers": {
    "knife4j-swagger": {
      "command": "npx",
      "args": ["-y", "@chaselen/knife4j-mcp"],
      "env": {
        "SWAGGER_RESOURCES_URL": "http://127.0.0.1:3301/swagger-resources",
        "SWAGGER_BASIC_AUTH": "demo:demo"
      }
    }
  }
}

OpenCode

opencode.jsonopencode.jsonc 中加入:

{
  "$schema": "https://opencode.ai/config.json",
  "mcp": {
    "knife4j-swagger": {
      "type": "local",
      "command": ["npx", "-y", "@chaselen/knife4j-mcp"],
      "enabled": true,
      "environment": {
        "SWAGGER_RESOURCES_URL": "http://127.0.0.1:3301/swagger-resources",
        "SWAGGER_BASIC_AUTH": "demo:demo"
      }
    }
  }
}

其他客户端

如果你的 MCP 客户端支持本地 stdio server,通常只要把下面三类信息按它自己的格式填进去即可:

  • command: npx

  • args: ["-y", "@chaselen/knife4j-mcp"]

  • env: SWAGGER_RESOURCES_URLSWAGGER_BASIC_AUTHSWAGGER_HEADERS 等环境变量

环境变量

必填

  • SWAGGER_RESOURCES_URL

    • Knife4j / Swagger 聚合入口地址,用来读取模块列表。

    • 这个地址通常就是平台暴露出来的 /swagger-resources,例如:http://127.0.0.1:3301/swagger-resources

    • server 启动后会先请求它,再根据返回结果继续拉取每个模块自己的 Swagger / OpenAPI 文档。

    • 注意:这里填的不是某个单独模块的 /v2/api-docs/v3/api-docs,而是“模块目录入口”。

可选

  • SWAGGER_BASE_URL

    • 用于补全 swagger-resources 里返回的相对路径。

    • 如果模块文档地址是 /api/user/v2/api-docs 这种相对路径,server 会拿它和 SWAGGER_BASE_URL 进行拼接。

    • 未设置时,默认回退到 SWAGGER_RESOURCES_URL 的基址。

    • 常见场景是:swagger-resources 和真实文档地址不在同一个基址下,或者经过了网关改写。

  • SWAGGER_BASIC_AUTH

    • 访问 Swagger 文档时使用的 HTTP Basic Auth 账号密码。

    • 这个值会同时用于请求 SWAGGER_RESOURCES_URL 和每个模块的 spec 文档。

    • 格式是 username:password,例如:demo:demo

    • 不需要带 Basic 前缀,程序会自动转成 Authorization: Basic ... 请求头。

    • 如果你的文档地址本身不需要登录认证,可以不填。

  • SWAGGER_HEADERS

    • 额外附带到所有文档请求上的自定义 HTTP Header。

    • 适合需要 Token、租户标识、环境标识这类网关头的场景。

    • 格式是 JSON 字符串,例如:{"X-Env":"dev","X-Token":"abc"}

    • 这些 Header 会和 Basic Auth 一起生效;如果两者都配置了,请求会同时带上。

  • SWAGGER_MODULE_ALLOWLIST

    • 只加载指定模块,其他模块会被忽略。

    • 适合模块很多、只想给 Agent 暴露其中一部分接口时使用。

    • 格式为逗号分隔,例如:sample-account,sample-auth

    • 这里填写的名称应与 swagger-resources 返回的模块名一致。

  • CACHE_TTL_MS

    • 内存缓存有效期,单位是毫秒。

    • 默认值是 300000,也就是 5 分钟。

    • 在缓存有效期内,查询会直接复用已加载的索引;过期后会在下次刷新时重新拉取远端文档。

  • SWAGGER_REQUEST_TIMEOUT_MS

    • 单次请求 swagger-resources 或模块 spec 的超时时间,单位是毫秒。

    • 默认值是 15000,也就是 15 秒;必须是大于 0 的数字。

  • SWAGGER_FETCH_CONCURRENCY

    • 同时拉取模块 spec 的最大请求数。

    • 默认值是 8,允许设置为 1100 之间的整数。

    • 模块很多或上游网关有连接数限制时,可以适当调低。

  • SWAGGER_EXTERNAL_REF_LIMIT

    • 单个模块最多自动加载的外部 $ref JSON 文档数。

    • 默认值是 32,允许设置为 0200;设置为 0 可关闭外部引用加载。

    • 外部文档使用与主 spec 相同的 Basic Auth、自定义 Header 和请求超时配置。

  • SWAGGER_EXTERNAL_REF_ORIGINS

    • 允许加载跨 origin 外部 $ref 的白名单,使用逗号分隔,例如:https://schemas.example.com,http://localhost:8080

    • 默认只允许与当前模块 spec 同 origin 的外部引用,避免把认证 Header 转发到未授权地址。

    • 白名单按 origin 匹配,配置中的路径会被忽略;只支持 HTTP 和 HTTPS。

  • LOG_LEVEL

    • 日志级别。

    • 当前设为 debug 时会输出更多拉取和解析过程日志,便于排查文档地址、认证或 JSON 格式问题。

一个更完整的例子

SWAGGER_RESOURCES_URL=https://gateway.example.com/swagger-resources \
SWAGGER_BASIC_AUTH=swagger_user:swagger_password \
SWAGGER_HEADERS='{"X-Env":"prod","X-Tenant":"platform"}' \
SWAGGER_MODULE_ALLOWLIST=system-user,system-auth \
npx -y @chaselen/knife4j-mcp

MCP Tools

对外只提供 4 个核心 tools:

  • list_specs:列出模块、spec 地址、加载状态和接口数量

  • find_api:按关键词、path、tag、module、method、接口类型和弃用状态搜索接口

    • 支持 offset + limit 分页

    • total 表示全部命中数,returned 表示本页数量,hasMore 表示是否还有后续结果

    • 相同相关性分数下使用稳定排序,便于可靠翻页

  • get_api_detail:获取单个接口的完整详情,并递归展开请求/响应 schema

    • 默认保持完整兼容输出

    • 传入 includeRaw: false 可省略递归结果中的 raw 和顶层 rawOperation,减少 Agent 上下文占用

  • refresh_specs:强制刷新 swagger-resources 和所有模块 spec

功能

  • 支持读取 Knife4j / Swagger 多模块聚合文档

  • 支持 Basic Auth 和自定义 Header

  • 支持 Swagger 2.0,并尽量兼容 OpenAPI 3

  • 支持按路径、关键词、tag、method 等条件搜索接口

  • 在刷新阶段预计算路径别名和全文搜索文本,减少查询时的重复解析

  • get_api_detail 可使用原始短路径、规范化路径或可唯一匹配的完整网关路径

  • 支持通过 get_api_detail 获取完整接口详情,并递归展开请求/响应 schema

  • 详情会显式返回 operationId、弃用状态、认证要求、servers、externalDocs、callbacks 和 security schemes

  • 请求与响应详情支持 examples、encoding、响应 headers 与 links

  • Schema 展开支持 OpenAPI 3.1 nullable 类型、default、const、examples、读写属性、discriminator 和常用校验约束

  • 支持自动加载并打包跨文件 $ref,同时限制外部文档数量

  • OpenAPI 3.1 webhooks 会作为 kind: "webhook" 的接口参与搜索

  • 支持模块 allowlist、缓存 TTL 和手动刷新

  • 单个模块加载失败不会影响其他模块可用

  • 刷新发生临时失败时保留该模块上一次成功的索引,并在模块状态中标记 stale

  • 聚合入口刷新失败时继续提供上一次成功的完整索引,并标记整体与模块状态为 stale

  • 模块 spec 使用可配置的并发上限拉取,避免刷新时瞬间压高网关连接数

  • 无效 spec 和重复模块名会被隔离并显示为失败状态

兼容性边界

  • 支持 Swagger 2.x、OpenAPI 3.0 和常用 OpenAPI 3.1 JSON Schema 字段。

  • 本地 JSON Pointer 与 HTTP(S) JSON 外部 $ref 可以递归展开;不解析 YAML、file: 或其他协议。

  • 循环引用会保留为带 ref / refName 的节点,避免无限递归。

  • callbackslinkssecuritySchemes 等复杂扩展会保留结构化原始定义;请求和响应的主要 Schema 会进一步展开。

开发与验证

npm install
npm test
npm pack --dry-run
  • npm test 会构建项目并运行 parser、registry、HTTP 配置和 MCP 内存传输集成测试。

最小可运行示例

仓库自带一个 mock 的多模块 Swagger 服务。

1. 启动 mock 文档服务

MOCK_SWAGGER_BASIC_AUTH=demo:demo npm run mock:swagger

默认地址:

  • http://127.0.0.1:3301/swagger-resources

  • http://127.0.0.1:3301/sample-account/v2/api-docs

  • http://127.0.0.1:3301/sample-auth/v2/api-docs

  • http://127.0.0.1:3301/demo/sample-notify/v3/api-docs

2. 构建 MCP server

npm run build

3. 运行 smoke test

SWAGGER_RESOURCES_URL=http://127.0.0.1:3301/swagger-resources \
SWAGGER_BASIC_AUTH=demo:demo \
npm run test:smoke

这个脚本会通过 MCP stdio client 依次调用:

  • tools/list

  • list_specs

  • find_api

  • get_api_detail

它会自动完成一次 list_specs -> find_api -> get_api_detail 的最小联调验证。

Available Tools

4 tools
find_apiFind APIA

Find candidate APIs by path, keyword, tag, module, or method. After locating a candidate, call get_api_detail with its module, path, and method to read the full indexed API documentation instead of fetching Swagger/OpenAPI spec URLs directly.

ParametersJSON Schema
NameRequiredDescriptionDefault
queryNo
pathNo
tagNo
moduleNo
methodNo
limitNo

Output Schema

ParametersJSON Schema
NameRequiredDescription
totalYes
resultsYes

TDQS

A4/5.0
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations provided; description does not disclose read-only nature, auth needs, or rate limits. It hints at not fetching specs directly but lacks full behavioral disclosure.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Two sentences, front-loaded with purpose, no fluff. Could potentially be slightly more concise but overall well-structured.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given 6 parameters and no annotations, description does not explain return value (likely summary of candidates) or how queries interact with other parameters. Output schema exists but content unknown.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Description lists search dimensions (path, keyword, tag, module, method) but does not explain 'query' parameter (likely full-text search) or 'limit' semantics. No enum hints. With 0% schema coverage, description adds some value but leaves gaps.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool finds candidate APIs by various dimensions (path, keyword, etc.) and distinguishes from get_api_detail which retrieves full documentation. It uses specific verb and resource.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines5/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Explicitly states when to use (to find candidate APIs) and provides a follow-up action (use get_api_detail). Implicitly excludes fetching Swagger URLs directly.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

get_api_detailGet API DetailA

Preferred tool for full API documentation. Use module + exact path + HTTP method to read the server-indexed API detail, including recursively expanded request and response schemas. Do not fetch /v2/api-docs, /v3/api-docs, or spec URLs directly.

ParametersJSON Schema
NameRequiredDescriptionDefault
moduleYes
pathYes
methodYes

Output Schema

ParametersJSON Schema
NameRequiredDescription
foundYes
detailNo
errorNo

TDQS

A4.3/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, the description itself clarifies it is a read operation that returns expanded schemas. It does not mention side effects or permissions, which would be expected for a read tool; however, the warning about not fetching spec URLs indicates safe behavior.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is composed of two brief, front-loaded sentences that convey all necessary information without redundancy.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the presence of an output schema, the description sufficiently covers the tool's purpose and usage. It could be enhanced by listing example parameters, but overall it is complete for its complexity.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters2/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema coverage is 0%, so the description must explain parameters. It says 'module + exact path + HTTP method' but does not define what constitutes a valid module, path format, or HTTP method. No examples are given, leaving the agent to infer from context.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description states it is the 'Preferred tool for full API documentation' to 'read the server-indexed API detail, including recursively expanded request and response schemas'. This clearly specifies the verb (read), resource (API detail), and distinguishes it from siblings like find_api.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines5/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

It explicitly says to 'use module + exact path + HTTP method' and warns 'Do not fetch /v2/api-docs, /v3/api-docs, or spec URLs directly', providing clear when and when-not usage guidance.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

list_specsList Swagger SpecsA

List aggregated Knife4j / Swagger modules and their loading status. Use this for module discovery and diagnostics, not for reading API details or fetching spec URLs directly.

ParametersJSON Schema
NameRequiredDescriptionDefault

No parameters

Output Schema

ParametersJSON Schema
NameRequiredDescription
refreshedAtYes
resourcesUrlYes
loadedModulesYes
failedModulesYes
totalOperationsYes
modulesYes
errorsYes

TDQS

A4/5.0
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations provided, and description does not disclose any behavioral traits beyond listing modules and status (e.g., read-only nature, auth needs, rate limits). For a list tool, it's likely benign, but lacks explicit transparency.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Two sentences, front-loaded with core purpose and usage instruction. No wasted words.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given no parameters, presence of output schema, and no annotations, the description is largely complete for a simple list tool. Lacks details on permissions or output structure but output schema covers that.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

No parameters in input schema; schema coverage is 100%. Baseline is 4, and description adds no parameter info as none exist.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

Description clearly states verb 'List' and resource 'aggregated Knife4j / Swagger modules and their loading status', differentiating from siblings by specifying not for reading API details or fetching spec URLs.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Explicitly says use for module discovery and diagnostics, and not for reading API details or fetching spec URLs, providing clear context. Does not name alternative tools but implies boundaries.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

refresh_specsRefresh Swagger SpecsA

Force a reload of swagger-resources and all module specs while keeping partial failures isolated. Use this when upstream docs changed or when a previous lookup returned stale results.

ParametersJSON Schema
NameRequiredDescriptionDefault

No parameters

Output Schema

ParametersJSON Schema
NameRequiredDescription
refreshedAtYes
resourcesUrlYes
loadedModulesYes
failedModulesYes
totalOperationsYes
modulesYes
errorsYes

TDQS

A4.2/5.0
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations provided, so description carries full burden. Discloses that partial failures are isolated, which adds transparency, but does not specify if the operation is safe to call repeatedly or if it requires special permissions. For a mutation (reload) tool, more detail would help.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Two sentences, each providing distinct value: first states the action and a key behavior (failure isolation), second provides usage guidance. No redundant or unnecessary words.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Output schema exists, so return values are covered. Description explains when to use and a behavioral detail. Could mention prerequisites or side effects, but for a zero-param tool with a simple purpose, it's reasonably complete.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Tool has 0 parameters, and schema coverage is 100%. Description doesn't need to add parameter info. Baseline 4 is appropriate.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

Description clearly states the tool forces a reload of swagger-resources and all module specs, distinguishing it from sibling tools that focus on finding, listing, or getting details of APIs.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Explicitly tells when to use: when upstream docs changed or stale results. Does not mention when not to use, but context from sibling tools makes it clear that this is for reloading, not for regular browsing.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

TDQS

A4.3/5.0
Disambiguation5/5

Each tool serves a distinct purpose: search, detail retrieval, listing, and refreshing. No overlap or ambiguity.

Naming Consistency5/5

All tool names follow a consistent 'verb_noun' pattern (find_api, get_api_detail, list_specs, refresh_specs).

Tool Count5/5

With 4 tools, the server is well-scoped for its purpose of API documentation browsing. Each tool is necessary.

Completeness4/5

Covers key operations (search, detail, listing, refresh). Minor gap: no raw spec retrieval, but described as unnecessary.

Maintenance

ActivitySlowing
ResponsivenessSyncing

Resources

Unclaimed servers have limited discoverability.

Looking for Admin?

If you are the server author, to access and configure the admin panel.

Related MCP Connectors

Related MCP Servers

  • F
    license
    B
    quality
    D
    maintenance
    An MCP server that crawls and parses OpenAPI JSON or Swagger UI URLs to provide concise endpoint summaries. It enables LLMs to discover and interact with API interfaces by extracting methods, paths, and operation IDs from documentation sources.
    2
  • A
    license
    Not graded
    quality
    A
    maintenance
    MCP server for loading and exploring OpenAPI/Swagger specifications, enabling AI assistants to dynamically browse API contracts by loading specs, searching endpoints, inspecting schemas, and retrieving operations.
    26
    3
    MIT

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/chaselen/knife4j-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server