inistate-mcp 1.0.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.
package/build/tools.js ADDED
@@ -0,0 +1,988 @@
1
+ import { appendFileSync } from "node:fs";
2
+ import { resolve } from "node:path";
3
+ import { z } from "zod";
4
+ import * as api from "./api.js";
5
+ import { clearFlagged, evaluateActivity, getModuleFieldTypes, getPriorFlag, recordFlagged, validateInputShapes, validateInputShapesWith, } from "./activity-guard.js";
6
+ import { designWorkflow, validateDesign, } from "./schema.js";
7
+ // ---------- Logging ----------
8
+ const LOG_PATH = resolve(process.cwd(), "debug.log");
9
+ function log(tool, detail) {
10
+ const ts = new Date().toISOString();
11
+ const line = `[${ts}] ${tool}: ${detail}\n`;
12
+ try {
13
+ appendFileSync(LOG_PATH, line);
14
+ }
15
+ catch { /* ignore */ }
16
+ }
17
+ // ---------- Response helpers ----------
18
+ function ok(data) {
19
+ return {
20
+ content: [{ type: "text", text: JSON.stringify(data) }],
21
+ };
22
+ }
23
+ function err(e) {
24
+ if (e && typeof e === "object" && "structured" in e) {
25
+ return {
26
+ isError: true,
27
+ content: [
28
+ {
29
+ type: "text",
30
+ text: JSON.stringify(e.structured),
31
+ },
32
+ ],
33
+ };
34
+ }
35
+ return {
36
+ isError: true,
37
+ content: [
38
+ { type: "text", text: e instanceof Error ? e.message : String(e) },
39
+ ],
40
+ };
41
+ }
42
+ // ---------- Workspace helper ----------
43
+ /** Apply workspaceId if provided (stateless mode), else rely on env/prior set_workspace. */
44
+ function applyWorkspace(workspaceId) {
45
+ if (workspaceId)
46
+ api.setWorkspaceId(workspaceId);
47
+ }
48
+ const wsParam = z
49
+ .string()
50
+ .optional()
51
+ .describe("Workspace ID. Required in stateless/remote mode. If set via env INISTATE_WORKSPACE_ID or prior set_workspace call, can be omitted.");
52
+ // ---------- Shared module-schema shapes (used by create_module + update_module) ----------
53
+ // `id` is optional on both: ignored on create, used to match items on update (enables renaming).
54
+ // `type` is optional so update can rename without re-sending it; create still requires it server-side.
55
+ const subFieldShape = z.object({
56
+ id: z.string().optional(),
57
+ name: z.string(),
58
+ type: z.string().optional(),
59
+ options: z.array(z.string()).optional(),
60
+ });
61
+ const fieldShape = z.object({
62
+ id: z.string().optional(),
63
+ name: z.string(),
64
+ type: z.string().optional(),
65
+ options: z.array(z.string()).optional(),
66
+ fields: z.array(subFieldShape).optional().describe("Sub-fields for Table type"),
67
+ ai_hint: z.string().optional(),
68
+ });
69
+ const stateShape = z.object({
70
+ id: z.string().optional(),
71
+ name: z.string(),
72
+ color: z.string().optional(),
73
+ initial: z.boolean().optional(),
74
+ ai_hint: z.string().optional(),
75
+ ai_instruction: z.string().optional(),
76
+ });
77
+ const activityFieldRefShape = z.object({
78
+ name: z.string(),
79
+ required: z.boolean().optional(),
80
+ readOnly: z.boolean().optional(),
81
+ options: z.array(z.string()).optional(),
82
+ });
83
+ const activityShape = z.object({
84
+ id: z.string().optional(),
85
+ name: z.string(),
86
+ actor: z.enum(["human", "ai", "hybrid"]).optional(),
87
+ fields: z.array(z.union([z.string(), activityFieldRefShape])).optional(),
88
+ ai_hint: z.string().optional(),
89
+ ai_instruction: z.string().optional(),
90
+ confidence_threshold: z.number().min(0).max(1).optional(),
91
+ });
92
+ const flowShape = z.object({
93
+ from: z.string(),
94
+ to: z.string(),
95
+ activity: z.string(),
96
+ ai_hint: z.string().optional(),
97
+ });
98
+ const moduleSectionsShape = {
99
+ icon: z.string().optional().describe("Emoji identifier"),
100
+ description: z.string().optional(),
101
+ information: z.array(fieldShape).optional().describe("Field definitions. Items matched by id on update enable renaming."),
102
+ states: z.array(stateShape).optional().describe("Workflow states. Omit for record list modules."),
103
+ activities: z.array(activityShape).optional().describe("Custom activities. Omit for record list modules."),
104
+ flows: z.array(flowShape).optional().describe("State transition rules. Omit for record list modules."),
105
+ };
106
+ // ---------- Tool registration ----------
107
+ export function registerTools(server) {
108
+ const configureTools = [];
109
+ // ═══════════════════════════════════════════
110
+ // 1. list_workspaces
111
+ // ═══════════════════════════════════════════
112
+ server.registerTool("list_workspaces", {
113
+ title: "List Workspaces",
114
+ description: "List workspaces the current user has access to. Call set_workspace to select one before any module or entry tools. This is typically the first tool to call in any session.",
115
+ inputSchema: {
116
+ search: z
117
+ .string()
118
+ .optional()
119
+ .describe("Optional name filter (case-insensitive)"),
120
+ },
121
+ annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false, idempotentHint: true },
122
+ }, async ({ search }) => {
123
+ try {
124
+ const query = search ? `?search=${encodeURIComponent(search)}` : "";
125
+ const data = await api.get(`/api/workspace${query}`);
126
+ return ok(data);
127
+ }
128
+ catch (e) {
129
+ return err(e);
130
+ }
131
+ });
132
+ // ═══════════════════════════════════════════
133
+ // 2. set_workspace
134
+ // ═══════════════════════════════════════════
135
+ server.registerTool("set_workspace", {
136
+ title: "Set Active Workspace",
137
+ description: `Set the active workspace for the current session. In stateless/remote mode, prefer passing workspaceId directly to each tool instead.
138
+
139
+ Workflow sequences after workspace is set:
140
+ - Design: design_workflow → validate_design → create_module
141
+ - Execute: list_modules → list_entries → get_form → submit_activity
142
+ - Modify: list_modules → get_module_canvas → validate_design → update_module
143
+ - Query: list_modules → list_entries → get_entry / get_entry_history`,
144
+ inputSchema: {
145
+ workspaceId: z
146
+ .string()
147
+ .describe("Workspace ID from list_workspaces"),
148
+ },
149
+ annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false, idempotentHint: true },
150
+ }, async ({ workspaceId }) => {
151
+ try {
152
+ api.setWorkspaceId(workspaceId);
153
+ const data = await api.get(`/api/workspace/${api.enc(workspaceId)}`);
154
+ return ok(data);
155
+ }
156
+ catch (e) {
157
+ return err(e);
158
+ }
159
+ });
160
+ // ═══════════════════════════════════════════
161
+ // 3. list_modules
162
+ // ═══════════════════════════════════════════
163
+ server.registerTool("list_modules", {
164
+ title: "List Modules",
165
+ description: "List all discoverable modules in the current workspace. Call this to find module names for execute, modify, and query operations.",
166
+ inputSchema: {
167
+ workspaceId: wsParam,
168
+ },
169
+ annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false, idempotentHint: true },
170
+ }, async ({ workspaceId }) => {
171
+ try {
172
+ applyWorkspace(workspaceId);
173
+ const data = await api.get("/api/mcp/");
174
+ return ok(data);
175
+ }
176
+ catch (e) {
177
+ return err(e);
178
+ }
179
+ });
180
+ // ═══════════════════════════════════════════
181
+ // 4. get_module_schema (configure mode)
182
+ // ═══════════════════════════════════════════
183
+ configureTools.push(server.registerTool("get_module_schema", {
184
+ title: "Get Module Schema",
185
+ description: "Get the canvas schema for a module. Use tier=basic (default) for fields and states only. Use tier=extended to also include activities and flows. Use basic for query operations. Use extended when you need to understand available activities and state transitions.",
186
+ inputSchema: {
187
+ module: z.string().describe("Module name from list_modules"),
188
+ tier: z
189
+ .enum(["basic", "extended"])
190
+ .default("basic")
191
+ .describe("basic = fields + states. extended = + activities and flows."),
192
+ workspaceId: wsParam,
193
+ },
194
+ annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false, idempotentHint: true },
195
+ }, async ({ module: moduleName, tier, workspaceId }) => {
196
+ try {
197
+ applyWorkspace(workspaceId);
198
+ const data = await api.get(`/api/mcp/${api.enc(moduleName)}?tier=${tier}`);
199
+ return ok(data);
200
+ }
201
+ catch (e) {
202
+ return err(e);
203
+ }
204
+ }));
205
+ // ═══════════════════════════════════════════
206
+ // 5. get_module_canvas (configure mode)
207
+ // ═══════════════════════════════════════════
208
+ configureTools.push(server.registerTool("get_module_canvas", {
209
+ title: "Get Module Canvas",
210
+ description: `Get the full module definition with stable IDs. The output is round-trippable — modify and send back via update_module. Use this when modifying a module to preserve IDs for renaming.
211
+
212
+ Modify workflow: list_modules → get_module_canvas → (apply changes) → validate_design → update_module.
213
+ Load resource inistate://schema before modifying to know valid field types, colors, and actors.`,
214
+ inputSchema: {
215
+ module: z.string().describe("Module name or numeric ID"),
216
+ workspaceId: wsParam,
217
+ },
218
+ annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false, idempotentHint: true },
219
+ }, async ({ module: moduleName, workspaceId }) => {
220
+ try {
221
+ applyWorkspace(workspaceId);
222
+ const data = await api.get(`/api/configure/${api.enc(moduleName)}`);
223
+ return ok(data);
224
+ }
225
+ catch (e) {
226
+ return err(e);
227
+ }
228
+ }));
229
+ // ═══════════════════════════════════════════
230
+ // 6. list_entries
231
+ // ═══════════════════════════════════════════
232
+ server.registerTool("list_entries", {
233
+ title: "List Entries",
234
+ description: "Query entries with filters, sorting, pagination. Filter keys are field display names; values are equality (simple) or operator objects (contains/startsWith/endsWith/min/max/above/below/between/after/before/empty/exists/yes/no/is/not/excludes). Use {or:[…]} for OR; multiple keys are AND-ed. Use 'me' for User-field self-match. See FilterOperators in inistate://schema/runtime for the full set.\n\nToken control: use `fields` to restrict the returned `data` to just the columns you need. For modules with many fields this can shrink the response by an order of magnitude. System fields (id, state, audit metadata, etc.) are always returned regardless.",
235
+ inputSchema: {
236
+ module: z.string().describe("Module name from list_modules"),
237
+ state: z.string().optional(),
238
+ search: z.string().optional().describe("Free-text against document ID and indexed text fields"),
239
+ filters: z.record(z.unknown()).optional(),
240
+ sortBy: z.string().optional(),
241
+ sortDirection: z.enum(["asc", "desc"]).default("asc").optional(),
242
+ currentPage: z.number().int().default(0).optional(),
243
+ pageSize: z.number().int().default(50).optional().describe("Default 50, max 500"),
244
+ fields: z
245
+ .array(z.string())
246
+ .optional()
247
+ .describe("Field display names (or raw field names) to include in each entry's `data`. Strongly preferred over returning everything when the module has many or large fields — prunes both DB I/O and response tokens. Omit only when you actually need the full row. System fields are always returned."),
248
+ workspaceId: wsParam,
249
+ },
250
+ annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false, idempotentHint: true },
251
+ }, async ({ module: moduleName, state, search, filters, sortBy, sortDirection, currentPage, pageSize, fields, workspaceId }) => {
252
+ try {
253
+ applyWorkspace(workspaceId);
254
+ const body = { module: moduleName };
255
+ if (state)
256
+ body.state = state;
257
+ if (search)
258
+ body.search = search;
259
+ if (filters)
260
+ body.filters = filters;
261
+ if (sortBy)
262
+ body.sortBy = sortBy;
263
+ if (sortDirection)
264
+ body.sortDirection = sortDirection;
265
+ if (currentPage !== undefined)
266
+ body.currentPage = currentPage;
267
+ if (pageSize !== undefined)
268
+ body.pageSize = pageSize;
269
+ if (fields && fields.length > 0)
270
+ body.fields = fields;
271
+ const data = await api.post("/api/mcp/list", body);
272
+ return ok(data);
273
+ }
274
+ catch (e) {
275
+ return err(e);
276
+ }
277
+ });
278
+ // ═══════════════════════════════════════════
279
+ // 7. get_entry
280
+ // ═══════════════════════════════════════════
281
+ server.registerTool("get_entry", {
282
+ title: "Get Entry",
283
+ description: "Read a single entry by its ID. Returns current field values, state, audit metadata, and available activities.",
284
+ inputSchema: {
285
+ module: z.string().describe("Module name from list_modules"),
286
+ entryId: z
287
+ .union([z.string(), z.number()])
288
+ .describe("Entry ID"),
289
+ workspaceId: wsParam,
290
+ },
291
+ annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false, idempotentHint: true },
292
+ }, async ({ module: moduleName, entryId, workspaceId }) => {
293
+ try {
294
+ applyWorkspace(workspaceId);
295
+ const data = await api.post("/api/mcp/entry", {
296
+ module: moduleName,
297
+ entryId,
298
+ });
299
+ return ok(data);
300
+ }
301
+ catch (e) {
302
+ return err(e);
303
+ }
304
+ });
305
+ // ═══════════════════════════════════════════
306
+ // 8. get_form
307
+ // ═══════════════════════════════════════════
308
+ server.registerTool("get_form", {
309
+ title: "Get Activity Form",
310
+ description: "Get the form fields, current values, and options for a module activity. ALWAYS call this before submit_activity to discover required fields, their types, valid options, default values, and the confidence threshold. Never fabricate form data — if required fields cannot be confidently populated, ask the user.",
311
+ inputSchema: {
312
+ module: z.string().describe("Module name from list_modules"),
313
+ activity: z
314
+ .string()
315
+ .default("create")
316
+ .describe("Activity name: create, edit, view, or any custom activity name from get_module_schema"),
317
+ entryId: z
318
+ .union([z.string(), z.number(), z.null()])
319
+ .optional()
320
+ .describe("Entry ID for edit/view/custom activities. Omit for create."),
321
+ workspaceId: wsParam,
322
+ },
323
+ annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false, idempotentHint: true },
324
+ }, async ({ module: moduleName, activity, entryId, workspaceId }) => {
325
+ try {
326
+ applyWorkspace(workspaceId);
327
+ const body = {
328
+ module: moduleName,
329
+ activity,
330
+ };
331
+ if (entryId !== undefined && entryId !== null)
332
+ body.entryId = entryId;
333
+ const data = await api.post("/api/mcp/form", body);
334
+ return ok(data);
335
+ }
336
+ catch (e) {
337
+ return err(e);
338
+ }
339
+ });
340
+ // ═══════════════════════════════════════════
341
+ // 9. submit_activity
342
+ // ═══════════════════════════════════════════
343
+ server.registerTool("submit_activity", {
344
+ title: "Submit Activity",
345
+ description: "Perform an activity on a module entry: standard (create [no entryId], edit, delete, changeStatus, comment, duplicate, manage) or any custom activity from get_module_schema. ALWAYS call get_form first. The `ai` object is REQUIRED (reasoning + model + confidence). If confidence < the activity's threshold, the transition is suppressed and the entry is flagged. Server-side guard rules (human/hybrid actor, state-change confirm, confidence-inflation) may block — see inistate://guardrails. Input shapes: ActivitySubmission in inistate://schema/runtime.",
346
+ inputSchema: {
347
+ module: z.string(),
348
+ activity: z.string().default("create"),
349
+ entryId: z.union([z.string(), z.number()]).optional().describe("Omit for create"),
350
+ entryIds: z.array(z.union([z.string(), z.number()])).optional().describe("For bulk ops"),
351
+ input: z
352
+ .record(z.unknown())
353
+ .optional()
354
+ .describe("Field values keyed by display name. File/Image: {name,path}. Module: {id,value} (both required). User: {id,value,username} (all three required). Plural variants (Users/Modules/Files/Images): arrays of those objects. User/Module shapes are validated pre-flight — bare ids, bare strings, or objects missing any required key will be rejected."),
355
+ state: z.string().optional().describe("Target state name"),
356
+ comment: z.string().optional().describe("Optional. Add only when it carries information not already in the field values or reasoning. Keep short and precise."),
357
+ assignees: z.array(z.string()).optional().describe("Usernames"),
358
+ due: z.string().optional().describe("ISO 8601"),
359
+ ai: z
360
+ .object({
361
+ reasoning: z.string().describe("Why the AI chose this action — recorded for audit. Keep short and precise; one or two sentences."),
362
+ model: z.string().describe("e.g. claude-haiku-4-5, claude-opus-4-7"),
363
+ confidence: z.number().min(0).max(1).describe("0-1; gated against the activity's confidence_threshold"),
364
+ sources: z
365
+ .array(z.object({
366
+ type: z.string().optional(),
367
+ reference: z.string().optional(),
368
+ excerpt: z.string().optional(),
369
+ }))
370
+ .optional(),
371
+ model_version: z.string().optional(),
372
+ prompt_hash: z.string().optional(),
373
+ })
374
+ .describe("REQUIRED — AI agent traceability"),
375
+ confirmed: z
376
+ .boolean()
377
+ .optional()
378
+ .describe("Set true only after explicit user authorization. Required for: changeStatus, state override, hybrid actor, retry after flag. Does not unlock human-actor activities. See inistate://guardrails."),
379
+ workspaceId: wsParam,
380
+ },
381
+ annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: false },
382
+ }, async ({ module: moduleName, activity, entryId, entryIds, input, state, comment, assignees, due, ai, confirmed, workspaceId, }) => {
383
+ try {
384
+ applyWorkspace(workspaceId);
385
+ const guard = await evaluateActivity({
386
+ module: moduleName,
387
+ activity,
388
+ entryId,
389
+ entryIds,
390
+ state,
391
+ confidence: ai?.confidence ?? 0,
392
+ confirmed,
393
+ });
394
+ if (!guard.ok) {
395
+ const target = entryId ?? (entryIds ? `bulk(${entryIds.length})` : "new");
396
+ log("submit_activity", `module=${moduleName} activity=${activity} entry=${target} → BLOCKED: ${guard.structured.error}`);
397
+ return err({ structured: guard.structured });
398
+ }
399
+ // Reference-shape pre-flight: User/Module fields must be { id, value }.
400
+ if (input) {
401
+ const shapeErrors = await validateInputShapes(moduleName, input);
402
+ if (shapeErrors.length > 0) {
403
+ const target = entryId ?? (entryIds ? `bulk(${entryIds.length})` : "new");
404
+ const structured = {
405
+ error: "invalid_reference_field_shape",
406
+ message: "One or more User/Module fields were submitted with the wrong shape. They require { id, value } objects (plural variants take arrays of them).",
407
+ activity,
408
+ fields: shapeErrors,
409
+ agent_action: "Re-read the entry or call get_form, copy the User/Module values back unchanged (they round-trip), and resubmit. Do not pass bare ids or display strings.",
410
+ };
411
+ log("submit_activity", `module=${moduleName} activity=${activity} entry=${target} → BLOCKED: invalid_reference_field_shape (${shapeErrors.length} field${shapeErrors.length === 1 ? "" : "s"})`);
412
+ return err({ structured });
413
+ }
414
+ }
415
+ // Normalize file field inputs: remap 'url' → 'path' if client sent { name, url } instead of { name, path }
416
+ if (input) {
417
+ for (const key of Object.keys(input)) {
418
+ const val = input[key];
419
+ if (val && typeof val === "object" && !Array.isArray(val)) {
420
+ const obj = val;
421
+ if (obj.url && !obj.path) {
422
+ obj.path = obj.url;
423
+ delete obj.url;
424
+ }
425
+ }
426
+ else if (Array.isArray(val)) {
427
+ for (const item of val) {
428
+ if (item && typeof item === "object") {
429
+ const obj = item;
430
+ if (obj.url && !obj.path) {
431
+ obj.path = obj.url;
432
+ delete obj.url;
433
+ }
434
+ }
435
+ }
436
+ }
437
+ }
438
+ }
439
+ const body = {
440
+ module: moduleName,
441
+ activity,
442
+ };
443
+ if (entryId !== undefined)
444
+ body.entryId = entryId;
445
+ if (entryIds)
446
+ body.entryIds = entryIds;
447
+ if (input)
448
+ body.input = input;
449
+ if (state)
450
+ body.state = state;
451
+ if (comment)
452
+ body.comment = comment;
453
+ if (assignees)
454
+ body.assignees = assignees;
455
+ if (due)
456
+ body.due = due;
457
+ if (ai)
458
+ body.ai = ai;
459
+ const target = entryId ?? (entryIds ? `bulk(${entryIds.length})` : "new");
460
+ log("submit_activity", `module=${moduleName} activity=${activity} entry=${target} payload=${JSON.stringify(body)}`);
461
+ const data = await api.post("/api/mcp/activity", body);
462
+ const flagged = data && typeof data === "object" && data.flagged === true;
463
+ const flagTargets = entryIds && entryIds.length > 0 ? entryIds : [entryId];
464
+ for (const t of flagTargets) {
465
+ if (flagged) {
466
+ recordFlagged(moduleName, t, activity, ai?.confidence ?? 0);
467
+ }
468
+ else {
469
+ clearFlagged(moduleName, t, activity);
470
+ }
471
+ }
472
+ log("submit_activity", `module=${moduleName} activity=${activity} entry=${target} → ${flagged ? "flagged" : "ok"}`);
473
+ return ok(data);
474
+ }
475
+ catch (e) {
476
+ const target = entryId ?? (entryIds ? `bulk(${entryIds.length})` : "new");
477
+ log("submit_activity", `module=${moduleName} activity=${activity} entry=${target} → FAILED: ${e instanceof Error ? e.message : String(e)}`);
478
+ return err(e);
479
+ }
480
+ });
481
+ // ═══════════════════════════════════════════
482
+ // 9b. submit_activities (bulk)
483
+ // ═══════════════════════════════════════════
484
+ server.registerTool("submit_activities", {
485
+ title: "Submit Activities (Bulk)",
486
+ description: "Bulk variant of submit_activity: same module + same activity applied to multiple entries, each with its own input payload. Use this instead of N sequential submit_activity calls when creating/editing many rows at once — saves substantial agent tokens by collapsing N tool turns into one.\n\nShape: top-level `module`, `activity`, and a default `ai` block; per-item `input` (and optional `entryId`, `state`, `comment`, `assignees`, `due`, `ai`, `clientRef`). When an item supplies its own `ai`, it wholly replaces the top-level `ai` for that item — no partial merge.\n\nExecution: items run sequentially fail-soft on the server. One item's failure does not abort the rest; per-item outcomes (success/failure, entryId, flagged, validation details) are returned in `results`. Use `clientRef` to correlate items to your local plan.\n\nLimits: max 100 items per request. Beyond that, chunk and retry.\n\nGuardrails: same `submit_activity` rules apply at the batch level — actor='human' rejects the whole batch; actor='hybrid' or activity='changeStatus' or top-level `state` requires `confirmed: true`. Per-item state overrides also require `confirmed: true`.",
487
+ inputSchema: {
488
+ module: z.string(),
489
+ activity: z.string().default("create"),
490
+ ai: z
491
+ .object({
492
+ reasoning: z.string().describe("Why the AI chose this action — recorded for audit. Keep short and precise; one or two sentences."),
493
+ model: z.string(),
494
+ confidence: z.number().min(0).max(1),
495
+ sources: z
496
+ .array(z.object({
497
+ type: z.string().optional(),
498
+ reference: z.string().optional(),
499
+ excerpt: z.string().optional(),
500
+ }))
501
+ .optional(),
502
+ model_version: z.string().optional(),
503
+ prompt_hash: z.string().optional(),
504
+ })
505
+ .describe("Default AI traceability applied to every item that does not specify its own."),
506
+ items: z
507
+ .array(z.object({
508
+ entryId: z.union([z.string(), z.number()]).optional().describe("Omit for create"),
509
+ input: z
510
+ .record(z.unknown())
511
+ .optional()
512
+ .describe("Field values keyed by display name. Same shape as submit_activity.input."),
513
+ state: z.string().optional().describe("Per-item target state name"),
514
+ comment: z.string().optional().describe("Optional. Add only when it carries information not already in the field values or reasoning. Keep short and precise."),
515
+ assignees: z.array(z.string()).optional(),
516
+ due: z.string().optional().describe("ISO 8601"),
517
+ ai: z
518
+ .object({
519
+ reasoning: z.string().describe("Why the AI chose this action — recorded for audit. Keep short and precise; one or two sentences."),
520
+ model: z.string(),
521
+ confidence: z.number().min(0).max(1),
522
+ sources: z
523
+ .array(z.object({
524
+ type: z.string().optional(),
525
+ reference: z.string().optional(),
526
+ excerpt: z.string().optional(),
527
+ }))
528
+ .optional(),
529
+ model_version: z.string().optional(),
530
+ prompt_hash: z.string().optional(),
531
+ })
532
+ .optional()
533
+ .describe("Optional per-item ai override. Wholly replaces top-level ai for this item."),
534
+ clientRef: z
535
+ .string()
536
+ .optional()
537
+ .describe("Optional caller-supplied correlation id, echoed back on the result."),
538
+ }))
539
+ .min(1)
540
+ .max(100)
541
+ .describe("1-100 items. Each item carries only what differs from the top-level activity."),
542
+ confirmed: z
543
+ .boolean()
544
+ .optional()
545
+ .describe("REQUIRED when the activity is 'changeStatus', any per-item or top-level `state` override is supplied, or the activity's actor is 'hybrid'. Set true ONLY after surfacing the planned bulk action to the user."),
546
+ workspaceId: wsParam,
547
+ },
548
+ annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: false },
549
+ }, async ({ module: moduleName, activity, ai, items, confirmed, workspaceId }) => {
550
+ try {
551
+ applyWorkspace(workspaceId);
552
+ // Batch-level guard for actor (human/hybrid) and changeStatus rules,
553
+ // which apply uniformly to the whole batch since module + activity are shared.
554
+ const guard = await evaluateActivity({
555
+ module: moduleName,
556
+ activity,
557
+ confidence: ai?.confidence ?? 0,
558
+ confirmed,
559
+ });
560
+ if (!guard.ok) {
561
+ log("submit_activities", `module=${moduleName} activity=${activity} count=${items.length} → BLOCKED: ${guard.structured.error}`);
562
+ return err({ structured: guard.structured });
563
+ }
564
+ // Any per-item state override also requires explicit confirmation.
565
+ const itemsWithState = items
566
+ .map((it, i) => ({ idx: i, state: it.state }))
567
+ .filter((x) => !!x.state);
568
+ if (itemsWithState.length > 0 && !confirmed) {
569
+ const structured = {
570
+ error: "state_override_requires_confirmation",
571
+ message: "One or more items pass a 'state' override. Bulk state changes require explicit user authorization — surface the planned changes and resubmit with confirmed: true.",
572
+ activity,
573
+ items: itemsWithState,
574
+ agent_action: "Show the user the per-item state changes you intend to make, then resubmit with confirmed: true.",
575
+ };
576
+ log("submit_activities", `module=${moduleName} activity=${activity} count=${items.length} → BLOCKED: state_override_requires_confirmation (${itemsWithState.length} items)`);
577
+ return err({ structured });
578
+ }
579
+ // Per-item confidence inflation: each item may override `ai`, so we
580
+ // can't fold this into the batch-level evaluateActivity call.
581
+ if (!confirmed) {
582
+ const inflated = [];
583
+ for (let i = 0; i < items.length; i++) {
584
+ const item = items[i];
585
+ const itemAi = item.ai ?? ai;
586
+ const conf = itemAi?.confidence ?? 0;
587
+ const prior = getPriorFlag(moduleName, item.entryId, activity);
588
+ if (prior && conf > prior.confidence + 1e-6) {
589
+ inflated.push({ idx: i, entryId: item.entryId, previous: prior.confidence, current: conf });
590
+ }
591
+ }
592
+ if (inflated.length > 0) {
593
+ const structured = {
594
+ error: "confidence_inflation_blocked",
595
+ message: "One or more items target entries that were previously flagged for human review and would be resubmitted with a higher confidence. Surface the flag(s) to the user.",
596
+ activity,
597
+ items: inflated,
598
+ agent_action: "Stop. Tell the user which entries were flagged. Do not retry these items with a higher confidence on your own. If the user explicitly authorizes proceeding, resubmit with confirmed: true.",
599
+ };
600
+ log("submit_activities", `module=${moduleName} activity=${activity} count=${items.length} → BLOCKED: confidence_inflation_blocked (${inflated.length} items)`);
601
+ return err({ structured });
602
+ }
603
+ }
604
+ // Reference-shape pre-flight: User/Module fields must be { id, value }
605
+ // (User adds `username`). Fetch the field-type map once for the whole
606
+ // batch — the per-item check is then synchronous.
607
+ const fieldTypes = await getModuleFieldTypes(moduleName);
608
+ const shapeFailures = [];
609
+ for (let i = 0; i < items.length; i++) {
610
+ const it = items[i];
611
+ if (!it.input)
612
+ continue;
613
+ const errs = validateInputShapesWith(fieldTypes, it.input);
614
+ if (errs.length > 0)
615
+ shapeFailures.push({ idx: i, fields: errs });
616
+ }
617
+ if (shapeFailures.length > 0) {
618
+ const structured = {
619
+ error: "invalid_reference_field_shape",
620
+ message: "One or more items submit User/Module fields with the wrong shape. They require { id, value } objects (plural variants take arrays of them).",
621
+ activity,
622
+ items: shapeFailures,
623
+ agent_action: "Re-read the entries or call get_form, copy the User/Module values back unchanged (they round-trip), and resubmit. Do not pass bare ids or display strings.",
624
+ };
625
+ log("submit_activities", `module=${moduleName} activity=${activity} count=${items.length} → BLOCKED: invalid_reference_field_shape (${shapeFailures.length} items)`);
626
+ return err({ structured });
627
+ }
628
+ // Normalize file fields per item: remap 'url' → 'path' if needed.
629
+ for (const item of items) {
630
+ if (!item.input)
631
+ continue;
632
+ for (const key of Object.keys(item.input)) {
633
+ const val = item.input[key];
634
+ if (val && typeof val === "object" && !Array.isArray(val)) {
635
+ const obj = val;
636
+ if (obj.url && !obj.path) {
637
+ obj.path = obj.url;
638
+ delete obj.url;
639
+ }
640
+ }
641
+ else if (Array.isArray(val)) {
642
+ for (const sub of val) {
643
+ if (sub && typeof sub === "object") {
644
+ const obj = sub;
645
+ if (obj.url && !obj.path) {
646
+ obj.path = obj.url;
647
+ delete obj.url;
648
+ }
649
+ }
650
+ }
651
+ }
652
+ }
653
+ }
654
+ const body = {
655
+ module: moduleName,
656
+ activity,
657
+ items,
658
+ };
659
+ if (ai)
660
+ body.ai = ai;
661
+ log("submit_activities", `module=${moduleName} activity=${activity} count=${items.length}`);
662
+ const data = (await api.post("/api/mcp/activity/bulk", body));
663
+ // Update flag cache from per-item results so future submit_activity
664
+ // calls on the same entries see the prior flag.
665
+ const results = Array.isArray(data.results)
666
+ ? (data.results)
667
+ : [];
668
+ for (let i = 0; i < results.length; i++) {
669
+ const r = results[i];
670
+ const itemAi = items[i]?.ai ?? ai;
671
+ const conf = itemAi?.confidence ?? 0;
672
+ const targetEntryId = r.entryId ?? items[i]?.entryId;
673
+ if (r.flagged === true) {
674
+ recordFlagged(moduleName, targetEntryId, activity, conf);
675
+ }
676
+ else if (r.success === true) {
677
+ clearFlagged(moduleName, targetEntryId, activity);
678
+ }
679
+ }
680
+ const summary = data.summary;
681
+ log("submit_activities", `module=${moduleName} activity=${activity} count=${items.length} → ok=${summary?.succeeded ?? "?"} fail=${summary?.failed ?? "?"} flagged=${summary?.flagged ?? "?"}`);
682
+ return ok(data);
683
+ }
684
+ catch (e) {
685
+ log("submit_activities", `module=${moduleName} activity=${activity} count=${items.length} → FAILED: ${e instanceof Error ? e.message : String(e)}`);
686
+ return err(e);
687
+ }
688
+ });
689
+ // ═══════════════════════════════════════════
690
+ // 10. get_entry_history
691
+ // ═══════════════════════════════════════════
692
+ server.registerTool("get_entry_history", {
693
+ title: "Get Entry History",
694
+ description: "Get the audit trail and comments for an entry. Returns chronological list of actions (create, edit, state changes, comments) with field-level change details and AI traceability context.",
695
+ inputSchema: {
696
+ module: z.string().describe("Module name from list_modules"),
697
+ entryId: z
698
+ .union([z.string(), z.number()])
699
+ .describe("Entry ID to get history for"),
700
+ page: z
701
+ .number()
702
+ .int()
703
+ .default(0)
704
+ .optional()
705
+ .describe("Page number (0-based, 50 items per page)"),
706
+ workspaceId: wsParam,
707
+ },
708
+ annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false, idempotentHint: true },
709
+ }, async ({ module: moduleName, entryId, page, workspaceId }) => {
710
+ try {
711
+ applyWorkspace(workspaceId);
712
+ const body = {
713
+ module: moduleName,
714
+ entryId,
715
+ };
716
+ if (page !== undefined)
717
+ body.page = page;
718
+ const data = await api.post("/api/mcp/history", body);
719
+ return ok(data);
720
+ }
721
+ catch (e) {
722
+ return err(e);
723
+ }
724
+ });
725
+ // ═══════════════════════════════════════════
726
+ // 11. upload_file
727
+ // ═══════════════════════════════════════════
728
+ server.registerTool("upload_file", {
729
+ title: "Upload File (Fallback)",
730
+ description: "FALLBACK ONLY — do NOT use this by default. Always use request_upload_url + confirm_upload first; call this tool only after the presigned flow has actually failed (e.g. request_upload_url errored, or the PUT/confirm step failed for non-retryable reasons). Uploads a file to S3 via base64/multipart. Returns { path, filename, mimeType, size }. Use the returned path as the 'path' value in File/Image fields for submit_activity (e.g. { name: 'photo.jpg', path: result.path }). Max 50MB. Blocked: .exe, .bat, .cmd, .dll, .msi.",
731
+ inputSchema: {
732
+ module: z
733
+ .string()
734
+ .describe("Module name. Required — scopes the file to the module's storage folder."),
735
+ name: z.string().describe("Original filename (e.g. 'report.pdf')"),
736
+ file: z.string().describe("Base64-encoded file content"),
737
+ mimeType: z
738
+ .string()
739
+ .default("application/octet-stream")
740
+ .describe("MIME type of the file"),
741
+ workspaceId: wsParam,
742
+ },
743
+ annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false },
744
+ }, async ({ module: moduleName, name: fileName, file: fileContent, mimeType, workspaceId }) => {
745
+ try {
746
+ applyWorkspace(workspaceId);
747
+ log("upload_file", `module=${moduleName} file=${fileName} mime=${mimeType}`);
748
+ const buffer = Buffer.from(fileContent, "base64");
749
+ const blob = new Blob([buffer], { type: mimeType });
750
+ const formData = new FormData();
751
+ formData.append("file", blob, fileName);
752
+ formData.append("module", moduleName);
753
+ const raw = await api.uploadFormData("/api/mcp/upload", formData);
754
+ log("upload_file", `module=${moduleName} file=${fileName} → ok`);
755
+ return ok(raw);
756
+ }
757
+ catch (e) {
758
+ log("upload_file", `module=${moduleName} file=${fileName} → FAILED: ${e instanceof Error ? e.message : String(e)}`);
759
+ return err(e);
760
+ }
761
+ });
762
+ // ═══════════════════════════════════════════
763
+ // 12. download_file
764
+ // ═══════════════════════════════════════════
765
+ server.registerTool("download_file", {
766
+ title: "Download File",
767
+ description: "Download a file by module name. Construct the URL from a File/Image field value: field.path = '/s/{guid}/{fileName}'. Returns a pre-signed S3 URL (1hr TTL).",
768
+ inputSchema: {
769
+ moduleName: z.string().describe("Module name (resolved to vectorId internally)"),
770
+ guid: z.string().describe("Short ID from the file URL"),
771
+ fileName: z.string().describe("Original filename"),
772
+ workspaceId: wsParam,
773
+ },
774
+ annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false, idempotentHint: true },
775
+ }, async ({ moduleName, guid, fileName, workspaceId }) => {
776
+ try {
777
+ applyWorkspace(workspaceId);
778
+ const result = await api.getRaw(`/api/mcp/download/${api.enc(moduleName)}/s/${api.enc(guid)}/${api.enc(fileName)}`);
779
+ if (result.redirectUrl) {
780
+ return ok({ downloadUrl: result.redirectUrl, fileName });
781
+ }
782
+ return ok(result.body);
783
+ }
784
+ catch (e) {
785
+ return err(e);
786
+ }
787
+ });
788
+ // ═══════════════════════════════════════════
789
+ // 13. request_upload_url
790
+ // ═══════════════════════════════════════════
791
+ server.registerTool("request_upload_url", {
792
+ title: "Request Upload URL",
793
+ description: `DEFAULT upload path — ALWAYS use this for every file upload (any size, up to 500MB). Only fall back to upload_file if this flow actually fails. Three-step flow: 1) call this tool, 2) PUT the raw bytes to uploadUrl with Content-Type exactly matching contentType (S3 rejects mismatches with 403 SignatureDoesNotMatch), 3) call confirm_upload({ s3Key }). The path returned by confirm_upload is used directly as the File/Image field value in submit_activity. uploadUrl expires in ~1 hour and cannot be renewed — call this again on expiry.`,
794
+ inputSchema: {
795
+ module: z
796
+ .string()
797
+ .describe("Module name. Required — scopes the file to the module's storage folder."),
798
+ fileName: z.string().describe("Original filename including extension (e.g. 'report.pdf')"),
799
+ contentType: z
800
+ .string()
801
+ .default("application/octet-stream")
802
+ .describe("MIME type. Must match the Content-Type header used in the PUT request."),
803
+ fileSize: z
804
+ .number()
805
+ .int()
806
+ .positive()
807
+ .describe("File size in bytes. Must be > 0 and ≤ 500MB (524288000)."),
808
+ workspaceId: wsParam,
809
+ },
810
+ annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false },
811
+ }, async ({ module: moduleName, fileName, contentType, fileSize, workspaceId }) => {
812
+ try {
813
+ applyWorkspace(workspaceId);
814
+ log("request_upload_url", `module=${moduleName} file=${fileName} size=${fileSize} mime=${contentType}`);
815
+ const data = await api.post("/api/mcp/request-upload-url", {
816
+ module: moduleName,
817
+ fileName,
818
+ contentType,
819
+ fileSize,
820
+ });
821
+ log("request_upload_url", `module=${moduleName} file=${fileName} → ok`);
822
+ return ok(data);
823
+ }
824
+ catch (e) {
825
+ log("request_upload_url", `module=${moduleName} file=${fileName} → FAILED: ${e instanceof Error ? e.message : String(e)}`);
826
+ return err(e);
827
+ }
828
+ });
829
+ // ═══════════════════════════════════════════
830
+ // 14. confirm_upload
831
+ // ═══════════════════════════════════════════
832
+ server.registerTool("confirm_upload", {
833
+ title: "Confirm Upload",
834
+ description: `Confirm a presigned upload completed. Call after successfully PUTting the file to the uploadUrl from request_upload_url. The server verifies the object exists in S3, reads its metadata, and tracks workspace storage. Only s3Key is required — filename, size, and MIME type are resolved from S3. Returns { url, filename, mimeType, size } where url is the /s/ path usable as a File/Image field value. Returns 400 if the file is not found in S3 — ensure the PUT completed before calling.`,
835
+ inputSchema: {
836
+ s3Key: z
837
+ .string()
838
+ .describe("The s3Key returned from request_upload_url."),
839
+ workspaceId: wsParam,
840
+ },
841
+ annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false },
842
+ }, async ({ s3Key, workspaceId }) => {
843
+ try {
844
+ applyWorkspace(workspaceId);
845
+ log("confirm_upload", `s3Key=${s3Key}`);
846
+ const data = await api.post("/api/mcp/confirm-upload", { s3Key });
847
+ log("confirm_upload", `s3Key=${s3Key} → ok`);
848
+ return ok(data);
849
+ }
850
+ catch (e) {
851
+ log("confirm_upload", `s3Key=${s3Key} → FAILED: ${e instanceof Error ? e.message : String(e)}`);
852
+ return err(e);
853
+ }
854
+ });
855
+ // ═══════════════════════════════════════════
856
+ // 15. design_workflow (configure mode)
857
+ // ═══════════════════════════════════════════
858
+ configureTools.push(server.registerTool("design_workflow", {
859
+ title: "Design Workflow",
860
+ description: `Generate a scaffolded ModuleSchema template from a natural language description. Use when the user wants to create a new module or workflow.
861
+
862
+ Design workflow: design_workflow → (complete template) → validate_design → create_module → get_module_schema(tier=extended).
863
+ Load resources inistate://schema and inistate://design-guide before designing for valid field types, colors, and design rules.`,
864
+ inputSchema: {
865
+ description: z
866
+ .string()
867
+ .describe("Natural language description of the desired workflow. Include: entity type, lifecycle states, activities, who performs each, what data is collected."),
868
+ industry: z
869
+ .enum([
870
+ "financial_services",
871
+ "healthcare",
872
+ "legal",
873
+ "hr",
874
+ "procurement",
875
+ "it_service",
876
+ "general",
877
+ ])
878
+ .default("general")
879
+ .describe("Industry context for compliance-aware defaults. Affects: default audit fields, confidence thresholds, actor type suggestions."),
880
+ },
881
+ annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false, idempotentHint: true },
882
+ }, async ({ description, industry }) => {
883
+ const result = designWorkflow(description, industry);
884
+ return ok(result);
885
+ }));
886
+ // ═══════════════════════════════════════════
887
+ // 14. validate_design (configure mode)
888
+ // ═══════════════════════════════════════════
889
+ configureTools.push(server.registerTool("validate_design", {
890
+ title: "Validate Design",
891
+ description: "Validate a module schema before creating or updating. Checks structural integrity against all FACTSOps rules without submitting to the API. Passing validate_design guarantees the subsequent create_module/update_module call will not fail with 422. Always call this before create_module or update_module.",
892
+ inputSchema: {
893
+ schema: z
894
+ .record(z.unknown())
895
+ .describe("A complete or partial ModuleSchema object"),
896
+ mode: z
897
+ .enum(["create", "update"])
898
+ .default("create")
899
+ .describe("create = new module (all rules). update = merge (omitted sections acceptable)."),
900
+ },
901
+ annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false, idempotentHint: true },
902
+ }, async ({ schema, mode }) => {
903
+ const result = validateDesign(schema, mode);
904
+ return ok(result);
905
+ }));
906
+ // ═══════════════════════════════════════════
907
+ // 15. create_module (configure mode)
908
+ // ═══════════════════════════════════════════
909
+ configureTools.push(server.registerTool("create_module", {
910
+ title: "Create Module",
911
+ description: "Create a new module. Supports workflow modules (states, activities, flows) and record list modules (fields only). Requires Administrator, Consultant, or Workspace Admin role. Always call validate_design first. See inistate://schema/configure for field types, color palette, and design rules.",
912
+ inputSchema: {
913
+ name: z.string().describe("Module name"),
914
+ ...moduleSectionsShape,
915
+ workspaceId: wsParam,
916
+ },
917
+ annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false },
918
+ }, async ({ name, icon, description: desc, information, states, activities, flows, workspaceId, }) => {
919
+ try {
920
+ applyWorkspace(workspaceId);
921
+ const body = { name };
922
+ if (icon)
923
+ body.icon = icon;
924
+ if (desc)
925
+ body.description = desc;
926
+ if (information)
927
+ body.information = information;
928
+ if (states)
929
+ body.states = states;
930
+ if (activities)
931
+ body.activities = activities;
932
+ if (flows)
933
+ body.flows = flows;
934
+ log("create_module", `name=${name}`);
935
+ const data = await api.post(`/api/configure`, body);
936
+ log("create_module", `name=${name} → ok`);
937
+ return ok(data);
938
+ }
939
+ catch (e) {
940
+ log("create_module", `name=${name} → FAILED: ${e instanceof Error ? e.message : String(e)}`);
941
+ return err(e);
942
+ }
943
+ }));
944
+ // ═══════════════════════════════════════════
945
+ // 16. update_module (configure mode)
946
+ // ═══════════════════════════════════════════
947
+ configureTools.push(server.registerTool("update_module", {
948
+ title: "Update Module",
949
+ description: "Update an existing module. Merges changes into the existing canvas; items matched by id enable renaming. Omitted sections are left unchanged. Always call get_module_canvas first to obtain the stable module id and item ids, then validate_design before submitting.",
950
+ inputSchema: {
951
+ id: z
952
+ .union([z.string(), z.number()])
953
+ .describe("Module id from get_module_canvas. Identifies which module to update."),
954
+ name: z.string().optional().describe("New module name (for renaming)"),
955
+ ...moduleSectionsShape,
956
+ workspaceId: wsParam,
957
+ },
958
+ annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: false },
959
+ }, async ({ id, name, icon, description: desc, information, states, activities, flows, workspaceId, }) => {
960
+ try {
961
+ applyWorkspace(workspaceId);
962
+ const body = { id };
963
+ if (name)
964
+ body.name = name;
965
+ if (icon)
966
+ body.icon = icon;
967
+ if (desc)
968
+ body.description = desc;
969
+ if (information)
970
+ body.information = information;
971
+ if (states)
972
+ body.states = states;
973
+ if (activities)
974
+ body.activities = activities;
975
+ if (flows)
976
+ body.flows = flows;
977
+ log("update_module", `id=${id}${name ? ` newName=${name}` : ""}`);
978
+ const data = await api.put(`/api/configure`, body);
979
+ log("update_module", `id=${id} → ok`);
980
+ return ok(data);
981
+ }
982
+ catch (e) {
983
+ log("update_module", `id=${id} → FAILED: ${e instanceof Error ? e.message : String(e)}`);
984
+ return err(e);
985
+ }
986
+ }));
987
+ return { configureTools };
988
+ }