# 系统工具开发指南

> 学习如何从零开发 FastGPT 系统工具插件，定义输入输出契约、密钥配置、运行逻辑并打包发布。

Source: https://doc.fastgpt.cn/plugin/system-tool-development
Last Updated: 2026-12-01

## 介绍

本文面向 FastGPT v4.15.0 之后的系统工具开发。系统工具使用 SDK 定义功能，以 `.pkg` 文件交付给 FastGPT Plugin 服务，由服务完成安装、更新和运行管理。模型预设采用[静态配置贡献流程](https://doc.fastgpt.cn/plugin/model-presets)。

当前稳定支持的系统工具插件类型有两种：

* 单工具：一个插件只暴露一个工具，使用 `defineTool()` 声明。
* 工具集：一个插件暴露多个相关子工具，使用 `defineToolSet()` 声明。

系统工具插件运行在 FastGPT Plugin 服务提供的运行时中。FastGPT 主服务通过插件服务调用工具，插件代码通过 `@fastgpt-plugin/sdk-factory` 描述输入、输出、密钥配置和执行逻辑。

## 与旧版机制的区别

1. FastGPT 和 FastGPT Plugin 的部署关系保持外置扩展模式，整体仍然是微服务架构。
2. 插件包协议从旧的内置系统工具目录升级为统一 `.pkg` 格式，便于安装、版本管理、热更新和后续扩展其他插件类型。
3. 插件运行时由服务端统一管理，当前默认运行时是 `local-pool`，每个插件版本拥有独立进程池、队列和运行时配置。
4. 插件元信息、输入输出 schema、密钥 schema 和图标资源都会进入构建产物，供 FastGPT 页面、工作流和 Agent 调用使用。
5. 工具开发使用 `@fastgpt-plugin/cli` 和 `@fastgpt-plugin/sdk-factory` 完成生命周期定义与打包。

## 开发前准备

开始编码前先明确这些信息：

| 信息     | 说明                                                                                                   |
| ------ | ---------------------------------------------------------------------------------------------------- |
| 插件类型   | `tool` 或 `tool-suite`。                                                                               |
| 插件 ID  | `pluginId`，全局稳定唯一，发布后保持不变。                                                                           |
| 子工具 ID | 工具集需要，`children[].id` 发布后保持不变。                                                                       |
| 中英文名称  | `name.en` 和 `name.zh-CN`。                                                                            |
| 中英文描述  | `description.en` 和 `description.zh-CN`。                                                              |
| 输入     | 每个字段的类型、约束、默认值、UI 标题和说明。                                                                             |
| 输出     | 每个字段的类型、含义和下游使用方式。                                                                                   |
| 密钥     | API Key、Base URL、账号密码等，通过 `secretSchema` 描述。                                                         |
| 外部 API | 请求方式、鉴权方式、超时、限流、错误响应和测试账号。                                                                           |
| 文件能力   | 需要上传文件时使用 `ctx.invoke.uploadFile()`，并声明 `file-upload:allow` 权限。                                      |
| 模型调用   | 需要反向调用 FastGPT 平台模型时，使用 `Model` 声明模型入参、声明 `model:invoke` 权限，并通过 `ctx.invoke.createModelClient()` 调用。 |
| 流式输出   | 需要流式返回文本回答时使用 `ctx.streamResponse()`。                                                                |
| 测试样例   | 至少包含成功路径、参数错误、鉴权失败和上游失败。                                                                             |

影响插件 ID、鉴权方式、计费或上架安全性的信息需要先确认。其他信息可以使用合理默认值继续推进，并在提交说明中记录假设。

## 使用 Agent 开发

使用 Claude Code、Codex 或其他 Agent 工具时，可直接复制下面的提示词：

```plaintext
请根据以下 FastGPT 官方插件开发 Skill 开发插件：

https://raw.githubusercontent.com/labring/fastgpt-official-plugins/refs/heads/main/.agents/skills/develop-fastgpt-plugin/SKILL.md

执行要求：

1. 先读取并理解该 Skill 的完整内容，后续开发流程以该 Skill 为准。
2. 在开始编码前，收集插件名称、插件类型、中文/英文名称与描述、输入输出、密钥、外部 API、预期行为、错误处理和测试样例。
3. 如需求缺失，最多提出 3 个关键问题；如果可以合理默认，说明假设后继续推进。
4. 使用 `@fastgpt-plugin/cli` 创建插件骨架，并优先遵循仓库内已有插件的结构、命名、测试和构建方式。
5. 实现完成后运行必要验证，包括测试、构建、插件检查和打包；无法验证的项目需要说明原因。
6. 最终输出变更文件、验证结果、剩余假设和需要人工确认的外部 API 行为。
```

在 `fastgpt-plugin` 仓库内开发或维护 SDK/CLI 时，也可以参考本地 Skill：

* `sdk/factory/skills/fastgpt-plugin-development/SKILL.md`
* `sdk/factory/skills/fastgpt-system-tool-development/SKILL.md`
* `sdk/factory/skills/fastgpt-sdk-factory/SKILL.md`

## 1. 准备开发环境

推荐环境：

* Node.js 22（`>= 22.23.2`）。
* `pnpm` 10，当前 `fastgpt-plugin` 仓库使用 pnpm workspace。
* Git。
* GitHub CLI `gh`，用于 fork、创建仓库和提交 PR。

开发社区插件时，先 fork 并 clone 社区插件仓库：

```bash
gh repo fork labring/fastgpt-community-plugins --clone
cd fastgpt-community-plugins
pnpm install
```

在 `fastgpt-plugin` 仓库内调试 CLI 或 SDK 时，先安装依赖并构建 CLI/SDK：

```bash
pnpm install
pnpm build:sdk-factory
pnpm build:cli
```

## 2. 创建插件骨架

单工具插件：

```bash
pnpx @fastgpt-plugin/cli create my-tool --type tool --cwd packages/tools
```

工具集插件：

```bash
pnpx @fastgpt-plugin/cli create my-tool-suite --type tool-suite --cwd packages/tools
```

也可以进入目标目录后交互式创建：

```bash
pnpx @fastgpt-plugin/cli create
```

CLI 会创建插件目录，并生成常见文件：

| 文件                 | 作用                                                                            |
| ------------------ | ----------------------------------------------------------------------------- |
| `index.ts`         | 插件入口，默认导出 `defineTool()` 或 `defineToolSet()`。                                 |
| `index.spec.ts`    | 单元测试文件。                                                                       |
| `package.json`     | 插件依赖和 `build`、`build:dev`、`check`、`dev`、`debug`、`debug:run`、`pack`、`test` 脚本。 |
| `tsconfig.json`    | TypeScript 配置。                                                                |
| `vitest.config.ts` | 测试配置。                                                                         |
| `README.md`        | 默认插件说明。                                                                       |
| `README.zh-CN.md`  | 简体中文插件说明。                                                                     |
| `README.en.md`     | 英文插件说明。                                                                       |
| `logo.svg`         | 插件主图标。                                                                        |

## 3. 实现单工具

系统工具入口必须默认导出 SDK factory 实例：

```ts
import {
  createToolHandler,
  defineTool,
  type InputSchemaMetaType,
  type OutputSchemaMetaType,
  type SecretSchemaMetaType
} from '@fastgpt-plugin/sdk-factory';
import z from 'zod';

const secretSchema = z.object({
  apiKey: z
    .string()
    .min(1)
    .meta({
      title: 'API Key',
      isSecret: true
    } satisfies SecretSchemaMetaType)
});

const handler = createToolHandler({
  inputSchema: z.object({
    query: z
      .string()
      .min(1)
      .meta({
        title: 'Query',
        description: 'Search keyword'
      } satisfies InputSchemaMetaType)
  }),
  outputSchema: z.object({
    result: z.string().meta({
      title: 'Result'
    } satisfies OutputSchemaMetaType)
  }),
  secretSchema,
  handler: async (input, ctx) => {
    return {
      result: input.query
    };
  }
});

export default defineTool({
  manifest: {
    pluginId: 'example-search',
    version: '1.0.0',
    name: {
      en: 'Example Search',
      'zh-CN': '示例搜索'
    },
    description: {
      en: 'Search example data',
      'zh-CN': '搜索示例数据'
    },
    versionDescription: {
      en: 'Initial version',
      'zh-CN': '初始版本'
    },
    tags: ['tools']
  },
  handler
});
```

核心规则：

* `pluginId`、子工具 `id`、输入字段名、输出字段名发布后保持稳定。
* `manifest.name`、`manifest.description` 和 `versionDescription` 使用 `{ en, 'zh-CN' }`。
* 输入、输出和密钥都用 Zod schema 描述。
* 输入字段补充 `InputSchemaMetaType`，输出字段补充 `OutputSchemaMetaType`。
* 密钥字段补充 `SecretSchemaMetaType`，敏感字段设置 `isSecret: true`。
* handler 返回值必须匹配 `outputSchema`。
* 外部 API 错误需要转成可定位的错误信息，并避免输出密钥、令牌和完整敏感响应。
* 调用宿主文件上传能力时，使用 `ctx.invoke.uploadFile()` 并在 `manifest.permission` 中声明 `file-upload:allow`，优先保留返回的 `err`。
* 需要反向调用 FastGPT 平台模型时，在 `manifest.permission` 中声明 `model:invoke`，在 `inputSchema` 中使用 `Model`（`format: 'modelId'`）声明单个模型入参（建议设置 `isToolParam: false`），并通过 `ctx.invoke.createModelClient()` 获取标准 OpenAI SDK 客户端发起 `chat.completions.create()` 调用。
* 需要流式输出文本回答时，使用 `ctx.streamResponse({ type: 'answer' | 'fastAnswer', content })`。

## 4. 实现工具集

工具集使用 `defineToolSet()`，把共用信息放在顶层 `manifest` 和 `secretSchema`，每个子工具在 `children` 中声明独立 `id`、名称、描述和 handler。

```ts
import {
  createToolHandler,
  defineToolSet,
  type InputSchemaMetaType,
  type OutputSchemaMetaType,
  type SecretSchemaMetaType
} from '@fastgpt-plugin/sdk-factory';
import z from 'zod';

const secretSchema = z.object({
  apiKey: z.string().meta({
    title: 'API Key',
    isSecret: true
  } satisfies SecretSchemaMetaType)
});

const searchHandler = createToolHandler({
  inputSchema: z.object({
    query: z.string().meta({
      title: 'Query'
    } satisfies InputSchemaMetaType)
  }),
  outputSchema: z.object({
    items: z.array(z.string()).meta({
      title: 'Items'
    } satisfies OutputSchemaMetaType)
  }),
  secretSchema,
  handler: async (input) => ({ items: [input.query] })
});

const summaryHandler = createToolHandler({
  inputSchema: z.object({
    content: z.string().meta({
      title: 'Content'
    } satisfies InputSchemaMetaType)
  }),
  outputSchema: z.object({
    summary: z.string().meta({
      title: 'Summary'
    } satisfies OutputSchemaMetaType)
  }),
  secretSchema,
  handler: async (input) => ({ summary: input.content.slice(0, 100) })
});

export default defineToolSet({
  manifest: {
    pluginId: 'text-tools',
    version: '1.0.0',
    name: {
      en: 'Text Tools',
      'zh-CN': '文本工具集'
    },
    description: {
      en: 'Search and summarize text',
      'zh-CN': '搜索和总结文本'
    }
  },
  children: [
    {
      id: 'search',
      name: { en: 'Search', 'zh-CN': '搜索' },
      description: { en: 'Search text', 'zh-CN': '搜索文本' },
      handler: searchHandler
    },
    {
      id: 'summary',
      name: { en: 'Summary', 'zh-CN': '总结' },
      description: { en: 'Summarize text', 'zh-CN': '总结文本' },
      handler: summaryHandler
    }
  ],
  secretSchema
});
```

## 5. 图标规范

CLI 构建时会扫描插件根目录中的图标并写入构建后的 `manifest.json`。

| 场景       | 文件名                                                                   |
| -------- | --------------------------------------------------------------------- |
| 主插件图标    | `logo.svg`、`logo.png`、`logo.jpg`、`logo.jpeg`、`logo.webp` 或 `logo.gif` |
| 工具集子工具图标 | `<childId>.logo.svg`、`<childId>.logo.png` 等                           |

注意事项：

* 图标文件放在插件根目录。
* 子工具图标的 `<childId>` 与 `children[].id` 完全一致。
* 同一个图标只保留一个扩展名，避免扫描结果不明确。
* 子工具没有独立图标时，默认复用主插件图标。
* 构建后检查 `dist/manifest.json` 中的 `icon` 字段。

## 6. 关键开发配方

### 6.1 鉴权外部 API 请求与安全调用

调用需要 API Key 的外部第三方服务时，通过 `secretSchema` 声明密钥字段，并在 handler 中通过 `ctx.secrets` 提取。捕获网络和 HTTP 错误并输出易于定位的问题描述，在错误信息中隐藏密钥：

```ts
import {
  createToolHandler,
  defineTool,
  type InputSchemaMetaType,
  type OutputSchemaMetaType,
  type SecretSchemaMetaType
} from '@fastgpt-plugin/sdk-factory';
import z from 'zod';

const secretSchema = z.object({
  apiKey: z
    .string()
    .min(1)
    .meta({
      title: 'API Key',
      isSecret: true
    } satisfies SecretSchemaMetaType)
});

const UPSTREAM_SEARCH_URL = 'https://api.example.com/v1/search';

const handler = createToolHandler({
  inputSchema: z.object({
    query: z
      .string()
      .min(1)
      .meta({
        title: '查询词',
        description: '发送到受信任外部服务的检索关键词'
      } satisfies InputSchemaMetaType)
  }),
  outputSchema: z.object({
    status: z.string().meta({
      title: '请求状态'
    } satisfies OutputSchemaMetaType),
    data: z.any().meta({
      title: '返回数据'
    } satisfies OutputSchemaMetaType)
  }),
  secretSchema,
  handler: async (input, ctx) => {
    try {
      const requestUrl = new URL(UPSTREAM_SEARCH_URL);
      requestUrl.searchParams.set('q', input.query);
      const res = await fetch(requestUrl.toString(), {
        headers: {
          Authorization: `Bearer ${ctx.secrets.apiKey}`,
          'Content-Type': 'application/json'
        }
      });
      if (!res.ok) {
        throw new Error(`Upstream service returned status ${res.status}`);
      }
      const data = await res.json();
      return { status: 'success', data };
    } catch (err: any) {
      throw new Error(`External API request failed: ${err.message || 'unknown error'}`);
    }
  }
});
```

将携带密钥的请求目标固定在受信任的服务端常量或受控配置中，避免将调用方或模型可控的任意 URL 直接作为发送 `ctx.secrets` 的目标地址。

### 6.2 宿主文件上传与产物返回

当工具需要生成文件（如报表、导出的图片或音视频）并返回给 FastGPT 用户时，调用宿主提供的文件上传能力 `ctx.invoke.uploadFile()`。宿主负责安全存储并生成外部访问链接：

```ts
handler: async (input, ctx) => {
  const content = Buffer.from(
    `Report for ${input.query}\nGenerated at ${new Date().toISOString()}`
  );
  const [result, err] = await ctx.invoke.uploadFile({
    file: content,
    fileName: 'report.txt',
    contentType: 'text/plain'
  });

  if (err) {
    throw new Error(`Failed to upload generated file: ${err}`);
  }

  return {
    fileUrl: result.accessURL,
    filename: 'report.txt'
  };
};
```

### 6.3 流式文本回答输出

需要将工具生成的文本实时流式输出到对话窗口时，使用 `ctx.streamResponse()` 发送 `{ type: 'answer' | 'fastAnswer', content: string }` 消息：

```ts
handler: async (input, ctx) => {
  await ctx.streamResponse({
    type: 'answer',
    content: 'Fetching remote resources...\n'
  });

  // 执行核心业务处理
  await ctx.streamResponse({
    type: 'answer',
    content: 'Processing complete.\n'
  });

  return { result: 'Operation completed successfully' };
};
```

### 6.4 外部副作用与重复调用控制

FastGPT 工作流和智能体在循环节点或网络波动时可能对同一工具发起多次重复调用。针对具备写操作、外部扣费或发送消息等副作用的接口：

* **业务幂等性**：建议在输入 Schema 中增加业务唯一标识（如 `requestId` 或 `orderId`），并在外部服务侧确保幂等执行。
* **状态感知**：对于已完成的外部任务，优先返回已有结果。
* **明确超时**：设置明确的 `fetch` 超时时限，及时捕获中断信号并停止后续处理。

### 6.5 模型反向调用（OpenAI SDK）

当工具在执行过程中需要调用 FastGPT 平台已配置的大语言模型完成总结、提取或推理时，可通过 `ctx.invoke.createModelClient()` 创建标准的官方 `OpenAI` SDK 客户端，由 FastGPT 宿主统一完成团队模型鉴权、代理转发与实时透明计费。

> * 模型反向调用当前需使用已发布的支持版本：`@fastgpt-plugin/sdk-factory@1.2.0-beta.4` 与 `@fastgpt-plugin/cli@0.2.2-beta.1`（npm 默认 `latest` 版本尚未包含 `Model`、`createModelClient()` 及远程 `chatCompletion` 联调支持；远程联调请执行 `pnpx @fastgpt-plugin/cli@0.2.2-beta.1 dev`），并确认测试环境的 FastGPT 主服务与 FastGPT Plugin 服务均已包含 `model:invoke` 能力。
> * 工具入参仅支持**单个模型**传入（使用 SDK 导出的 `Model` 常量，生成 `format: 'modelId'`），FastGPT 在工作流工具节点与 Agent 工具配置弹窗中自动渲染模型选择器，并禁止 Agent 运行时自行编造或覆盖模型参数。
> * 当前仅开放 `chat.completions` 对话补全接口（覆盖 LLM / VLM），且 `model` 参数必须传入 FastGPT 传入的 `modelId`，禁止直接传入原始上游模型名。

完整示例：

```ts
import {
  createToolHandler,
  defineInputSchema,
  defineOutputSchema,
  defineTool,
  Model
} from '@fastgpt-plugin/sdk-factory';
import z from 'zod';

const handler = createToolHandler({
  inputSchema: defineInputSchema({
    model: {
      type: Model,
      title: { en: 'Model', 'zh-CN': '模型' },
      description: {
        en: 'FastGPT chat model used to summarize content',
        'zh-CN': '用于总结内容的 FastGPT 对话模型'
      },
      isToolParam: false
    },
    content: {
      type: z.string().min(1),
      title: { en: 'Content', 'zh-CN': '待处理文本' },
      isToolParam: true
    },
    stream: {
      type: z.boolean().default(false).optional(),
      title: { en: 'Stream output', 'zh-CN': '流式输出' },
      isToolParam: false
    }
  }),
  outputSchema: defineOutputSchema({
    summary: {
      type: z.string(),
      title: { en: 'Summary', 'zh-CN': '总结结果' }
    }
  }),
  handler: async (input, ctx) => {
    const ai = ctx.invoke.createModelClient();

    if (input.stream) {
      const stream = await ai.chat.completions.create({
        model: input.model,
        messages: [
          { role: 'system', content: 'Summarize the user text concisely.' },
          { role: 'user', content: input.content }
        ],
        stream: true
      });

      let summary = '';
      for await (const chunk of stream) {
        const delta = chunk.choices[0]?.delta?.content ?? '';
        if (delta) {
          summary += delta;
          ctx.streamResponse({ type: 'answer', content: delta });
        }
      }
      return { summary };
    }

    const completion = await ai.chat.completions.create({
      model: input.model,
      messages: [
        { role: 'system', content: 'Summarize the user text concisely.' },
        { role: 'user', content: input.content }
      ]
    });

    return {
      summary: completion.choices[0]?.message?.content ?? ''
    };
  }
});

export default defineTool({
  manifest: {
    pluginId: 'text-summarizer',
    version: '1.0.0',
    name: { en: 'Text Summarizer', 'zh-CN': '文本总结器' },
    description: {
      en: 'Summarize input text with a FastGPT model',
      'zh-CN': '使用 FastGPT 平台模型总结输入文本'
    },
    permission: ['model:invoke']
  },
  handler
});
```

关键说明：

* **权限声明**：必须在 `manifest.permission` 中声明 `'model:invoke'`，否则在插件宿主与 FastGPT 服务端均会被拦截。
* **模型选择与权限校验**：使用 `Model` 定义的字段会在工作流与 Agent 配置界面渲染为模型下拉框。FastGPT 服务端先从当前团队模型目录校验该 `modelId` 存在且已启用（平台启用的系统模型与归属当前团队的团队模型均可解析，仅团队模型校验团队归属）：若命中当前工作流发布资源快照的预授权集合，则直接沿用发布者授权；未命中时，按当前运行成员校验模型 `use` 权限，并对所有调用统一执行团队 AI 积分余额检查。
* **透明计费**：反向模型调用消耗的 Token 与积分由 FastGPT 服务端按平台计费规则实时记入当前对话/工作流账单（独立明细条目，标注调用工具与模型）；无 `usageId` 且非调试来源时自动创建独立插件账单，无 `usageId` 的纯调试调用不产生账单。插件代码无需也不能访问 `usageId` 或处理扣费逻辑。

## 7. 调试、打包与发布流程

工具开发完成后，统一在[调试、打包与发布](https://doc.fastgpt.cn/plugin/debugging-and-publishing)中完成生命周期交付：

1. **本地调试**：使用 `pnpx @fastgpt-plugin/cli debug . --run` 校验 Schema、默认值与边界输入，详见[本地调试](https://doc.fastgpt.cn/plugin/debugging-and-publishing#本地调试)。
2. **远程联调**：获取 FastGPT 测试环境的调试链接，使用 `pnpx @fastgpt-plugin/cli dev` 接入调试通道，详见[远程调试](https://doc.fastgpt.cn/plugin/debugging-and-publishing#远程调试)。
3. **构建打包**：运行 `pnpm run build`、`cli check` 和 `pnpm run pack` 生成 `.pkg` 产物，详见[构建检查和打包](https://doc.fastgpt.cn/plugin/debugging-and-publishing#构建检查和打包)。
4. **提交前验证**：对照涵盖输入输出、错误处理和真实调用的[验证清单](https://doc.fastgpt.cn/plugin/debugging-and-publishing#验证清单)逐项检查。
5. **发布渠道**：选择社区插件（PR 提交至 community 仓库）、官方插件或私有商业交付，详见[发布流程](https://doc.fastgpt.cn/plugin/debugging-and-publishing#发布流程)。

## 架构选型与版本规范

### `tool` 和 `tool-suite` 如何选择？

单一能力使用 `tool`。多个共享鉴权、共享上游 API、业务上强相关的能力使用 `tool-suite`，例如搜索、详情、创建任务放在同一个插件中。

### 插件版本如何管理？

`manifest.version` 使用语义化版本。修复兼容性问题升级 patch，新增兼容功能升级 minor，修改输入输出字段、子工具 ID 或用户配置方式时升级 major，并提前评估已有工作流兼容性。

### 可以把 API Key 写在代码或环境变量里吗？

插件应通过 `secretSchema` 声明密钥，并通过 `ctx.secrets` 读取。代码仓库、测试快照、错误日志和 README 中都不应出现真实密钥。

### 本地 debug 通过后还需要测试环境验证吗？

需要。本地 debug 用于快速验证插件逻辑和 schema，测试环境验证用于确认真实安装、运行时、宿主反向调用、网络和权限行为。

## 参考

* [FastGPT Plugin 仓库](https://github.com/labring/fastgpt-plugin)
* [系统插件开发指南](https://github.com/labring/fastgpt-plugin/blob/main/docs/dev/how-to-devlop-plugin.md)
* [SDK Factory 使用指南](https://github.com/labring/fastgpt-plugin/blob/main/sdk/factory/README.md)
* [CLI 使用指南](https://github.com/labring/fastgpt-plugin/blob/main/apps/cli/README.md)
