@heningyuan/vscode-mcp 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,438 @@
1
+ ---
2
+ sidebar_position: 4
3
+ ---
4
+
5
+ # Function Workbench SDK 使用指南
6
+
7
+ 本页描述 **VSCode Function Workbench 当前实际提供的 SDK**。它运行在受限的 Node / QuickJS Runtime 中,函数代码只产生本体事务;最终由 Action Executor 把事务提交到 Fabric。
8
+
9
+ > 本页中的集合读取方法是 `fetch()`。通用应用 SDK 文档中出现的 `fetchPage()` 属于另一层通用 Transport API,不应直接用于当前 Function Workbench 脚本。
10
+
11
+ ## 1. 固定入口与执行边界
12
+
13
+ 工作区预置 `client.ts` 和 `utils.ts`。业务函数只能从 `./client` 导入
14
+ `client`、`clientReady`,不要修改或提交 `client.ts`:运行时会根据当前页面的
15
+ location 注入连接配置。
16
+
17
+ ```ts
18
+ // utils.ts:新建对象时生成主键。
19
+ export function randomUUID(): string {
20
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (character) => {
21
+ const value = Math.floor(Math.random() * 16);
22
+ return (character === "x" ? value : (value & 0x3) | 0x8).toString(16);
23
+ });
24
+ }
25
+ ```
26
+
27
+ 业务文件只导出一个 default async 函数。Runtime 编译所有工作区文件后执行这个 default 函数:
28
+
29
+ ```ts
30
+ import { client, clientReady } from "./client";
31
+ import { randomUUID } from "./utils";
32
+
33
+ export default async function executeAction(): Promise<OntologyTransaction> {
34
+ await clientReady;
35
+
36
+ const transaction = client.beginTransaction();
37
+ const product = client.objects.产品信息.create(randomUUID(), { 产品号: "P00001" });
38
+ product.set("项目名称", "新的项目名称");
39
+ transaction.add(product);
40
+ return transaction;
41
+ }
42
+ ```
43
+
44
+ 规则:
45
+
46
+ - 必须在首次读写前 `await clientReady`;连接和鉴权由预置 `client.ts` 完成。
47
+ - `beginTransaction()`、`set()`、`links.xxx.add()` 等只记录本地操作,不会直接写 Fabric。
48
+ - Function 必须 `return transaction`;不能调用 `transaction.commit()`,真正提交由调用 Runtime 的执行器完成。
49
+ - `client.objects` 下的对象名、属性名和关系名来自已选择的 Capability 的 **API code**,不是 UI 显示名称。中文 API code 合法,例如 `client.objects.产品信息`。
50
+
51
+ ## 2. 对象与集合的返回形态
52
+
53
+ SDK 统一把读取结果包装为实例,而不是直接暴露后端 DTO。
54
+
55
+ ### 2.1 导入资源生成的定义
56
+
57
+ 在“资源导入”中选择本体后,工作台会为每个对象生成只读定义文件:
58
+
59
+ ```text
60
+ types/ontology-<对象 API code>.generated.d.ts
61
+ ```
62
+
63
+ 同时,`ontology.generated.d.ts` 作为只读索引展示已导入的对象。运行时会将这些定义合并到编辑器和函数执行环境中,因此业务代码直接使用生成的对象 API、属性、LoadedInstance 类型和 Links accessor;**不要手写、复制或修改生成文件**。
64
+
65
+ 例如导入了 `Documents` 和 `Tags` 后,应以生成定义为准:
66
+
67
+ ```ts
68
+ // Documents、DocumentsLoadedInstance、relatedTags 都来自导入资源生成的定义。
69
+ const documents: DocumentsLoadedInstance[] = [];
70
+ const tags: TagsLoadedInstance[] = [];
71
+
72
+ documents.forEach((document) => {
73
+ tags.forEach((tag) => document.links.relatedTags.add(tag));
74
+ });
75
+ ```
76
+
77
+ 导入资源发生变化时,重新生成的定义会覆盖旧的 `types/ontology-*.generated.d.ts`。函数参数和代码补全应随新定义调整;`client.ts`、`ontology.generated.d.ts` 和生成的对象定义都不应纳入代码提交。
78
+
79
+ ### 2.2 数据源与 MetaHub 工具集
80
+
81
+ 资源导入也会为数据源和 MetaHub 工具集生成只读类型定义。它们均为全局声明,不需要、也不能从 `types` 目录手动导入:
82
+
83
+ ```ts
84
+ // 数据源:名称和表名以生成类型为准;行是普通对象。
85
+ const customers = await client.dataSource.销售数据库.customers.query({
86
+ page: 1,
87
+ pageSize: 20, // 服务端上限为 200
88
+ where: { status: "active" },
89
+ orderBy: { createdAt: "desc" },
90
+ });
91
+ for (const customer of customers.data) {
92
+ console.log(customer.id, customer.name);
93
+ }
94
+
95
+ // MetaHub:入参和返回字段以生成类型为准。
96
+ const result = await client.metahub.Office工具.office转pdf格式({
97
+ document_name: document.properties.name,
98
+ source_document_url: document.properties.url,
99
+ });
100
+ document.set("preview_url", result.pdf_document_url);
101
+ transaction.add(document);
102
+ ```
103
+
104
+ - 数据源调用固定为 `client.dataSource.<数据源名>.<表名>.query(...)`,返回 `{ data, total? }`;其中每一行是普通类型化对象,读取 `row.field`,**不是** `row.properties.field`。
105
+ - MetaHub 调用固定为 `client.metahub.<工具集名>.<工具名>(input)`;不得直接调用 Fabric HTTP 接口、不得使用资源 ID 或旧的 `_192168...` 键,也不要用宽泛的类型断言猜测返回字段。
106
+ - 本体实例则相反:属性必须从 `instance.properties.<属性 API code>` 读取。例如 `document.properties.name`,不能写成 `document.name`、`document.url` 或 `document.data.name`。写入使用 `instance.set("属性 API code", value)`,然后 `transaction.add(instance)`。
107
+
108
+ | 入口 | 返回值 | 是否发起读取 |
109
+ | ----------------------------------------------- | ------------ | --------------------------- |
110
+ | `client.objects.产品信息.get("P00001")` | 引用实例 | 否 |
111
+ | `await client.objects.产品信息.fetch("P00001")` | 已加载实例 | 是,按主键读取 |
112
+ | `await client.objects.产品信息.fetch()` | `PageResult` | 是,读取对象集合默认第一页 |
113
+ | `await query.fetch({ pageSize })` | `PageResult` | 是,执行 ObjectSet 查询 |
114
+ | `await relation.fetch({ pageSize })` | `PageResult` | 是,执行关系 / 多跳关系查询 |
115
+ | `create` / `upsert` / `delete` | 引用实例 | 否,仅记录意图 |
116
+
117
+ `PageResult` 的结构为:
118
+
119
+ ```ts
120
+ type PageResult<T> = {
121
+ data: readonly T[];
122
+ nextPageToken?: string;
123
+ totalCount?: number;
124
+ };
125
+ ```
126
+
127
+ 实例的重要字段为:
128
+
129
+ ```ts
130
+ const product = await client.objects.产品信息.fetch("P00001");
131
+
132
+ product.$primaryKey; // "P00001"
133
+ product.$apiName; // Capability 中的对象类型 API code / objectType
134
+ product.properties; // 后端返回的 properties 加上尚未提交的 set() 修改
135
+ product.links; // Capability 中声明的关系
136
+ ```
137
+
138
+ 读取对象属性请使用 `properties`,不要依赖旧的 `data` 字段。后端单对象和 ObjectSet 行都必须返回 `objectType`、`primaryKey` 和 `properties`;完整信封见[后端接口契约](./0821接口)。
139
+
140
+ ## 3. 读取对象
141
+
142
+ ### 3.1 按主键读取
143
+
144
+ `get()` 只构造引用,适合已知主键且不依赖旧值的更新。`fetch(primaryKey)` 才从 Fabric 读取属性与 revision。
145
+
146
+ ```ts
147
+ // 无需读取旧值:直接修改已知对象。
148
+ const product = client.objects.产品信息.get("P00001");
149
+ product.set("项目名称", "新的项目名称");
150
+
151
+ // 需要依据当前状态做判断:先读取。
152
+ const loadedProduct = await client.objects.产品信息.fetch("P00001");
153
+ if (loadedProduct.properties.状态 !== "已归档") {
154
+ loadedProduct.set("状态", "已归档");
155
+ }
156
+ ```
157
+
158
+ ### 3.2 读取对象集合
159
+
160
+ `fetch()` 不传主键时,读取该对象类型的第一页:
161
+
162
+ ```ts
163
+ const page = await client.objects.产品信息.fetch();
164
+
165
+ for (const product of page.data) {
166
+ console.log(product.$primaryKey, product.properties.产品号);
167
+ }
168
+ ```
169
+
170
+ > 当前 Runtime 的对象 API 上,`fetch()` 无参数表示读取默认第一页;`fetch("P00001")` 表示按主键读取。要为对象集合指定分页参数,请先调用 `where({})` 或 `orderBy()`。
171
+
172
+ 筛选与排序返回新的惰性查询,只有最终 `fetch()` 才发请求:
173
+
174
+ ```ts
175
+ const page = await client.objects.产品信息
176
+ .where({ 产品号: { $isNotNull: true } })
177
+ .orderBy({ 产品号: "asc" })
178
+ .fetch({ pageSize: 50 });
179
+ ```
180
+
181
+ 支持的常用筛选操作符包括:`$eq`、`$ne`、`$gt`、`$gte`、`$lt`、`$lte`、`$in`、`$notIn`、`$isNull`、`$isNotNull`、`$contains`。对象属性、排序字段和操作符最终仍由 Fabric 根据 Capability 校验。
182
+
183
+ 分页令牌是服务端产生的、不透明的游标:
184
+
185
+ ```ts
186
+ const query = client.objects.产品信息.where({});
187
+ const first = await query.fetch({ pageSize: 50 });
188
+ const second = first.nextPageToken
189
+ ? await query.fetch({ pageSize: 50, pageToken: first.nextPageToken })
190
+ : undefined;
191
+ ```
192
+
193
+ 不要解析、拼接或自行生成 `pageToken`。需要遍历全部页时使用 `asyncIter()`:
194
+
195
+ ```ts
196
+ for await (const product of client.objects.产品信息
197
+ .where({ 产品号: { $isNotNull: true } })
198
+ .asyncIter({ pageSize: 100 })) {
199
+ console.log(product.properties.产品号);
200
+ }
201
+ ```
202
+
203
+ ## 4. 关系导航与多跳查询
204
+
205
+ 关系不是预先放入 `properties` 的嵌套数组;通过 `.links.<relationApiCode>` 构造 ObjectSet。它可以从对象类型集合或一个具体实例开始,也可以一直向下链式导航。
206
+
207
+ ### 4.1 从对象类型开始
208
+
209
+ ```ts
210
+ const result = await client.objects.产品信息.links.输入资料_产品信息.fetch({ pageSize: 20 });
211
+
212
+ const outlineResult =
213
+ await client.objects.产品信息.links.输入资料_产品信息.links.输入资料_锥形弹簧型式试验大纲.fetch({
214
+ pageSize: 20,
215
+ });
216
+ ```
217
+
218
+ 这表示“从所有产品信息出发”,沿关系得到最终对象集合。中间层不会被自动加载到内存。
219
+
220
+ ### 4.2 从一个对象开始
221
+
222
+ ```ts
223
+ const chunks = await client.objects.文档.get("1").links.分片_文档.fetch({ pageSize: 5 });
224
+ ```
225
+
226
+ `get()` 返回的引用也可导航 links;只有读取 `properties` 时才必须使用 `fetch(primaryKey)`。
227
+
228
+ ### 4.3 多跳、筛选与最终排序
229
+
230
+ ```ts
231
+ const result = await client.objects.Ontology085c63cf26c8486ba4c757356f1ad2f4.get("1")
232
+ .links.bbbToaaa.links.cccTobbb.links.dddToccc.links.eeeToddd.where({ 状态: "启用" })
233
+ .orderBy({ 创建时间: "desc" })
234
+ .fetch({ pageSize: 5 });
235
+ ```
236
+
237
+ 每一次 `.links.<relation>` 都是一次 traversal。`where()` 作用于当前这一跳得到的对象;`orderBy()` 只对最终 `fetch()` 的结果排序。若排序后继续 `.links`,前一层排序不会传到下一跳。
238
+
239
+ Runtime 会把这些调用转换为 `POST /fabric/ontology/object-sets/search`。关系目标类型 Capability 缺失时不会由 Runtime 本地拦截;请求仍会交给 Fabric 解析,但类型补全、表格显示和后端校验应使用完整 Capability。
240
+
241
+ ## 5. 写入:由调用方传入目标实例
242
+
243
+ 所有写入都先记录在实例上,最后将发生变更的实例加入同一事务。**只有创建可以不传实例;修改、Upsert、删除和 Links 变更必须由调用方传入已选中的实例。** 函数不得根据名称、属性或写死主键自行查找并修改对象,以免误改同名数据。
244
+
245
+ 以下示例的 `Documents`、`DocumentsLoadedInstance` 和 `relatedTags` 均为当前 Capability 生成的 API code;实际函数应替换为类型定义中显示的名称。
246
+
247
+ ### 5.1 创建
248
+
249
+ 创建没有既有目标,因此只接收创建所需属性:
250
+
251
+ ```ts
252
+ import { client, clientReady } from "./client";
253
+ import { randomUUID } from "./utils";
254
+
255
+ export default async function executeAction(
256
+ name: string,
257
+ code: string
258
+ ): Promise<OntologyTransaction> {
259
+ await clientReady;
260
+ const tx = client.beginTransaction();
261
+
262
+ const doc = client.objects.Documents.create(randomUUID(), { name, code });
263
+ tx.add(doc);
264
+ return tx;
265
+ }
266
+ ```
267
+
268
+ `create(primaryKey, initialProperties)` 的主键必须唯一,不要把字符串 `"uuid"` 当作固定主键。在 Function Workbench 中,必须按生成属性的名称、类型和必填性逐个声明参数,再组装 `initialProperties`,便于参数表单和函数参数映射。不要用 `data: Documents` 或 `Partial<Documents>` 隐藏全部字段,也不要补全一批空字符串、计数值或状态。若生成类型包含主键属性,显式接收该属性并用同一个值作为 `create` 的主键,不另外制造第二个 `rid`。
269
+
270
+ `Documents` 是导入资源生成的全局类型,不要写 `import type { Documents } from "./types/ontology-Documents.generated"`。
271
+
272
+ ### 5.2 修改
273
+
274
+ 修改目标必须作为函数参数传入。调用方从列表、详情页或文件选择器取得实例后再调用函数;函数内不再 `get()` 或 `fetch()` 另找目标。
275
+
276
+ ```ts
277
+ import { client, clientReady } from "./client";
278
+
279
+ export default async function executeAction(
280
+ name: string,
281
+ code: string,
282
+ documents: DocumentsLoadedInstance[]
283
+ ): Promise<OntologyTransaction> {
284
+ await clientReady;
285
+ const tx = client.beginTransaction();
286
+
287
+ documents.forEach((document) => {
288
+ document.set("name", name);
289
+ document.set("code", code);
290
+ tx.add(document);
291
+ });
292
+
293
+ return tx;
294
+ }
295
+ ```
296
+
297
+ 传入的已加载实例会保留 `$primaryKey`、`$revision` 与 links;因此后端可以对正确对象执行乐观锁校验。
298
+
299
+ ### 5.3 创建或修改(Upsert)
300
+
301
+ Upsert 同样必须由调用方传入目标实例,并以实例的 `$primaryKey` 作为 key。它不会根据 `name` 自动推断要覆盖哪个对象。
302
+
303
+ ```ts
304
+ import { client, clientReady } from "./client";
305
+
306
+ export default async function executeAction(
307
+ name: string,
308
+ code: string,
309
+ documents: DocumentsLoadedInstance[]
310
+ ): Promise<OntologyTransaction> {
311
+ await clientReady;
312
+ const tx = client.beginTransaction();
313
+
314
+ documents.forEach((document) => {
315
+ const doc = client.objects.Documents.upsert(document.$primaryKey, { name, code });
316
+ tx.add(doc);
317
+ });
318
+
319
+ return tx;
320
+ }
321
+ ```
322
+
323
+ 若没有已选实例,请调用创建函数,而不是把空数组当成“自动创建”的信号。`upsert` 的存在时合并语义仍由后端事务接口定义。
324
+
325
+ ### 5.4 删除
326
+
327
+ 删除也只能针对调用方传入的实例:
328
+
329
+ ```ts
330
+ import { client, clientReady } from "./client";
331
+
332
+ export default async function executeAction(
333
+ documents: DocumentsLoadedInstance[]
334
+ ): Promise<OntologyTransaction> {
335
+ await clientReady;
336
+ const tx = client.beginTransaction();
337
+
338
+ documents.forEach((document) => {
339
+ document.delete();
340
+ tx.add(document);
341
+ });
342
+
343
+ return tx;
344
+ }
345
+ ```
346
+
347
+ ### 5.5 Links:新增与移除关系
348
+
349
+ Links 的源对象和目标对象都应由调用方传入。不要在函数中根据显示名称查询链接对象,也不要只传普通属性对象。
350
+
351
+ 关系参数必须使用导入资源生成的 `LoadedInstance` 类型。不要接收 `chunkIds` 后再调用 `get()` / `fetch()`,也不要把关系参数声明为可选。关系 accessor 属于哪一端,必须以生成定义为准。
352
+
353
+ ```ts
354
+ import { client, clientReady } from "./client";
355
+
356
+ // 为选中的文档添加选中的标签。
357
+ export default async function executeAction(
358
+ documents: DocumentsLoadedInstance[],
359
+ tags: TagsLoadedInstance[]
360
+ ): Promise<OntologyTransaction> {
361
+ await clientReady;
362
+ const tx = client.beginTransaction();
363
+
364
+ documents.forEach((document) => {
365
+ tags.forEach((tag) => document.links.relatedTags.add(tag));
366
+ tx.add(document);
367
+ });
368
+
369
+ return tx;
370
+ }
371
+ ```
372
+
373
+ 移除关系仅将 `add` 改为 `remove`,参数保持为调用方传入的目标实例:
374
+
375
+ ```ts
376
+ documents.forEach((document) => {
377
+ tags.forEach((tag) => document.links.relatedTags.remove(tag));
378
+ tx.add(document);
379
+ });
380
+ ```
381
+
382
+ `add()` / `remove()` 接受主键或本体实例;在函数工作台中优先传入实例,确保关系变更与用户选择的对象完全一致。若项目仅有目标主键,可传主键字符串。Function Workbench 不提供 `changeRelation()`,关系只能通过 `links.<relationApiCode>.add/remove` 记录。
383
+
384
+ ## 7. 完整示例
385
+
386
+ 下面示例查询一个文档的五层关联,创建产品与输入资料,并在一个事务中建立关系:
387
+
388
+ ```ts
389
+ import { client, clientReady } from "./client";
390
+ import { randomUUID } from "./utils";
391
+
392
+ export default async function executeAction(): Promise<OntologyTransaction> {
393
+ await clientReady;
394
+
395
+ const transaction = client.beginTransaction();
396
+
397
+ const terminalPage = await client.objects.Ontology085c63cf26c8486ba4c757356f1ad2f4.get(
398
+ "1"
399
+ ).links.bbbToaaa.links.cccTobbb.links.dddToccc.links.eeeToddd.fetch({ pageSize: 5 });
400
+ console.log("末端关联数量", terminalPage.data.length);
401
+
402
+ const product = client.objects.产品信息.create(randomUUID(), { 产品号: "P00001" });
403
+ product.set("项目名称", "锥形弹簧");
404
+ product.set("物料编码", "MAT-001");
405
+
406
+ const file = client.objects.输入资料.create(randomUUID(), { 名称: "试验大纲" });
407
+ product.links.输入资料_产品信息.add(file);
408
+
409
+ transaction.add(file);
410
+ transaction.add(product);
411
+ return transaction;
412
+ }
413
+ ```
414
+
415
+ 执行成功后的 Runtime 返回 `ontology-apply/v1` DSL,而不是直接保存结果。完整 DSL 和 `POST /fabric/ontology/transactions/apply` 的后端契约见[后端接口契约](./0821接口#6-关系变更与事务提交)。
416
+
417
+ ## 8. 常见问题
418
+
419
+ ### 为什么 `schemaVersion` 是 `unknown` 或缺失?
420
+
421
+ 事务 Schema Version 来自当前选中对象的 Capability。对象 Capability 未刷新、Capability 没有返回 `schemaVersion`,或对象 API code 没有正确映射到 objectType 时,运行时无法为该 ChangeSet 附加版本。刷新并重新选择 Capability 后再构建/执行;后端也应拒绝无版本的写事务,而不是猜测版本。
422
+
423
+ ### 为什么 `get()` 后拿不到属性?
424
+
425
+ `get()` 是引用,不做网络读取;它用于 `set()`、关系导航和构造事务。读取属性请使用:
426
+
427
+ ```ts
428
+ const product = await client.objects.产品信息.fetch("P00001");
429
+ console.log(product.properties.项目名称);
430
+ ```
431
+
432
+ ### 为什么 `tx.add(instance)` 没有变更?
433
+
434
+ `tx.add()` 只会收集该实例已经记录的写操作。先调用 `set()`、`create()`、`upsert()`、`delete()`、`links.xxx.add()` 或 `links.xxx.remove()`,再 `tx.add(instance)`。
435
+
436
+ ### 为什么不能在 Function 内 `commit()`?
437
+
438
+ Function Runtime 的职责是安全执行代码并返回 DSL;提交者必须统一处理调用权限、审计、幂等、schema/revision 校验和原子性。因此 Function 只能 `return transaction`。
@@ -0,0 +1,190 @@
1
+ ---
2
+ name: ontology-function-workbench
3
+ description: Create or edit VSCode Function Workbench ontology functions that return transactions, including object writes and Links mutations.
4
+ ---
5
+
6
+ # Ontology Function Workbench
7
+
8
+ Use this skill when generating or editing a function in the VSCode Function Workbench. The output is a TypeScript default async function that returns an `OntologyTransaction`; it does not commit the transaction itself.
9
+
10
+ ## Runtime contract
11
+
12
+ - Import `client` and `clientReady` only from `./client`; do not edit, replace, or generate `client.ts`. Its connection configuration comes from the current page location.
13
+ - Call `await clientReady`, then `const tx = client.beginTransaction()`, add every changed instance with `tx.add(...)`, and `return tx`.
14
+ - Use the selected Capability's generated API code and types exactly as supplied by `ontology.generated.d.ts`.
15
+ - Do not edit `ontology.generated.d.ts` or `__generated_user__.d.ts`.
16
+
17
+ ## Imported resources
18
+
19
+ The resource-import panel generates one read-only definition per imported ontology under the `types` directory; `ontology.generated.d.ts` is the read-only index. AIP receives a machine-readable resource manifest in `codeEditor.ontologyResources` and the merged declarations in `codeEditor.ontologyTypes`.
20
+
21
+ - Use `ontologyResources` first for exact object API codes, fields, generated data/`LoadedInstance` types, relation owners and targets. Use `externalResources` to see the imported data-source keys, table keys, MetaHub collection keys and tool keys. Use `ontologyTypes` for the complete TypeScript signatures for all three resource kinds.
22
+ - Treat these contexts as the source of truth. Do not invent API codes from display labels or create any import statement for these global declarations. This also applies to `client.dataSource` and `client.metahub`; never import a generated declaration from `./types`.
23
+ - Do not edit generated definitions. When the user changes imported resources, use the newly generated definitions and adjust only business function files.
24
+
25
+ ### Loaded instance properties
26
+
27
+ An ontology `LoadedInstance` is an instance wrapper, not a flattened backend row. Business properties are **only** under `instance.properties`; its direct members are runtime metadata such as `$primaryKey`, `$apiName`, `$revision` and `links`.
28
+
29
+ ```ts
30
+ // Correct: use the exact generated property API code.
31
+ const documentName = document.properties.name;
32
+ const sourceDocumentUrl = document.properties.url;
33
+
34
+ // Wrong: never generate document.name, document.url or document.data.name.
35
+ document.set("preview_url", pdfUrl);
36
+ ```
37
+
38
+ Use bracket notation when the generated property API code is not a valid TypeScript identifier. Never guess a property name: read it from `ontologyResources` / `ontologyTypes`.
39
+
40
+ ### Data sources and MetaHub
41
+
42
+ External resources are global generated client APIs. Their collection, table and tool names must be copied exactly from `ontologyTypes` (and can be cross-checked in `externalResources`); they are not IP addresses, resource IDs, or display-name guesses.
43
+
44
+ ```ts
45
+ // Data-source rows are ordinary typed rows, not ontology instances.
46
+ const customers = await client.dataSource.销售数据库.customers.query({
47
+ page: 1,
48
+ pageSize: 20, // Keep pageSize at or below 200.
49
+ where: { status: "active" },
50
+ orderBy: { createdAt: "desc" },
51
+ });
52
+ for (const customer of customers.data) {
53
+ console.log(customer.id, customer.name); // No `.properties` on data-source rows.
54
+ }
55
+
56
+ // MetaHub input and output are generated from the selected tool schema.
57
+ const pdfResult = await client.metahub.Office工具.office转pdf格式({
58
+ document_name: document.properties.name,
59
+ source_document_url: document.properties.url,
60
+ });
61
+ document.set("preview_url", pdfResult.pdf_document_url);
62
+ tx.add(document);
63
+ ```
64
+
65
+ Do not call Fabric endpoints directly, do not use legacy generated keys such as `_192168...`, and do not hide an unknown MetaHub response behind `as { pdf_url?: string; url?: string }`. Use the exact generated input field and output field names. A MetaHub call does not itself produce an ontology transaction; add the changed ontology instance to `tx` after applying `set()`.
66
+
67
+ ## Target-selection rule
68
+
69
+ Creation is the only write operation that may omit an instance argument. For update, upsert, deletion, and every Links change, require the caller to pass the selected loaded instances. Never find a target inside the function by display name, an arbitrary property, or a hard-coded primary key.
70
+
71
+ Every transaction function returns `Promise<OntologyTransaction>` and ends with `return tx`; never use `Promise<void>`. For creation, expand every generated object property into an explicit parameter with its generated type and requiredness, then assemble the object passed to `create`. Do not accept `data: Documents` or any other generated object as a black-box data parameter. Do not use `Partial`, assign a second `rid`, or make up empty strings, counters, statuses, or other default values.
72
+
73
+ Use `DocumentsLoadedInstance[]` below as a placeholder for the generated loaded-instance type of the actual object.
74
+
75
+ ```ts
76
+ // Create: each generated property is a caller-supplied parameter.
77
+ export default async function executeAction(
78
+ primaryKey: string,
79
+ name?: string,
80
+ category?: string
81
+ ): Promise<OntologyTransaction> {
82
+ await clientReady;
83
+ const tx = client.beginTransaction();
84
+ const doc = client.objects.Documents.create(primaryKey, { name, category });
85
+ tx.add(doc);
86
+ return tx;
87
+ }
88
+
89
+ // Update: the caller passes the selected instances.
90
+ documents.forEach((document: DocumentsLoadedInstance) => {
91
+ document.set("name", name);
92
+ document.set("code", code);
93
+ tx.add(document);
94
+ });
95
+
96
+ // Upsert: use the caller-provided instance key; do not infer a target by name.
97
+ documents.forEach((document: DocumentsLoadedInstance) => {
98
+ const doc = client.objects.Documents.upsert(document.$primaryKey, { name, code });
99
+ tx.add(doc);
100
+ });
101
+
102
+ // Delete: delete the caller-provided instance.
103
+ documents.forEach((document: DocumentsLoadedInstance) => {
104
+ document.delete();
105
+ tx.add(document);
106
+ });
107
+ ```
108
+
109
+ ## Links
110
+
111
+ For a relationship mutation, require both the selected source and target instances. Function Workbench has no `changeRelation` API: use only the generated typed relation accessor.
112
+
113
+ Relation parameters are always required generated loaded instances. Never accept identifiers such as `chunkIds`, never call `get()` or `fetch()` to turn IDs into relation targets, and never make a relation parameter optional. Read the generated definitions to determine which instance owns the relation accessor.
114
+
115
+ ```ts
116
+ documents.forEach((document: DocumentsLoadedInstance) => {
117
+ tags.forEach((tag: TagsLoadedInstance) => document.links.relatedTags.add(tag));
118
+ tx.add(document);
119
+ });
120
+
121
+ // Removing a link has the same parameter rule.
122
+ documents.forEach((document: DocumentsLoadedInstance) => {
123
+ tags.forEach((tag: TagsLoadedInstance) => document.links.relatedTags.remove(tag));
124
+ tx.add(document);
125
+ });
126
+ ```
127
+
128
+ When the target is an array, call the accessor once for each selected instance. Do not spread the array into `add` or `remove`.
129
+
130
+ ```ts
131
+ for (const chunk of chunks) {
132
+ document.links.分片_文档.add(chunk);
133
+ }
134
+ ```
135
+
136
+ If the generated declaration exposes a relation as only `{ fetch(): Promise<unknown> }`, it is not an editable relation accessor. Do not use a type assertion or another API to bypass that error; correct the imported resource's relation target definition, regenerate the declarations, then generate the function.
137
+
138
+ `add` and `remove` also accept a primary-key string at runtime, but generated Function Workbench code must use the caller-provided loaded instance. Never pass a plain property object as a link target. For create-and-link requests, create the new object, apply the accessor on whichever side owns it according to `ontologyResources`, confirm the signature in `ontologyTypes`, and add every changed source instance to the transaction. Do not guess or hard-code a relation direction.
139
+
140
+ ## Delete documents
141
+
142
+ Deletion receives the selected loaded instances. Do not query IDs, cast a reference instance, or synthesize an object before deleting it.
143
+
144
+ ```ts
145
+ export default async function executeAction(
146
+ documents: DocumentsLoadedInstance[]
147
+ ): Promise<OntologyTransaction> {
148
+ await clientReady;
149
+ const tx = client.beginTransaction();
150
+
151
+ documents.forEach((document) => {
152
+ document.delete();
153
+ tx.add(document);
154
+ });
155
+
156
+ return tx;
157
+ }
158
+ ```
159
+
160
+ ## Lifecycle functions and argument mapping
161
+
162
+ Instance lifecycle registration uses `instance.on(trigger, { functionApiCode, args })`.
163
+ `args` keys must exactly match the published target function's parameter names. Do not remove `args` or assume a target function always names its parameter `document` or accepts positional automatic injection.
164
+
165
+ ```ts
166
+ document.on("UPDATED", {
167
+ functionApiCode: "onDocumentUpdated",
168
+ args: {
169
+ document: { $source: "instance" },
170
+ event: { $source: "event" },
171
+ // Alternatively map individual generated properties to target parameters:
172
+ // oldName: { $source: "before", field: "name" },
173
+ // newName: { $source: "after", field: "name" },
174
+ },
175
+ });
176
+ ```
177
+
178
+ Bindings are resolved by the lifecycle dispatcher from the committed event. `instance` is restored as the selected generated LoadedInstance; `event` contains `before`, `after`, and per-field `changes` with `oldValue` and `newValue`. Plain JSON values are fixed literals captured at registration. Do not pass an SDK instance or `instance.properties` as a literal and assume it will refresh when the event fires. Do not implement a JavaScript expression evaluator or interpolate strings in mappings.
179
+
180
+ The SDK and Function Runtime serialize registrations; this repository does not contain the Fabric lifecycle dispatcher. Do not claim a successful build or registration has executed the target function. Check the automation reference for implementation limits. Repeating the same trigger/function binding within a pending instance replaces its argument mapping; durable deduplication, task retries, loop protection and function-deletion dependencies belong to the backend.
181
+
182
+ When editing through MCP, read `vscode_get_context` and its bundled `guidance` first; use `vscode_get_guidance` for the `function-sdk` and `automation` references. MCP applies exact-text edits through `vscode_apply_changes`; the AIP payload below applies only when replying through AIP.
183
+
184
+ ## Code-edit response
185
+
186
+ When replying through AIP, emit the required `ontology-code-actions` payload before prose for every code modification. Keep the edit minimal, preserve unrelated code, and never replace an existing file wholesale. Put the complete operation in the existing default `executeAction`; do not leave it empty and add a second exported function or duplicate generated ontology types with local interfaces.
187
+
188
+ The UI treats model output as untrusted. It first simulates all exact-text edits against the current workspace, then validates the default entry point, transaction lifecycle, generated object and relation names, relation ownership, required `LoadedInstance` parameters, and protected files. Only a valid payload is applied once. The applied edit is reversible through Undo; an invalid payload is shown as not applied with the validation reason.
189
+
190
+ Read the developer-facing reference at `docs/fabric-docs/docs/function-sdk.md` when detailed query, transaction, or relation behavior is needed.
package/package.json CHANGED
@@ -1,6 +1,40 @@
1
1
  {
2
2
  "name": "@heningyuan/vscode-mcp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Control OnChain apps/vscode workbenches from MCP clients through a shared local WebSocket bridge.",
5
+ "license": "UNLICENSED",
6
+ "type": "module",
7
+ "bin": {
8
+ "onchain-vscode-mcp": "cli.mjs"
9
+ },
10
+ "files": [
11
+ "cli.mjs",
12
+ "server.mjs",
13
+ "bridge.mjs",
14
+ "shared-bridge.mjs",
15
+ "guidance.mjs",
16
+ "sync-guides.mjs",
17
+ "guides",
18
+ "README.md"
19
+ ],
20
+ "keywords": ["mcp", "onchain", "vscode", "websocket"],
21
+ "publishConfig": {
22
+ "access": "public",
23
+ "registry": "https://registry.npmjs.org/"
24
+ },
25
+ "engines": {
26
+ "node": ">=20"
27
+ },
28
+ "scripts": {
29
+ "start": "node server.mjs",
30
+ "test": "node --test *.test.mjs",
31
+ "sync:guides": "node sync-guides.mjs",
32
+ "prepack": "npm run sync:guides",
33
+ "prepublishOnly": "npm run sync:guides && npm test"
34
+ },
35
+ "dependencies": {
36
+ "@modelcontextprotocol/sdk": "^1.32.2",
37
+ "ws": "^8.18.3",
38
+ "zod": "4.3.6"
39
+ }
40
+ }