feat: 支持智能体自主编写 Tool/MCP / Guide self-authored Tools and MCP (#272)

用户要求自建可复用工具或设备协议接入时,现有指南缺少从代码到工具登记与调用的完整路径。新增双语 tool-mcp-authoring
Skill,提供 AgentFS Tool 和 MCP 作者合同、依赖/权限及生命周期验证;同步内置清单和目录元数据。修正
app-developer 的正文、参考和示例,作者动作统一使用 AppAuthoring,安装生命周期保留 AppManage。

When users request reusable tools or device integrations, the existing
guidance does not explain the complete
code-to-registration-to-invocation path. Add bilingual Tool/MCP
authoring guidance and references, and update builtin/catalog metadata.
Migrate app-developer authoring instructions and examples to
AppAuthoring while keeping installation lifecycle on AppManage.

验证 / Validation: market i18n and complete catalog validation pass (0
errors; existing governance warnings retained); all translation
freshness checks pass. Both localized script examples pass the real Tool
frontmatter Schema, execute valid input and reject invalid input.
Full-tree credential-pattern and customer-neutrality checks pass. No
hardware operation, model decision or full application release is
claimed.
This commit is contained in:
yige authored and GitHub committed 2026-11-09 17:11:25 +08:00
1 parent 2a6a814a0f
commit da94f5361b
18 files changed
+474 -51

No files matched your search

@@ -0,0 +1,61 @@
# AgentFS script Tool contract
Use for bounded, independently callable operations. The current client's `toolFrontmatterSchema` and `scriptExecutionConfigSchema` are authoritative (`packages/schemas/src/agent/tool-frontmatter.ts` in the main repository). This example is not a replacement for the actual contract.
## Files and parameters
Place `TOOL.md` and the entry file under the actual AgentFS root's `agents/<own-id>/tools/<tool-id>/`, within current file authority. Each invocation runs in that tool directory; this does not create a filesystem sandbox. The following harmless teaching example is not an installed tool.
`TOOL.md` has YAML frontmatter; JSON is valid YAML:
```markdown
---
{
"name": "ExampleEcho",
"description": "Return the supplied text without accessing devices.",
"risk_level": "low",
"executor": "script",
"status": "enabled",
"command": "run.cjs",
"script": { "runtime": "node", "timeout": 5000 },
"input_schema": {
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"required": ["message"],
"additionalProperties": false,
"properties": { "message": { "type": "string", "description": "Text to return." } }
}
}
---
Return the actual input to verify the tool call chain.
```
Adjacent `run.cjs`:
```javascript
let input = ''
process.stdin.setEncoding('utf8')
process.stdin.on('data', chunk => { input += chunk })
process.stdin.on('end', () => {
try {
const { message } = JSON.parse(input)
if (typeof message !== 'string') throw new Error('message must be a string')
process.stdout.write(JSON.stringify({ success: true, content: message }))
} catch (error) {
process.stderr.write(String(error))
process.exitCode = 1
}
})
```
`script.runtime: node` uses only an already discovered managed Node, with command identifying a static entry inside the tool directory. A missing runtime fails explicitly without download or PATH fallback; establish actual managed Node availability first. For another runtime, omit runtime, set command to its real executable and pass the script path/options separately in `script.args`. Execution does not use a shell; do not place a shell program or variable user command in command.
Parameters arrive as stdin JSON; stdout carries results and stderr diagnostics. JSON success cannot override a nonzero exit code. Install dependencies where this entry can actually resolve them and retain locked versions; do not assume access to a development workspace's node_modules or virtual environment. The default timeout is 30000 milliseconds, at most 600000. A new process per call is not a persistent device connection.
## Save, refresh and call
Use the original Write/Edit tools to author complete material, then `RefreshAgentFS(changeTypes=["tool"])` to refresh your own registry and inspect failure diagnostics. Alternatively, when the current local API contract permits it, `POST /api/agents/<own-id>/tools` creates only a skeleton with name, description, executor, risk_level and body. Complete command/script/input_schema still require the full TOOL.md or `PUT /api/agents/<own-id>/tools/<tool-id>` with `{content: "complete TOOL.md"}`. Mediated, remote or unavailable management access does not justify finding a platform token.
Inspect purpose and current visibility through `ToolCatalog`. If an exact known name is undeclared, use `LoadTools(names=["actual tool name"])` (registered identity DiscoverTools); call the actual declaration on the next model request. Refresh does not widen a Run's fixed tool ceiling; changes to an already bound definition may require the next turn or a new session. For a missing name, inspect refresh diagnostics, enabled state, permissions and Run ceiling instead of inventing a result.
Actually invoke a harmless input, inspect output and invalid parameters plus relevant failure/timeout cases, then validate business operations on authorized hardware. Rediscover and call after restart. Tools belong to their Agent by default; copying/installing for another Agent follows that target's original authorization and is not global publication.
@@ -0,0 +1,61 @@
# AgentFS 脚本 Tool 合同
适用于有限时长、可独立调用的操作。权威字段为当前客户端的 `toolFrontmatterSchema` 和 `scriptExecutionConfigSchema`(主仓 `packages/schemas/src/agent/tool-frontmatter.ts`),不能以本例替代实际工具合同。
## 文件与参数
在实际 AgentFS 根的 `agents/<自身 id>/tools/<tool-id>/` 保存 `TOOL.md` 和入口文件,读写仍需当前目录权限。每次脚本调用的工作目录为该工具目录;脚本没有因此获得文件系统沙箱。下面是无硬件副作用的教学示例,不是已经安装的工具。
`TOOL.md` 使用 YAML frontmatter;JSON 也是合法 YAML:
```markdown
---
{
"name": "ExampleEcho",
"description": "返回传入的文本;不访问设备。",
"risk_level": "low",
"executor": "script",
"status": "enabled",
"command": "run.cjs",
"script": { "runtime": "node", "timeout": 5000 },
"input_schema": {
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"required": ["message"],
"additionalProperties": false,
"properties": { "message": { "type": "string", "description": "需要返回的文本。" } }
}
}
---
返回实际输入,用于验证工具调用链。
```
同目录 `run.cjs`:
```javascript
let input = ''
process.stdin.setEncoding('utf8')
process.stdin.on('data', chunk => { input += chunk })
process.stdin.on('end', () => {
try {
const { message } = JSON.parse(input)
if (typeof message !== 'string') throw new Error('message must be a string')
process.stdout.write(JSON.stringify({ success: true, content: message }))
} catch (error) {
process.stderr.write(String(error))
process.exitCode = 1
}
})
```
`script.runtime: node` 只使用已发现的受管 Node,command 必须是工具目录内静态入口;缺运行时会明确失败,不下载也不回退 PATH。先确认真实受管 Node 可用。选择其它运行时则省略 runtime,command 为实际可执行文件,脚本路径与选项用 `script.args` 独立传递。它们不经过 shell;不要把一段 shell 程序或可变用户命令塞进 command。
参数通过 stdin JSON 传入;stdout 返回结果,诊断写 stderr。返回 JSON 的 success 不能覆盖非零退出码。依赖应安装在真实可解析的位置并记录锁定版本,不假设工具目录能读取开发工作区的 node_modules/虚拟环境。默认 timeout 为 30000 毫秒,最大 600000;持久设备连接不要依赖每次启动的脚本进程存活。
## 保存、刷新和调用
可直接用原 Write/Edit 编写完整材料,再调用 `RefreshAgentFS(changeTypes=["tool"])` 刷新自身注册表,检查失败诊断。也可按当前可用的本机 API 合同创建:`POST /api/agents/<自身 id>/tools` 只生成名称、描述、executor、risk_level 和 body 等骨架;完整 command、script、input_schema 仍须通过完整 TOOL.md 或 `PUT /api/agents/<自身 id>/tools/<tool-id>` 的 `{content: "完整 TOOL.md"}` 补齐。受中介约束、远端或不可用的管理入口不能靠找 token 绕过。
用 `ToolCatalog` 检查用途和当前可见性;已知准确名称而未声明时,使用 `LoadTools(names=["实际工具名"])`(注册身份 DiscoverTools),加载后按真实声明发起下一次模型调用。刷新成功不代表当前 Run 固定上限扩大;改动已经绑定的定义可能需下一轮或新会话。名字缺失时核对刷新诊断、启用状态、权限与 Run 上限,不伪造调用结果。
先真实调用无副作用输入,检查输出、非法参数及必要的失败/超时;再在授权设备上验证业务。重启后重新发现并调用。工具默认属于自身 Agent;其他 Agent 的复制/安装和配置沿目标原授权,不因这里创建了目录就全局可用。
@@ -0,0 +1,39 @@
# Self-authored MCP connection contract
Use when operations share connection/state or other MCP clients need the capability. Choose the implementation language and SDK. Implement initialization, listing, parameter schemas and calls against the chosen installed SDK's actual protocol and documentation; never fabricate success receipts.
## Service, dependencies and host
Keep source, dependency manifests/locks and configuration schemas in authorized directories. Use the actual runtime path. A local stdio process writes only MCP protocol to stdout and diagnostics to stderr. Verify startup directory and module resolution rather than assuming Electron bundles your library or platform-specific native driver.
Identify the Agent Service host that accesses the device. A remote server's COM/USB devices are not the browser computer's hardware. External libraries, hardware and hosted services require their actual licenses, deployment and authorization; registering a connection does not provide them. Stop the affected operation and report missing prerequisites.
## Attach to your own Agent
The current McpConnectionRequest/Schema defines the accepted request. Through the current permitted local API path, optionally `POST /api/mcp/test-connection` with `{connection: <connection request>}`, then `POST /api/agents/<own-id>/mcp-servers`, for example:
```json
{
"serverId": "example-device",
"config": {
"transport": "stdio",
"command": "<actual absolute Node executable on the host>",
"args": ["<absolute installed server entry>"],
"cwd": "<absolute authorized service directory>"
}
}
```
Replace angle-bracket placeholders with actual paths before execution. Keep executable/args separate. Use original connection/secret-reference facilities for sensitive values, never platform tokens/passwords in source or CLI arguments. Connection requests and persisted agent.json mcp_servers entries have different shapes: let this endpoint convert, or inspect the actual agent.json Schema before using authorized file tools to edit your own configuration followed by `RefreshAgentFS(changeTypes=["agent"])`. `ManageAgent.update` does not accept mcp_servers; its rejection is not lack of MCP support.
Ordinary embedded local non-governance APIs, remote/standalone and mediated modes have different access rules. Follow current prompts and actual permissions. If mediated or unavailable, use an offered original configuration capability or report the missing entry; do not extract platform credentials, forge Origin or borrow another identity. First connection can actually start a process and remains subject to the original file, execution, request and MCP-call approvals.
For remote connections, use the client's actual transport, endpoint and OAuth/secretRef contract. An ordinary self-authored local server needs no invented external catalog acquisition identity. Catalog-owned services retain their original acquisition/installation contract; do not impersonate provenance or replace someone else's installation.
## Discover, reuse and actually invoke
Inspect connection-test lists/diagnostics; handshake and listing do not prove a device operation succeeded. After saving, obtain the real model-facing tool name through current catalog/declarations, using `LoadTools` when needed. Do not guess it from the remote declaration or a namespace convention. A fixed worker/background tool ceiling does not expand when new MCP is registered; choose subsequent execution within original authorization and session state.
Actually invoke an authorized harmless tool, then validate device behavior and relevant errors, disconnect/recovery and concurrent device ownership. For a shared catalog, load a service-registration Skill from the actual directory. Attaching to yourself needs no global listing. Other Agents require their own authorized configuration; discoverable does not mean installed or authorized.
Persisted configuration and a live business subscription are separate facts. Current connection owners manage MCP connections and stdio processes; this is not an OS startup service. Continuous subscriptions need an explicit process lifecycle and a real ingress to the Agent. After restart, inspect configuration, rediscover and call, and separately verify business reconnection. Remove your own configuration through the original `DELETE /api/agents/<own-id>/mcp-servers/<serverId>` contract when appropriate; close only your owned resources through their runtime owner, retain user data and leave shared processes alone.
@@ -0,0 +1,39 @@
# 自编 MCP 的接入合同
适用于多个操作共享连接/状态,或需要 MCP 客户端复用的能力。服务代码由 Agent 选择语言和 SDK;以所选已安装 SDK 的真实协议和文档实现初始化、工具列表、参数 Schema 与调用,不伪造成功回执。
## 服务、依赖与目标宿主
在获准目录保存服务源、依赖清单/锁文件和配置 Schema。使用真实运行时路径;本地 stdio 程序只向 stdout 写 MCP 协议,日志写 stderr。实际启动目录和模块解析必须经过验证,不能假设 Electron 内置了作者选择的库或平台相关原生驱动。
明确设备连接发生在哪台 Agent Service 宿主。远端服务上的 COM/USB 不是用户浏览器所在电脑的设备。外部库、硬件和托管服务按其许可证、部署和授权条件使用,连接登记不提供这些资源;缺条件时停止受影响操作并报告。
## 接入自身 Agent
实际连接请求由当前客户端的 McpConnectionRequest/Schema 决定。通过当前获准且可用的本机 API 路径,可以先 `POST /api/mcp/test-connection`,正文 `{connection: <连接请求>}`;再 `POST /api/agents/<自身 id>/mcp-servers`,正文例如:
```json
{
"serverId": "example-device",
"config": {
"transport": "stdio",
"command": "<宿主真实 Node 可执行文件绝对路径>",
"args": ["<已安装服务入口的绝对路径>"],
"cwd": "<已授权服务目录的绝对路径>"
}
}
```
尖括号是待替换的真实路径,不可原样执行。路径/args 分开传递;敏感连接值使用原连接或秘密引用能力,不把平台 token、密码写进文件或 CLI 参数。连接请求与持久化 agent.json 的 mcp_servers 结构并非相同对象;使用该接口转换,或核对真实 agent.json Schema 后用获准文件工具编辑自身配置并 `RefreshAgentFS(changeTypes=["agent"])`。`ManageAgent.update` 不接受 mcp_servers,不能把拒绝当作 MCP 不受支持。
普通 embedded 本机非治理 API、remote/standalone 和 mediated 模式的访问方式不同,以当前提示词和实际权限为准。受中介约束或入口不可用时使用已提供的原配置能力,或明确报告缺少入口;不读取平台凭据、伪造 Origin 或使用其它身份绕过。首次连接可能真实启动服务进程,仍沿原文件、执行、请求与 MCP 调用审批。
远端连接使用客户端实际接受的传输、端点和 OAuth/secretRef 合同;无需为普通自编本地 MCP 构造外部目录来源证明。已有目录托管服务则沿其原获取/安装合同,不伪造目录身份或改装别人的安装。
## 发现、复用与实际调用
检查连接测试的工具列表与诊断;它只证明握手和列表发现,不证明设备操作成功。保存后用当前工具目录/声明取得真实模型侧工具名,必要时 `LoadTools`;不按远端声明名或命名空间习惯猜调用名。固定子任务/后台工具上限不会因登记新 MCP 自动扩大;按原授权和会话状态选择后续执行。
真实调用一次获准的无副作用工具,再验证设备操作及必要的异常、断连/恢复和并发占用。共享目录需求可按目录加载服务登记 Skill;只给自身接入不需要全局目录。其它 Agent 要有自己的授权配置,目录可发现不代表已安装或获准执行。
配置持久化和业务监听存活是不同事实。MCP 连接与 stdio 子进程由当前连接 owner 管理,不等于系统启动服务;长期订阅需明确进程生命周期及事件进入 Agent 的真实入口。重启后检查配置、再次发现和真实调用,并单独核验业务重连。卸载自身配置可按原接口 `DELETE /api/agents/<自身 id>/mcp-servers/<serverId>`;同时依原运行 owner 关闭本次拥有的资源,保留用户数据,不结束共享进程。