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

+9
View File
@@ -0,0 +1,9 @@
MIT License
Copyright (c) 2026 DesireCore
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+98
View File
@@ -0,0 +1,98 @@
---
{
"name": "tool-mcp-authoring",
"description": "Use when the user needs to build, package or modify a custom Tool, MCP Server or device-protocol integration. Reuse existing execution and approval contracts. Requires actual runtimes, drivers/libraries and authorized devices/services; third-party licenses, deployment and costs depend on the chosen dependencies. Report missing prerequisites.",
"license": "MIT",
"compatibility": "Requires DesireCore 10.0.203 or newer and actually available file/execution/configuration capabilities. Runtimes, third-party drivers/libraries, hardware and hosted services are not bundled by this Skill and require their applicable license, deployment, authorization and costs. Report unavailable prerequisites.",
"version": "1.0.0",
"requiredClientVersion": "10.0.203",
"type": "procedural",
"risk_level": "medium",
"status": "enabled",
"disable-model-invocation": true,
"tags": [
"tools",
"mcp",
"development",
"devices"
],
"metadata": {
"author": "desirecore",
"updated_at": "2026-11-09",
"i18n": {
"default_locale": "en-US",
"source_locale": "zh-CN",
"locales": [
"zh-CN",
"en-US"
],
"zh-CN": {
"name": "自建 Tool 与 MCP",
"short_desc": "编写、登记和验证可复用工具与 MCP 服务",
"description": "在用户需要自主编写、封装或修改自定义 Tool、MCP Server 或设备协议接入能力时使用。复用现有执行与审批合同;依赖真实可用的运行时、驱动/库及获准设备或服务,第三方许可、部署和费用按所选依赖确认,缺条件时报告。",
"body": "./SKILL.zh-CN.md",
"source_hash": "sha256:4a1d9c15821f8571",
"translated_by": "ai:gpt-6",
"translated_at": "2026-11-09"
},
"en-US": {
"name": "Self-authored Tools and MCP",
"short_desc": "Build, register and verify reusable tools and MCP services",
"description": "Use when the user needs to build, package or modify a custom Tool, MCP Server or device-protocol integration. Reuse existing execution and approval contracts. Requires actual runtimes, drivers/libraries and authorized devices/services; third-party licenses, deployment and costs depend on the chosen dependencies. Report missing prerequisites.",
"body": "./SKILL.md",
"source_hash": "sha256:4a1d9c15821f8571",
"translated_by": "ai:gpt-6",
"translated_at": "2026-11-09"
}
}
},
"market": {
"icon": "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"white\" stroke-width=\"1.6\"><rect x=\"3\" y=\"3\" width=\"18\" height=\"18\" rx=\"3\"/><path d=\"M3 8h18M8 8v13M12 13h5M12 17h5\"/></svg>",
"category": "development",
"maintainer": {
"name": "DesireCore Official",
"verified": true
},
"channel": "latest"
}
}
---
# Self-authored Tools and MCP
## Choose the delivery
Implement the requested capability as verifiable code and contracts that remain usable. The Agent chooses language, libraries and approach; the platform supplies original file tools, execution, discovery, approvals and runtime facts without imposing a business workflow.
| User goal | Possible carrier |
|---|---|
| One diagnosis, read or conversion | A script in the authorized workspace |
| Reusable atomic operation with an input schema | An AgentFS custom Tool |
| Operations sharing a device connection or service state | A self-authored MCP Server attached to the actual Agent Service |
| Reusable method, conventions and supporting scripts | A Skill; it does not register a function tool by itself |
| Configuration UI, multiple devices, installable delivery | An application or plugin, optionally composing existing Tool/MCP capabilities |
Check existing capabilities and the user's choice. An explicit request to build can proceed directly without searching the market first. For application delivery, load the application authoring Skill from the actual directory: authoring actions use `AppAuthoring`, installation lifecycle uses `AppManage`.
## Use real environments and original authority
- Continue the current Plan, work directory and authorization. Creating a tool does not justify changing approval mode, extracting a platform token or widening a child task's authority. Another Agent's installation/configuration needs its original authorization.
- Probe actual runtimes, libraries, drivers and devices/services. Prepare missing prerequisites through available runtime Skills or original execution tools, recording versions and location. Third-party libraries, hardware and hosted services retain their license, deployment and cost requirements; report unavailable prerequisites.
- Keep reviewable code/configuration in permitted directories, private device settings and credentials in private configuration or original connection owners, and out of public Skills, CLI arguments, logs and examples. Registering a connector does not provide external hardware, licenses or services.
- Derive serial ports, baud rates, addresses and endpoints from the actual device and protocol material. Provide descriptions in configuration/parameter schemas. Classify read/write risk by actual effects and test authorized read-only operations or simulated endpoints first without calling them physical-device evidence.
## Read the relevant authoring contract
- Atomic scripts, complete TOOL.md, registration and discovery: [AgentFS Tool](references/agentfs-tool.md).
- Local/remote MCP, dependencies, connections and sharing: [MCP service](references/mcp-server.md).
- For reusable operating methods, load Skill authoring/management guidance from the actual directory. For a shared HTTP/MCP catalog, load service-registration guidance. Attaching MCP to yourself needs no global listing.
## Verify results and lifecycle
Report separately: source/dependencies prepared, configuration saved, registration/discovery successful, actual invocation successful, device behavior observed and restart recovery verified. Earlier stages do not establish later ones.
After registry refresh, call actual current catalog/declaration names. Loading does not increase authority; a worker/background Run with a fixed tool ceiling cannot bypass it by creating new capabilities. Use the error and original context to choose a subsequent turn, a suitable execution Agent or a precise authorization requirement instead of blindly loading again.
Continuous subscriptions such as MQTT need a real process/service carrier and an explicit path through an authorized existing schedule, Webhook or other real ingress to the Agent. MCP list-change notifications are not a general device-event wakeup facility. A saved config, one background command or registered MCP does not prove listening survives an application restart. If choosing scheduling, use `ManageSchedule` rather than writing persistent schedule files directly.
Verify relevant device ownership, timeout, cancellation, disconnect/recovery and concurrency for the chosen delivery. Reconcile uncertain device writes before deciding to retry. Close/remove only your owned connections, processes and registrations rather than shared services. Deliver actual entrypoints, call examples and unverified limits without packaging every simple script as an application.
+38
View File
@@ -0,0 +1,38 @@
# 自建 Tool 与 MCP
## 选择交付方式
把用户需要的能力实现成可核验、可继续使用的代码和合同。Agent 选择语言、库及实现方式,平台提供原文件工具、执行、发现、审批与运行事实;不要求固定业务流程。
| 用户目标 | 可选承载 |
|---|---|
| 一次诊断、读取或转换 | 在授权工作目录写脚本并执行 |
| 有输入 Schema 的可复用原子操作 | AgentFS 自定义 Tool |
| 多个操作共享设备连接或服务状态 | 自编 MCP Server,接入实际目标 Agent Service |
| 可复用的方法、约定及配套脚本 | Skill;它本身不会登记函数工具 |
| 配置界面、多设备管理、可安装交付 | 应用或插件,可组合既有 Tool/MCP |
先检查已有能力及用户选择。用户明确要求自建时可直接编写,不必先查市场。涉及应用交付时按目录加载应用作者 Skill,作者动作使用 `AppAuthoring`;安装生命周期使用 `AppManage`。
## 使用真实环境与原授权
- 沿用当前任务的 Plan、工作目录及授权;不因创建工具而改审批模式、获取平台 token 或扩大子任务权限。跨 Agent 安装/改配置需要该目标的原授权。
- 探测实际运行时、库、驱动和设备/服务。依赖不存在时按可用的运行时 Skill 或原执行工具准备,记录版本和安装位置。第三方库、设备、托管服务的许可证、部署条件及费用由所选依赖决定;缺少条件时报告具体不可用项。
- 代码和可审阅配置放在获准目录,设备私有参数与凭据留在私有配置或原连接 owner;不写进公共 Skill、命令行、日志或示例。注册连接器不会提供外部硬件、许可证或服务。
- 串口号、波特率、设备地址、网络端点等由实际设备及协议材料确定;配置与参数 Schema 提供 description。读状态和写设备按真实副作用分别声明风险,测试先使用获准的只读操作或模拟端点,不能冒充真机结果。
## 按需读取作者合同
- 原子脚本工具、完整 TOOL.md、登记与发现:读 [AgentFS 工具](references/agentfs-tool.zh-CN.md)。
- 本地或远端 MCP、依赖、连接和共享:读 [MCP 服务](references/mcp-server.zh-CN.md)。
- 保存操作方法时按目录加载 Skill 作者/管理指南;共享 HTTP/MCP 目录时按目录加载服务登记指南。接入自身 MCP 不要求先登记全局目录。
## 核验结果与生命周期
分别记录:源代码和依赖已准备、配置已保存、注册/发现成功、实际调用成功、设备行为已观测、重启恢复已验证。只完成前一项时不承诺后一项。
刷新注册表后按当前工具目录和实际模型声明调用。加载工具不会扩大权限;固定工具上限的子任务或后台 Run 不能靠新建能力绕过原上限。按错误和原上下文选择下一轮、适当执行 Agent 或报告需要的授权,不盲目重复加载。
长期 MQTT 等订阅要有真实进程/服务载体,并明确事件如何通过获准的原调度、Webhook 或其它实际入口触达 Agent。MCP 列表变化通知不是设备业务事件的通用唤醒器;保存配置、一次后台命令或注册 MCP 都不能证明应用重启后仍在监听。若选择调度,使用 `ManageSchedule`,不直接写持久调度文件。
按所选交付核验端口占用、超时、取消、断连/恢复与必要的并发访问;设备写入结果未知时先核实状态再决定是否重试。关闭或移除能力时只处理本次拥有的连接、进程与注册,不停止共享服务。给出实际入口、调用示例和未验证范围,不要求每个简单脚本都打包成应用。
@@ -0,0 +1,77 @@
{
"$schema": "../../schemas/catalog-metadata.v1.schema.json",
"schemaVersion": 1,
"identity": {
"kind": "skill",
"id": "tool-mcp-authoring"
},
"presentation": {
"defaultLocale": "en-US",
"i18n": {
"zh-CN": {
"name": "自建 Tool 与 MCP",
"summary": "编写、登记和验证可复用工具与 MCP 服务",
"description": "在用户需要自主编写、封装或修改自定义 Tool、MCP Server 或设备协议接入能力时使用。复用现有执行与审批合同;依赖真实可用的运行时、驱动/库及获准设备或服务,第三方许可、部署和费用按所选依赖确认,缺条件时报告。"
},
"en-US": {
"name": "Self-authored Tools and MCP",
"summary": "Build, register and verify reusable tools and MCP services",
"description": "Use when the user needs to build, package or modify a custom Tool, MCP Server or device-protocol integration. Reuse existing execution and approval contracts. Requires actual runtimes, drivers/libraries and authorized devices/services; third-party licenses, deployment and costs depend on the chosen dependencies. Report missing prerequisites."
}
},
"category": "development",
"tags": [
"tools",
"mcp",
"development",
"devices"
]
},
"release": {
"state": "known",
"version": "1.0.0",
"versionScheme": "semver"
},
"timestamps": {
"catalogUpdatedAt": {
"state": "known",
"value": "2026-11-09",
"precision": "day"
},
"releasePublishedAt": {
"state": "unknown"
},
"reviewedAt": {
"state": "unknown"
},
"upstreamObservedAt": {
"state": "unknown"
}
},
"provenance": {},
"governance": {
"stewardship": "official",
"availability": "installable",
"license": {
"state": "known",
"value": "MIT",
"evidencePath": "LICENSE"
},
"redistribution": "verify-package-terms",
"listingMaintainer": {
"name": "DesireCore Official",
"verified": true
}
},
"compatibility": {
"platforms": {
"state": "unknown"
},
"requiredClientVersion": "10.0.203"
},
"spec": {
"kind": "skill",
"riskLevel": "medium",
"skillType": "procedural"
}
}
@@ -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 关闭本次拥有的资源,保留用户数据,不结束共享进程。