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.
@@ -0,0 +1,505 @@
1
+ import { readFileSync } from "fs";
2
+ import { resolve, dirname } from "path";
3
+ import { fileURLToPath } from "url";
4
+ // ---------- Load schema at startup ----------
5
+ const __filename = fileURLToPath(import.meta.url);
6
+ const __dirname = dirname(__filename);
7
+ const SCHEMA_PATH = resolve(__dirname, "../inistate-schema.json");
8
+ const DESIGN_GUIDE_PATH = resolve(__dirname, "../facts-module-design-guide.md");
9
+ const FRONTEND_GUIDE_PATH = resolve(__dirname, "../facts-frontend-guide.md");
10
+ export const SCHEMA = JSON.parse(readFileSync(SCHEMA_PATH, "utf-8"));
11
+ export const DESIGN_GUIDE = readFileSync(DESIGN_GUIDE_PATH, "utf-8");
12
+ export const FRONTEND_GUIDE = readFileSync(FRONTEND_GUIDE_PATH, "utf-8");
13
+ // ---------- Mode-filtered schema views ----------
14
+ //
15
+ // The full SCHEMA is large (~66KB). Most agent sessions only need runtime
16
+ // tools (list/get/submit/upload) and their types — configure-mode tools
17
+ // (create_module, update_module) and design rules (state_color_system,
18
+ // module_types) are dead weight. We expose filtered variants so agents
19
+ // can pick by mode.
20
+ const SHARED_DEFINITIONS = [
21
+ "FieldType",
22
+ "FieldDefinition",
23
+ "SubFieldDefinition",
24
+ "StateDefinition",
25
+ "FileFieldValue",
26
+ "FileFieldInput",
27
+ "FileUploadResult",
28
+ "PresignedUploadResult",
29
+ "ModuleFieldValue",
30
+ "UserFieldValue",
31
+ "ErrorResponse",
32
+ ];
33
+ const RUNTIME_DEFINITIONS = [
34
+ ...SHARED_DEFINITIONS,
35
+ "EntryData",
36
+ "Entry",
37
+ "EntryList",
38
+ "ActivityForm",
39
+ "ActivitySubmission",
40
+ "AvailableActivities",
41
+ "ActivityResult",
42
+ "HistoryEvent",
43
+ "EntryHistory",
44
+ "FilterOperators",
45
+ ];
46
+ const CONFIGURE_DEFINITIONS = [
47
+ ...SHARED_DEFINITIONS,
48
+ "ActivityDefinition",
49
+ "ActivityFieldRef",
50
+ "FlowDefinition",
51
+ "ModuleSchema",
52
+ ];
53
+ const RUNTIME_OPERATIONS = [
54
+ "list_workspaces",
55
+ "get_workspace",
56
+ "discover_modules",
57
+ "get_module",
58
+ "list_entries",
59
+ "get_entry",
60
+ "get_form",
61
+ "submit_activity",
62
+ "submit_activities",
63
+ "get_history",
64
+ "request_upload_url",
65
+ "confirm_upload",
66
+ "upload_file",
67
+ "download_file",
68
+ ];
69
+ const CONFIGURE_OPERATIONS = [
70
+ "get_module_schema",
71
+ "create_module",
72
+ "update_module",
73
+ ];
74
+ const RUNTIME_WORKFLOW_KEYS = [
75
+ "_description",
76
+ "steps",
77
+ "key_rules",
78
+ "confidence_gate",
79
+ "ai_audit_trail",
80
+ ];
81
+ const CONFIGURE_WORKFLOW_KEYS = [
82
+ "_description",
83
+ "steps",
84
+ "key_rules",
85
+ "module_types",
86
+ "state_color_system",
87
+ ];
88
+ function pickKeys(source, keys) {
89
+ const out = {};
90
+ for (const k of keys) {
91
+ if (k in source)
92
+ out[k] = source[k];
93
+ }
94
+ return out;
95
+ }
96
+ function buildSchemaView(definitionKeys, operationKeys, workflowKeys) {
97
+ return {
98
+ $schema: SCHEMA.$schema,
99
+ title: SCHEMA.title,
100
+ description: SCHEMA.description,
101
+ version: SCHEMA.version,
102
+ definitions: pickKeys(SCHEMA.definitions, definitionKeys),
103
+ operations: {
104
+ _description: SCHEMA.operations._description,
105
+ ...pickKeys(SCHEMA.operations, operationKeys),
106
+ },
107
+ workflow_guide: pickKeys(SCHEMA.workflow_guide, workflowKeys),
108
+ };
109
+ }
110
+ export const SCHEMA_RUNTIME = buildSchemaView(RUNTIME_DEFINITIONS, RUNTIME_OPERATIONS, RUNTIME_WORKFLOW_KEYS);
111
+ export const SCHEMA_CONFIGURE = buildSchemaView(CONFIGURE_DEFINITIONS, CONFIGURE_OPERATIONS, CONFIGURE_WORKFLOW_KEYS);
112
+ // ---------- Derived lookups ----------
113
+ export const VALID_FIELD_TYPES = SCHEMA.definitions.FieldType.enum;
114
+ export const VALID_ACTOR_TYPES = SCHEMA.definitions.ActivityDefinition.properties.actor.enum;
115
+ export const COLOR_PALETTE = SCHEMA.workflow_guide.state_color_system.palette;
116
+ export const VALID_COLORS = Object.keys(COLOR_PALETTE);
117
+ export const COLOR_KEYWORDS = SCHEMA.workflow_guide.state_color_system.keyword_hints;
118
+ // ---------- Helpers ----------
119
+ export function isValidFieldType(type) {
120
+ if (type.startsWith("Selection(") && type.endsWith(")"))
121
+ return true;
122
+ return VALID_FIELD_TYPES.includes(type);
123
+ }
124
+ export function isValidColor(hex) {
125
+ return VALID_COLORS.includes(hex);
126
+ }
127
+ export function isValidActor(actor) {
128
+ return VALID_ACTOR_TYPES.includes(actor);
129
+ }
130
+ export function suggestColorForState(stateName) {
131
+ const lower = stateName.toLowerCase();
132
+ // Check terminal keywords first (dark green / dark red)
133
+ const terminalSuccess = COLOR_KEYWORDS["#1E6B45"] || [];
134
+ if (terminalSuccess.some((kw) => lower.includes(kw)))
135
+ return "#1E6B45";
136
+ const terminalFailure = COLOR_KEYWORDS["#8B2D2D"] || [];
137
+ if (terminalFailure.some((kw) => lower.includes(kw)))
138
+ return "#8B2D2D";
139
+ // Then check remaining in decision order
140
+ const order = [
141
+ "#2A7B50",
142
+ "#C0392B",
143
+ "#A07828",
144
+ "#6B4D91",
145
+ "#2968A8",
146
+ "#5A6070",
147
+ ];
148
+ for (const hex of order) {
149
+ const keywords = COLOR_KEYWORDS[hex] || [];
150
+ if (keywords.some((kw) => lower.includes(kw)))
151
+ return hex;
152
+ }
153
+ return "#2968A8"; // default when unsure
154
+ }
155
+ export function validateDesign(schema, mode = "create") {
156
+ const errors = [];
157
+ const warnings = [];
158
+ const name = schema.name || "";
159
+ const information = schema.information || [];
160
+ const states = schema.states || [];
161
+ const activities = schema.activities || [];
162
+ const flows = schema.flows || [];
163
+ const isWorkflow = states.length > 0;
164
+ // Rule 1: name is required
165
+ if (!name && mode === "create") {
166
+ errors.push("Module name is required.");
167
+ }
168
+ // Collect field names
169
+ const fieldNames = new Set();
170
+ for (const f of information) {
171
+ if (fieldNames.has(f.name)) {
172
+ errors.push(`Duplicate field name: '${f.name}'.`);
173
+ }
174
+ fieldNames.add(f.name);
175
+ }
176
+ // Validate field types
177
+ for (const f of information) {
178
+ if (f.type && !isValidFieldType(f.type)) {
179
+ errors.push(`Field '${f.name}' has invalid type '${f.type}'. Valid types: ${VALID_FIELD_TYPES.join(", ")}.`);
180
+ }
181
+ // Table fields must have sub-fields
182
+ if (f.type === "Table") {
183
+ if (!f.fields || !Array.isArray(f.fields) || f.fields.length === 0) {
184
+ errors.push(`Table field '${f.name}' has no sub-fields defined.`);
185
+ }
186
+ else {
187
+ for (const sf of f.fields) {
188
+ if (sf.type && !isValidFieldType(sf.type)) {
189
+ errors.push(`Table field '${f.name}' sub-field '${sf.name}' has invalid type '${sf.type}'.`);
190
+ }
191
+ }
192
+ }
193
+ }
194
+ }
195
+ if (isWorkflow) {
196
+ // Rule 2: At least one state
197
+ // (already true since isWorkflow = states.length > 0)
198
+ // Rule 3: Exactly one initial state
199
+ const initialStates = states.filter((s) => s.initial === true);
200
+ if (initialStates.length === 0) {
201
+ errors.push("No initial state defined — exactly one state must have initial: true.");
202
+ }
203
+ else if (initialStates.length > 1) {
204
+ errors.push(`Multiple initial states: ${initialStates.map((s) => `'${s.name}'`).join(", ")}. Exactly one is allowed.`);
205
+ }
206
+ // Collect state names
207
+ const stateNames = new Set();
208
+ for (const s of states) {
209
+ if (stateNames.has(s.name)) {
210
+ errors.push(`Duplicate state name: '${s.name}'.`);
211
+ }
212
+ stateNames.add(s.name);
213
+ }
214
+ // Validate state colors
215
+ for (const s of states) {
216
+ if (s.color && !isValidColor(s.color)) {
217
+ errors.push(`State '${s.name}' has invalid color '${s.color}'. Valid colors: ${VALID_COLORS.join(", ")}.`);
218
+ }
219
+ if (!s.color) {
220
+ warnings.push(`State '${s.name}' has no color — will use default.`);
221
+ }
222
+ }
223
+ // Collect activity names
224
+ const activityNames = new Set();
225
+ for (const a of activities) {
226
+ if (activityNames.has(a.name)) {
227
+ errors.push(`Duplicate activity name: '${a.name}'.`);
228
+ }
229
+ activityNames.add(a.name);
230
+ }
231
+ // Validate activity properties
232
+ for (const a of activities) {
233
+ // Actor validation
234
+ if (a.actor && !isValidActor(a.actor)) {
235
+ errors.push(`Activity '${a.name}' has invalid actor '${a.actor}'. Valid: human, ai, hybrid.`);
236
+ }
237
+ // Confidence threshold
238
+ if (a.confidence_threshold !== undefined &&
239
+ a.confidence_threshold !== null) {
240
+ if (a.confidence_threshold < 0 || a.confidence_threshold > 1) {
241
+ errors.push(`Activity '${a.name}' confidence_threshold must be between 0 and 1.`);
242
+ }
243
+ }
244
+ // Activity field references
245
+ if (a.fields && Array.isArray(a.fields)) {
246
+ for (const ref of a.fields) {
247
+ const fieldName = typeof ref === "string" ? ref : ref.name;
248
+ if (!fieldNames.has(fieldName)) {
249
+ errors.push(`Activity '${a.name}' references field '${fieldName}' which is not defined in information. Available fields: ${[...fieldNames].join(", ")}.`);
250
+ }
251
+ }
252
+ }
253
+ // Warnings for AI actors
254
+ if (a.actor === "ai") {
255
+ if (!a.confidence_threshold &&
256
+ a.confidence_threshold !== 0) {
257
+ warnings.push(`Activity '${a.name}' has no confidence_threshold — AI agents will not be gated on this activity.`);
258
+ }
259
+ if (!a.ai_hint) {
260
+ warnings.push(`Activity '${a.name}' has actor 'ai' but no ai_hint — agents may struggle to execute correctly.`);
261
+ }
262
+ }
263
+ }
264
+ // Validate flows
265
+ for (const f of flows) {
266
+ if (f.from !== "" && !stateNames.has(f.from)) {
267
+ errors.push(`Flow references state '${f.from}' (from) which is not defined. Available states: ${[...stateNames].join(", ")}.`);
268
+ }
269
+ if (!stateNames.has(f.to)) {
270
+ errors.push(`Flow references state '${f.to}' (to) which is not defined. Available states: ${[...stateNames].join(", ")}.`);
271
+ }
272
+ if (!activityNames.has(f.activity)) {
273
+ errors.push(`Flow from '${f.from}' to '${f.to}' references activity '${f.activity}' which is not defined in activities. Available activities: ${[...activityNames].join(", ")}.`);
274
+ }
275
+ }
276
+ // Warning: unreachable states (no incoming flows, except initial)
277
+ const initialName = initialStates.length > 0 ? initialStates[0].name : "";
278
+ const statesWithIncoming = new Set(flows.map((f) => f.to));
279
+ for (const s of states) {
280
+ if (s.name !== initialName && !statesWithIncoming.has(s.name)) {
281
+ warnings.push(`State '${s.name}' is unreachable — no flows lead to it.`);
282
+ }
283
+ }
284
+ // Warning: unused activities
285
+ const activitiesInFlows = new Set(flows.map((f) => f.activity));
286
+ for (const a of activities) {
287
+ if (!activitiesInFlows.has(a.name)) {
288
+ warnings.push(`Activity '${a.name}' is not used in any flow.`);
289
+ }
290
+ }
291
+ // Warning: no terminal states
292
+ const statesWithOutgoing = new Set(flows.map((f) => f.from));
293
+ const terminalStates = states.filter((s) => !statesWithOutgoing.has(s.name));
294
+ if (terminalStates.length === 0) {
295
+ warnings.push("No terminal states — process may run indefinitely.");
296
+ }
297
+ // Build summary
298
+ const summary = {
299
+ field_count: information.length,
300
+ state_count: states.length,
301
+ activity_count: activities.length,
302
+ flow_count: flows.length,
303
+ initial_state: initialName,
304
+ terminal_states: terminalStates.map((s) => s.name),
305
+ ai_activities: activities.filter((a) => a.actor === "ai").length,
306
+ hybrid_activities: activities.filter((a) => a.actor === "hybrid")
307
+ .length,
308
+ gated_activities: activities.filter((a) => a.confidence_threshold && a.confidence_threshold > 0).length,
309
+ };
310
+ return {
311
+ valid: errors.length === 0,
312
+ errors,
313
+ warnings,
314
+ summary: errors.length === 0 ? summary : null,
315
+ };
316
+ }
317
+ // Record list module — minimal validation
318
+ return {
319
+ valid: errors.length === 0,
320
+ errors,
321
+ warnings,
322
+ summary: errors.length === 0
323
+ ? { field_count: information.length, module_type: "record_list" }
324
+ : null,
325
+ };
326
+ }
327
+ const INDUSTRY_DEFAULTS = {
328
+ financial_services: {
329
+ confidence_threshold: 0.9,
330
+ audit_fields: ["Compliance Note", "Risk Score"],
331
+ actor_suggestion: "hybrid for all approval activities",
332
+ },
333
+ healthcare: {
334
+ confidence_threshold: 0.9,
335
+ audit_fields: ["Clinical Justification", "HIPAA Flag"],
336
+ actor_suggestion: "human for patient-affecting activities",
337
+ },
338
+ legal: {
339
+ confidence_threshold: 0.85,
340
+ audit_fields: ["Legal Review Note", "Privilege Flag"],
341
+ actor_suggestion: "hybrid for review activities",
342
+ },
343
+ hr: {
344
+ confidence_threshold: 0.8,
345
+ audit_fields: ["HR Note"],
346
+ actor_suggestion: "hybrid for approval activities",
347
+ },
348
+ procurement: {
349
+ confidence_threshold: 0.8,
350
+ audit_fields: ["Budget Code", "PO Reference"],
351
+ actor_suggestion: "ai for matching/validation activities",
352
+ },
353
+ it_service: {
354
+ confidence_threshold: 0.7,
355
+ audit_fields: ["Resolution Note"],
356
+ actor_suggestion: "ai for triage activities",
357
+ },
358
+ general: {
359
+ confidence_threshold: 0.8,
360
+ audit_fields: [],
361
+ actor_suggestion: "human default",
362
+ },
363
+ };
364
+ function detectPattern(desc) {
365
+ const d = desc.toLowerCase();
366
+ if (d.includes("list") ||
367
+ d.includes("directory") ||
368
+ d.includes("catalog") ||
369
+ d.includes("registry") ||
370
+ d.includes("lookup")) {
371
+ return "record_list";
372
+ }
373
+ if (d.includes("ticket") ||
374
+ d.includes("support") ||
375
+ d.includes("issue") ||
376
+ d.includes("incident") ||
377
+ d.includes("service")) {
378
+ return "ticket_management";
379
+ }
380
+ if (d.includes("pipeline") ||
381
+ d.includes("stage") ||
382
+ d.includes("onboard") ||
383
+ d.includes("multi")) {
384
+ return "multi_stage_pipeline";
385
+ }
386
+ return "approval_workflow";
387
+ }
388
+ export function designWorkflow(description, industry = "general") {
389
+ const pattern = detectPattern(description);
390
+ const indDefaults = INDUSTRY_DEFAULTS[industry] || INDUSTRY_DEFAULTS.general;
391
+ if (pattern === "record_list") {
392
+ return {
393
+ template: {
394
+ name: "",
395
+ icon: "",
396
+ description: "",
397
+ information: [
398
+ { name: "Name", type: "Text", ai_hint: "" },
399
+ { name: "", type: "", ai_hint: "" },
400
+ ],
401
+ },
402
+ suggestions: {
403
+ detected_pattern: "record_list",
404
+ recommended_fields: ["Name", "Code", "Description", "Active"],
405
+ industry_defaults: indDefaults,
406
+ },
407
+ next_step: "Fill in the field definitions. Record list modules do not need states, activities, or flows. Then call validate_design.",
408
+ };
409
+ }
410
+ const baseStates = {
411
+ approval_workflow: [
412
+ { name: "Draft", color: "#5A6070", initial: true, ai_hint: "", ai_instruction: "" },
413
+ { name: "Pending Approval", color: "#2968A8", ai_hint: "", ai_instruction: "" },
414
+ { name: "Approved", color: "#1E6B45", ai_hint: "", ai_instruction: "" },
415
+ { name: "Rejected", color: "#8B2D2D", ai_hint: "", ai_instruction: "" },
416
+ ],
417
+ ticket_management: [
418
+ { name: "New", color: "#5A6070", initial: true, ai_hint: "", ai_instruction: "" },
419
+ { name: "Triaged", color: "#2968A8", ai_hint: "", ai_instruction: "" },
420
+ { name: "In Progress", color: "#2A7B50", ai_hint: "", ai_instruction: "" },
421
+ { name: "Resolved", color: "#1E6B45", ai_hint: "", ai_instruction: "" },
422
+ { name: "Closed", color: "#1E6B45", ai_hint: "", ai_instruction: "" },
423
+ ],
424
+ multi_stage_pipeline: [
425
+ { name: "Not Started", color: "#5A6070", initial: true, ai_hint: "", ai_instruction: "" },
426
+ { name: "In Progress", color: "#2A7B50", ai_hint: "", ai_instruction: "" },
427
+ { name: "Review", color: "#2968A8", ai_hint: "", ai_instruction: "" },
428
+ { name: "Completed", color: "#1E6B45", ai_hint: "", ai_instruction: "" },
429
+ { name: "Cancelled", color: "#8B2D2D", ai_hint: "", ai_instruction: "" },
430
+ ],
431
+ record_list: [],
432
+ };
433
+ const baseActivities = {
434
+ approval_workflow: [
435
+ { name: "Submit", actor: "hybrid", fields: [], ai_hint: "", ai_instruction: "", confidence_threshold: 0 },
436
+ { name: "Approve", actor: "human", fields: [], ai_hint: "", ai_instruction: "", confidence_threshold: indDefaults.confidence_threshold },
437
+ { name: "Reject", actor: "human", fields: [], ai_hint: "", ai_instruction: "", confidence_threshold: 0 },
438
+ ],
439
+ ticket_management: [
440
+ { name: "Triage", actor: "hybrid", fields: [], ai_hint: "", ai_instruction: "", confidence_threshold: 0 },
441
+ { name: "Assign", actor: "human", fields: [], ai_hint: "", ai_instruction: "", confidence_threshold: 0 },
442
+ { name: "Resolve", actor: "human", fields: [], ai_hint: "", ai_instruction: "", confidence_threshold: 0 },
443
+ { name: "Close", actor: "human", fields: [], ai_hint: "", ai_instruction: "", confidence_threshold: 0 },
444
+ ],
445
+ multi_stage_pipeline: [
446
+ { name: "Start", actor: "human", fields: [], ai_hint: "", ai_instruction: "", confidence_threshold: 0 },
447
+ { name: "Submit for Review", actor: "hybrid", fields: [], ai_hint: "", ai_instruction: "", confidence_threshold: 0 },
448
+ { name: "Complete", actor: "human", fields: [], ai_hint: "", ai_instruction: "", confidence_threshold: 0 },
449
+ { name: "Cancel", actor: "human", fields: [], ai_hint: "", ai_instruction: "", confidence_threshold: 0 },
450
+ ],
451
+ record_list: [],
452
+ };
453
+ const baseFlows = {
454
+ approval_workflow: [
455
+ { from: "Draft", to: "Pending Approval", activity: "Submit" },
456
+ { from: "Pending Approval", to: "Approved", activity: "Approve" },
457
+ { from: "Pending Approval", to: "Rejected", activity: "Reject" },
458
+ ],
459
+ ticket_management: [
460
+ { from: "New", to: "Triaged", activity: "Triage" },
461
+ { from: "Triaged", to: "In Progress", activity: "Assign" },
462
+ { from: "In Progress", to: "Resolved", activity: "Resolve" },
463
+ { from: "Resolved", to: "Closed", activity: "Close" },
464
+ ],
465
+ multi_stage_pipeline: [
466
+ { from: "Not Started", to: "In Progress", activity: "Start" },
467
+ { from: "In Progress", to: "Review", activity: "Submit for Review" },
468
+ { from: "Review", to: "Completed", activity: "Complete" },
469
+ { from: "In Progress", to: "Cancelled", activity: "Cancel" },
470
+ ],
471
+ record_list: [],
472
+ };
473
+ const recommendedFields = {
474
+ approval_workflow: ["Title", "Requested By", "Amount", "Justification", "Attachments"],
475
+ ticket_management: ["Title", "Priority", "Category", "Assignee", "Description", "Attachments"],
476
+ multi_stage_pipeline: ["Title", "Owner", "Due Date", "Status Notes", "Attachments"],
477
+ record_list: [],
478
+ };
479
+ return {
480
+ template: {
481
+ name: "",
482
+ icon: "",
483
+ description: "",
484
+ published: true,
485
+ information: [
486
+ { name: "Title", type: "Text", ai_hint: "" },
487
+ { name: "", type: "", ai_hint: "" },
488
+ ],
489
+ states: baseStates[pattern],
490
+ activities: baseActivities[pattern],
491
+ flows: baseFlows[pattern],
492
+ },
493
+ suggestions: {
494
+ detected_pattern: pattern,
495
+ recommended_fields: recommendedFields[pattern],
496
+ recommended_states: baseStates[pattern].map((s) => s.name),
497
+ industry_defaults: {
498
+ confidence_threshold: indDefaults.confidence_threshold,
499
+ audit_fields: indDefaults.audit_fields,
500
+ actor_suggestion: indDefaults.actor_suggestion,
501
+ },
502
+ },
503
+ next_step: "Complete the template fields, then call validate_design with the finished schema.",
504
+ };
505
+ }
@@ -0,0 +1,76 @@
1
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
+ import { z } from "zod";
3
+ import { registerTools } from "./tools.js";
4
+ import { registerResources } from "./resources.js";
5
+ import { registerPrompts } from "./prompts.js";
6
+ import { requestContext } from "./context.js";
7
+ import { setUserMode } from "./mode-store.js";
8
+ export function createServer(initialMode) {
9
+ const server = new McpServer({
10
+ name: "inistate-mcp",
11
+ version: "1.0.0",
12
+ });
13
+ const { configureTools } = registerTools(server);
14
+ const { configureResources, frontendResources } = registerResources(server);
15
+ const { configurePrompts } = registerPrompts(server);
16
+ // Initial mode: per-request override > env var > configure default.
17
+ // Default exposes runtime CRUD + design (configure) tools on connect.
18
+ // INISTATE_MCP_MODE=runtime narrows to entry CRUD only.
19
+ // INISTATE_MCP_MODE=frontend adds the frontend-guide resource on top.
20
+ // initialMode lets the HTTP transport (stateless, fresh server per request)
21
+ // restore a per-user choice from the mode store.
22
+ const envMode = (process.env.INISTATE_MCP_MODE || "").toLowerCase();
23
+ const envResolved = envMode === "frontend"
24
+ ? "frontend"
25
+ : envMode === "runtime"
26
+ ? "runtime"
27
+ : "configure";
28
+ const startMode = initialMode ?? envResolved;
29
+ const startConfigure = startMode === "configure" || startMode === "frontend";
30
+ const startFrontend = startMode === "frontend";
31
+ if (!startConfigure) {
32
+ for (const t of configureTools)
33
+ t.disable();
34
+ for (const r of configureResources)
35
+ r.disable();
36
+ for (const p of configurePrompts)
37
+ p.disable();
38
+ }
39
+ if (!startFrontend) {
40
+ for (const r of frontendResources)
41
+ r.disable();
42
+ }
43
+ let currentMode = startMode;
44
+ server.registerTool("switch_mode", {
45
+ description: "Switch tool surface. 'configure' (default) exposes entry CRUD plus module design tools (create_module, update_module, design_workflow, validate_design, get_module_canvas, get_module_schema) and schema/configure and design-guide resources. 'runtime' narrows to entry CRUD only. 'frontend' is a superset of 'configure' that also exposes the inistate://frontend-guide resource — REST API reference for generating Vue/React UIs that call the Inistate API directly with a user-supplied token. Use 'frontend' when the user wants to build a custom UI (and optionally iterate on the schema in the same session). The tool/resource list refreshes via list_changed after this call.",
46
+ inputSchema: {
47
+ mode: z.enum(["runtime", "configure", "frontend"]).describe("Target mode"),
48
+ },
49
+ annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false, idempotentHint: true },
50
+ }, async ({ mode }) => {
51
+ const enableConfigure = mode === "configure" || mode === "frontend";
52
+ const enableFrontend = mode === "frontend";
53
+ for (const t of configureTools)
54
+ enableConfigure ? t.enable() : t.disable();
55
+ for (const r of configureResources)
56
+ enableConfigure ? r.enable() : r.disable();
57
+ for (const p of configurePrompts)
58
+ enableConfigure ? p.enable() : p.disable();
59
+ for (const r of frontendResources)
60
+ enableFrontend ? r.enable() : r.disable();
61
+ currentMode = mode;
62
+ // Persist across the stateless HTTP transport's per-request servers.
63
+ const userId = requestContext.getStore()?.userId;
64
+ if (userId)
65
+ setUserMode(userId, mode);
66
+ return {
67
+ content: [
68
+ {
69
+ type: "text",
70
+ text: JSON.stringify({ mode: currentMode, message: `Switched to ${mode} mode` }, null, 2),
71
+ },
72
+ ],
73
+ };
74
+ });
75
+ return server;
76
+ }