inistate-mcp 1.4.0 → 1.5.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/README.md CHANGED
@@ -85,7 +85,7 @@ Tools marked **(configure)** are only exposed in configure mode — see [Modes](
85
85
  | Tool | Description |
86
86
  |------|-------------|
87
87
  | `list_workspaces` | List workspaces the user has access to |
88
- | `set_workspace` | Set the active workspace |
88
+ | `set_workspace` | Look up a workspace by id or name and return its module list (stores nothing) |
89
89
  | `list_modules` | List all discoverable modules in the workspace |
90
90
  | `get_module_schema` | Get the canvas schema (basic or extended tier) — available in every mode |
91
91
  | `get_module_canvas` | Get full module definition with stable IDs (round-trippable) **(configure)** |
@@ -96,6 +96,7 @@ Tools marked **(configure)** are only exposed in configure mode — see [Modes](
96
96
  | `submit_activity` | Create, edit, delete, or run custom activities |
97
97
  | `submit_activities` | Bulk variant — same activity applied to up to 100 entries in one call |
98
98
  | `get_entry_history` | Get entry audit trail and comments |
99
+ | `get_document` | An entry's document, the system's own print or one designed in Inistate: a link that lasts up to an hour (default) or the file itself (max 4 MB) |
99
100
  | `request_upload_url` | Default upload path — get a presigned S3 URL to PUT file bytes to |
100
101
  | `confirm_upload` | Confirm a presigned upload completed; returns the File/Image field path |
101
102
  | `upload_file` | Fallback upload via base64/multipart (use only if the presigned flow fails) |
@@ -143,7 +144,7 @@ Tools and resources marked **(configure)** / **(frontend)** are absent from the
143
144
 
144
145
  ## Typical Workflow
145
146
 
146
- 1. `list_workspaces` → `set_workspace` — select a workspace (auto-selected when exactly one matches; both return the workspace's module list, so `list_modules` is only needed to refresh)
147
+ 1. `list_workspaces` → `set_workspace` — find the workspace (when exactly one matches, list_workspaces returns its module list itself; both return it, so `list_modules` is only needed to refresh). The server keeps no state between calls: pass `workspaceId` on every later call, unless `INISTATE_WORKSPACE_ID` is configured.
147
148
  2. `get_module_schema` — understand a module's fields, states, and activities
148
149
  3. `get_form` — discover required fields before the first submission per (module, activity); reuse its schema for further entries
149
150
  4. `submit_activity` — create or update entries (`submit_activities` for bulk)
@@ -226,7 +227,28 @@ mcp-publisher publish
226
227
  ## Deployment
227
228
 
228
229
  Deployment is done by hand; there is no CI deploy. After a release, update the server
229
- (see PM2 below): pull `production`, `npm ci`, `npm run build`, then `npm run pm2:restart`.
230
+ (see PM2 below):
231
+
232
+ ```bash
233
+ npm run update # git pull, npm ci only if the lockfile changed, then deploy
234
+ npm run rollback # if it went wrong after the fact: restores build-prev
235
+ ```
236
+
237
+ Do not run `npm run build` on the server while it is serving: it starts with `rimraf build`, and
238
+ pm2 runs the live server from `build/`, so the server is left on an empty or half-written folder
239
+ and stalls. (Installing no longer builds: there is no `prepare` script, only `prepublishOnly`.) `npm run deploy` (run by `npm run update`) compiles
240
+ into `build-next` and only renames folders once that succeeded; if the new build does not answer
241
+ `/health` it puts the previous one back.
242
+
243
+ `npm ci` also deletes `node_modules` while the server is running, so run it only when
244
+ dependencies changed, and follow it at once with `npm run deploy`.
245
+
246
+ The PM2 app runs in cluster mode with **one** instance, so `pm2 reload` starts the new process,
247
+ waits for it to report ready, then stops the old one (in-flight requests get 8 s to finish).
248
+ Keep `instances: 1`: the OAuth provider keeps pending logins and tokens in process memory, and a
249
+ login that reached two different workers would fail. After the first deploy of this change run
250
+ `pm2 delete inistate-mcp && npm run pm2:start && npx pm2 save` once, because an existing fork-mode
251
+ app does not switch to cluster mode on reload.
230
252
 
231
253
  ## PM2 (Ubuntu/AWS)
232
254
 
@@ -355,21 +355,13 @@ function checkSingleRef(field, type, value, index) {
355
355
  const valueOk = typeof obj.value === "string";
356
356
  const usernameOk = !isUserType ||
357
357
  (typeof obj.username === "string" && obj.username.length > 0);
358
- if (idOk && valueOk && usernameOk) {
359
- // A display name standing in for the id ({ id: "carol" }) passes the key
360
- // checks but the platform stores it as-is — a silently dangling reference.
361
- // Real ids are numeric or document ids ("CLN00001"); a string id with
362
- // whitespace or no digit at all is a name, not an id.
363
- if (typeof obj.id === "string" && (/\s/.test(obj.id) || !/\d/.test(obj.id))) {
364
- return {
365
- field,
366
- type,
367
- received: value,
368
- message: `${type} field '${locator}' id '${obj.id}' looks like a display name, not an entry id. Look up the entry with list_entries on the connected module and round-trip its reference object unchanged.`,
369
- };
370
- }
358
+ // Shape only: what an id looks like says nothing about whether it is one. A
359
+ // module whose records live in another system uses that system's own keys
360
+ // (HQ, KLG-WH, BANK), so the MCP never judges an id by its spelling. Whether
361
+ // it names an entry is the backend's call: it knows the connected module
362
+ // (KY 2026-11-14, "MCP must stay generic").
363
+ if (idOk && valueOk && usernameOk)
371
364
  return null;
372
- }
373
365
  const missing = [];
374
366
  if (!idOk)
375
367
  missing.push("id (string|number)");
package/build/api.d.ts CHANGED
@@ -1,10 +1,29 @@
1
+ /**
2
+ * A link the API handed out, under the configured API base. The API cannot see its own public origin behind its
3
+ * balancer (it once answered https://api.inistate.com:85/...), so whatever origin the link carries - none, an
4
+ * internal port, another host, protocol-relative - is dropped: only its path, query and fragment are kept.
5
+ */
6
+ export declare function absoluteUrl(link: string): string;
7
+ /**
8
+ * Point the current call at a workspace. The MCP keeps no state between calls: this writes the
9
+ * call's own request context — every tool call runs in one (tools.ts registerTool), as does every
10
+ * HTTP request — and it is gone when the call ends. There used to be a process-wide fallback for
11
+ * stdio, written by set_workspace and by any call that passed workspaceId, so one call silently
12
+ * re-pointed every later one (production, 2026-11-10: a peek at a workspace's copy made the
13
+ * original's Customer list 0 rows). Outside a call there is nothing to write to, so that is an error.
14
+ */
1
15
  export declare function setWorkspaceId(wsid: string): void;
16
+ /**
17
+ * The workspace the current call uses: its own (the tool's workspaceId, or the HTTP request's
18
+ * x-workspace-id header), else INISTATE_WORKSPACE_ID, else none — the server then resolves it
19
+ * (a member with only one workspace) or refuses.
20
+ */
2
21
  export declare function getWorkspaceId(): string | null;
3
22
  /**
4
23
  * A bare "Module 'X' not found" sends agents hunting across workspaces one
5
24
  * set_workspace at a time (observed: 7 calls to locate a module created in
6
- * the wrong workspace). Anchor the error to the active workspace and name
7
- * the two possible fixes.
25
+ * the wrong workspace). Anchor the error to the workspace this call used and
26
+ * name the two possible fixes.
8
27
  */
9
28
  export declare function annotateModuleNotFound(message: string): string;
10
29
  /**
package/build/api.js CHANGED
@@ -3,6 +3,16 @@ const BASE_URL = (process.env.INISTATE_API_BASE ||
3
3
  process.env.INISTATE_API_URL ||
4
4
  process.env.INISTATE_BASE_URL ||
5
5
  "https://api.inistate.com").replace(/\/+$/, "");
6
+ /**
7
+ * A link the API handed out, under the configured API base. The API cannot see its own public origin behind its
8
+ * balancer (it once answered https://api.inistate.com:85/...), so whatever origin the link carries - none, an
9
+ * internal port, another host, protocol-relative - is dropped: only its path, query and fragment are kept.
10
+ */
11
+ export function absoluteUrl(link) {
12
+ // A base resolves a bare or protocol-relative link too; its own origin is thrown away with the link's.
13
+ const u = new URL(link, "http://origin.invalid");
14
+ return `${BASE_URL}${u.pathname}${u.search}${u.hash}`;
15
+ }
6
16
  const LOG_ENABLED = process.env.INISTATE_LOG !== "0";
7
17
  function log(message, data) {
8
18
  if (!LOG_ENABLED)
@@ -20,29 +30,32 @@ function log(message, data) {
20
30
  const ENV_API_KEY = process.env.INISTATE_ACCESS_TOKEN ||
21
31
  process.env.INISTATE_API_TOKEN ||
22
32
  process.env.INISTATE_API_KEY;
23
- let workspaceId = process.env.INISTATE_WORKSPACE_ID ?? null;
33
+ /** The workspace a call uses when it names none: configuration, fixed for the life of the process. */
34
+ const ENV_WORKSPACE_ID = process.env.INISTATE_WORKSPACE_ID || null;
35
+ /**
36
+ * Point the current call at a workspace. The MCP keeps no state between calls: this writes the
37
+ * call's own request context — every tool call runs in one (tools.ts registerTool), as does every
38
+ * HTTP request — and it is gone when the call ends. There used to be a process-wide fallback for
39
+ * stdio, written by set_workspace and by any call that passed workspaceId, so one call silently
40
+ * re-pointed every later one (production, 2026-11-10: a peek at a workspace's copy made the
41
+ * original's Customer list 0 rows). Outside a call there is nothing to write to, so that is an error.
42
+ */
24
43
  export function setWorkspaceId(wsid) {
25
44
  const ctx = requestContext.getStore();
26
- if (ctx) {
27
- // HTTP mode: write to per-request context, not the global
28
- ctx.workspaceId = wsid;
45
+ if (!ctx) {
46
+ throw new Error("setWorkspaceId outside a tool call: the MCP keeps no workspace between calls.");
29
47
  }
30
- else {
31
- // stdio/session mode: write to the global
32
- workspaceId = wsid;
33
- }
34
- }
35
- export function getWorkspaceId() {
36
- return workspaceId;
48
+ ctx.workspaceId = wsid;
37
49
  }
38
50
  /**
39
- * Resolve the effective workspace ID.
40
- * Priority: per-request context header > tool param (via setWorkspaceId) > env var
51
+ * The workspace the current call uses: its own (the tool's workspaceId, or the HTTP request's
52
+ * x-workspace-id header), else INISTATE_WORKSPACE_ID, else none — the server then resolves it
53
+ * (a member with only one workspace) or refuses.
41
54
  */
42
- function effectiveWorkspaceId() {
43
- const ctx = requestContext.getStore();
44
- return ctx?.workspaceId || workspaceId;
55
+ export function getWorkspaceId() {
56
+ return requestContext.getStore()?.workspaceId || ENV_WORKSPACE_ID;
45
57
  }
58
+ const effectiveWorkspaceId = getWorkspaceId;
46
59
  /**
47
60
  * Resolve the effective Authorization header value.
48
61
  * Priority: per-request context header (HTTP/OAuth flow) > env API key (stdio).
@@ -76,16 +89,16 @@ function authHeader() {
76
89
  /**
77
90
  * A bare "Module 'X' not found" sends agents hunting across workspaces one
78
91
  * set_workspace at a time (observed: 7 calls to locate a module created in
79
- * the wrong workspace). Anchor the error to the active workspace and name
80
- * the two possible fixes.
92
+ * the wrong workspace). Anchor the error to the workspace this call used and
93
+ * name the two possible fixes.
81
94
  */
82
95
  export function annotateModuleNotFound(message) {
83
96
  if (!/^module '.+' not found\.?$/i.test(message.trim()))
84
97
  return message;
85
98
  const wsid = effectiveWorkspaceId();
86
99
  return wsid
87
- ? `${message.trim().replace(/\.$/, "")} in the active workspace (id ${wsid}). Check list_modules for the exact name, or call set_workspace if the module lives in another workspace.`
88
- : `${message.trim().replace(/\.$/, "")}. No active workspace is set — call set_workspace (or pass workspaceId) first.`;
100
+ ? `${message.trim().replace(/\.$/, "")} in workspace ${wsid}, the one this call used. Check list_modules for the exact name, or pass another workspaceId if the module lives in another workspace.`
101
+ : `${message.trim().replace(/\.$/, "")}. This call named no workspace, and the MCP keeps none between calls — pass workspaceId (list_workspaces lists them).`;
89
102
  }
90
103
  /**
91
104
  * The next step for the agent after an API error: the server's own when it sends one (it knows why, e.g. a
@@ -83,6 +83,11 @@ export interface Capabilities {
83
83
  * link or as the file. Absent or false: get_document returns a capability message.
84
84
  */
85
85
  documents?: boolean;
86
+ /**
87
+ * Re-linking a Module field to another module with its entries' values (relink_field), and update_module's pointer
88
+ * to it. Absent or false: relink_field is not registered.
89
+ */
90
+ relink?: boolean;
86
91
  }
87
92
  /** Who is writing a design: the provenance headers a configure write carries (see provenance.ts). */
88
93
  export type DesignWriteHeaders = Record<string, string>;
@@ -196,7 +201,10 @@ export interface Backend {
196
201
  /** Which backend this is — drives capability messages and diagnostics. */
197
202
  readonly kind: "local" | "cloud";
198
203
  capabilities(): Capabilities;
199
- /** Set the active workspace for subsequent calls. Context op, no I/O. */
204
+ /**
205
+ * Point the current tool call at a workspace. Context op, no I/O, and nothing outlives the
206
+ * call: the MCP keeps no workspace between calls.
207
+ */
200
208
  setActiveWorkspace(wsid: string): void;
201
209
  listWorkspaces(search?: string): Promise<unknown>;
202
210
  getWorkspace(workspaceId: string): Promise<unknown>;
@@ -236,6 +244,8 @@ export interface Backend {
236
244
  replayChange?(module: string, payload: Record<string, unknown>): Promise<unknown>;
237
245
  /** A module's design history (get_module_history). Only when capabilities().designRecord is true. */
238
246
  getModuleHistory?(params: GetModuleHistoryParams): Promise<unknown>;
247
+ /** Re-link a Module field to another module, its entries' values with it (relink_field). The Inistate Platform only. */
248
+ relinkField?(module: string, payload: Record<string, unknown>, provenance?: DesignWriteHeaders): Promise<unknown>;
239
249
  /** Only when capabilities().skills is true; optional so a backend without skills need not stub it. */
240
250
  getModuleSkill?(params: GetModuleSkillParams): Promise<unknown>;
241
251
  /** Only when capabilities().approvals is true; optional so other backends need not stub them. */
@@ -294,6 +304,7 @@ export declare class CloudBackend implements Backend {
294
304
  getApprovalRequest(requestId: string): Promise<unknown>;
295
305
  createModule(payload: Record<string, unknown>, provenance?: DesignWriteHeaders): Promise<unknown>;
296
306
  updateModule(payload: Record<string, unknown>, provenance?: DesignWriteHeaders): Promise<unknown>;
307
+ relinkField(module: string, payload: Record<string, unknown>, provenance?: DesignWriteHeaders): Promise<unknown>;
297
308
  listEntries(p: ListEntriesParams): Promise<unknown>;
298
309
  aggregateEntries(p: AggregateEntriesParams): Promise<unknown>;
299
310
  getEntry(p: GetEntryParams): Promise<unknown>;
package/build/backend.js CHANGED
@@ -37,10 +37,11 @@ export class CloudBackend {
37
37
  card: true,
38
38
  skills: true,
39
39
  approvals: true,
40
- automations: experimentalEnabled(),
40
+ automations: true,
41
41
  designRecord: true,
42
42
  designApprovals: true,
43
- documents: experimentalEnabled(),
43
+ documents: true,
44
+ relink: experimentalEnabled(),
44
45
  };
45
46
  }
46
47
  setActiveWorkspace(wsid) {
@@ -114,6 +115,9 @@ export class CloudBackend {
114
115
  updateModule(payload, provenance) {
115
116
  return api.put("/api/configure", payload, provenance);
116
117
  }
118
+ relinkField(module, payload, provenance) {
119
+ return api.post(`/api/configure/${api.enc(module)}/relink`, payload, provenance);
120
+ }
117
121
  listEntries(p) {
118
122
  const body = { module: p.module };
119
123
  if (p.listing)
@@ -201,7 +205,7 @@ export class CloudBackend {
201
205
  confirmUpload(p) {
202
206
  return api.post("/api/mcp/confirm-upload", { s3Key: p.s3Key });
203
207
  }
204
- getDocument(p) {
208
+ async getDocument(p) {
205
209
  // `as` travels only when given: without it the server picks (a link, or the file for an Inistate-designed document).
206
210
  const body = { module: p.module, entry: p.entry };
207
211
  if (p.document)
@@ -210,7 +214,13 @@ export class CloudBackend {
210
214
  body.format = p.format;
211
215
  if (p.as)
212
216
  body.as = p.as;
213
- return api.post("/api/mcp/document", body);
217
+ const data = await api.post("/api/mcp/document", body);
218
+ // The API answers the link as a path (/doc/link/...); it goes out under the configured API base.
219
+ if (data && typeof data === "object" && typeof data.link === "string") {
220
+ const d = data;
221
+ d.link = api.absoluteUrl(d.link);
222
+ }
223
+ return data;
214
224
  }
215
225
  // The hosted Platform designs modules directly and does not introspect
216
226
  // external stores; capabilities().scaffold is false, so the tool gates this
@@ -15,7 +15,7 @@
15
15
  * 2. Attribute the limit to the substrate, not to withholding.
16
16
  * No crippleware tone, no sales pitch beyond one factual `upgrade` line.
17
17
  */
18
- export type CapabilityCode = "workspaces" | "governed_history" | "files" | "authorization" | "frontend_guide" | "scaffold" | "skills" | "approvals" | "automations" | "design_history" | "documents";
18
+ export type CapabilityCode = "workspaces" | "governed_history" | "files" | "authorization" | "frontend_guide" | "scaffold" | "skills" | "approvals" | "automations" | "design_history" | "documents" | "relink";
19
19
  export interface CapabilityMessage {
20
20
  error: "capability_unavailable";
21
21
  backend: string;
@@ -27,6 +27,7 @@ const MESSAGES = {
27
27
  automations: "Automations are not available on this backend. Checking, testing and running a module's automations is a capability of the Inistate Platform.",
28
28
  design_history: "Module design history is not available on this backend. Who changed a module's design and why is kept by the Inistate Platform.",
29
29
  documents: "Documents are not available on this backend. Printing an entry's documents, a connected system's own or one designed in Inistate, is a capability of the Inistate Platform.",
30
+ relink: "Re-linking a field is not available on this backend. Moving a Module field and its entries' values to another module, with a backup and an undo, is a capability of the Inistate Platform.",
30
31
  };
31
32
  const UPGRADE = {
32
33
  workspaces: "Connect to the Inistate Platform to enable workspaces.",
@@ -40,6 +41,7 @@ const UPGRADE = {
40
41
  automations: "Connect to the Inistate Platform to design and run automations.",
41
42
  design_history: "Connect to the Inistate Platform to read a module's design history.",
42
43
  documents: "Connect to the Inistate Platform to get an entry's documents.",
44
+ relink: "Connect to the Inistate Platform to re-link a field.",
43
45
  };
44
46
  export function capabilityMessage(capability, backend = "local") {
45
47
  return {
@@ -13,5 +13,10 @@ export interface RequestContext {
13
13
  client?: string;
14
14
  /** The client's Mcp-Session-Id, when it sends one — groups one conversation's design saves */
15
15
  sessionId?: string;
16
+ /**
17
+ * Set by the HTTP transport. A stdio tool call runs in a context too (tools.ts registerTool:
18
+ * the MCP keeps no state between calls), so having a context no longer means HTTP.
19
+ */
20
+ overHttp?: boolean;
16
21
  }
17
22
  export declare const requestContext: AsyncLocalStorage<RequestContext>;
@@ -1,6 +1,6 @@
1
1
  /**
2
- * Tools still under test: automations (get_module_automations, save_automation, get_automation_runs,
3
- * replay_change, the inistate://schema/automation guide) and get_document. They are built and tested on main
4
- * but not registered unless INISTATE_MCP_EXPERIMENTAL=1, so a release can ship without them.
2
+ * Tools still under test: relink_field. It is built and tested on main but not registered unless
3
+ * INISTATE_MCP_EXPERIMENTAL=1, so a release can ship without it. (The automation tools, get_document and the
4
+ * automation guide were released and are no longer gated.)
5
5
  */
6
6
  export declare function experimentalEnabled(): boolean;
@@ -1,7 +1,7 @@
1
1
  /**
2
- * Tools still under test: automations (get_module_automations, save_automation, get_automation_runs,
3
- * replay_change, the inistate://schema/automation guide) and get_document. They are built and tested on main
4
- * but not registered unless INISTATE_MCP_EXPERIMENTAL=1, so a release can ship without them.
2
+ * Tools still under test: relink_field. It is built and tested on main but not registered unless
3
+ * INISTATE_MCP_EXPERIMENTAL=1, so a release can ship without it. (The automation tools, get_document and the
4
+ * automation guide were released and are no longer gated.)
5
5
  */
6
6
  export function experimentalEnabled() {
7
7
  return process.env.INISTATE_MCP_EXPERIMENTAL === "1";
package/build/http.js CHANGED
@@ -88,8 +88,14 @@ registerAppAuthorizeRoutes(app, oauthProvider, ISSUER_URL);
88
88
  /* ------------------------------------------------------------------ */
89
89
  /* Health check */
90
90
  /* ------------------------------------------------------------------ */
91
+ let shuttingDown = false;
92
+ const STARTED_AT = Date.now();
91
93
  app.get("/health", (_req, res) => {
92
- res.json({ status: "ok" });
94
+ if (shuttingDown) {
95
+ res.status(503).json({ status: "draining" });
96
+ return;
97
+ }
98
+ res.json({ status: "ok", uptimeSeconds: Math.round((Date.now() - STARTED_AT) / 1000) });
93
99
  });
94
100
  /* ------------------------------------------------------------------ */
95
101
  /* MCP endpoint (stateless) */
@@ -137,6 +143,7 @@ app.post("/mcp", express.raw({ type: "*/*", limit: "4mb" }), async (req, res) =>
137
143
  mode,
138
144
  client: req.headers["user-agent"] || undefined,
139
145
  sessionId: req.headers["mcp-session-id"] || undefined,
146
+ overHttp: true,
140
147
  };
141
148
  await requestContext.run(ctx, async () => {
142
149
  const transport = new StreamableHTTPServerTransport({
@@ -170,13 +177,39 @@ app.get("/.well-known/openai-apps-challenge", (_, res) => {
170
177
  /* ------------------------------------------------------------------ */
171
178
  /* Start */
172
179
  /* ------------------------------------------------------------------ */
173
- app.listen(PORT, () => {
180
+ const httpServer = app.listen(PORT, () => {
174
181
  console.log(`Inistate MCP HTTP server listening on port ${PORT}`);
175
182
  console.log(` MCP: POST http://localhost:${PORT}/mcp`);
176
183
  console.log(` OAuth: GET http://localhost:${PORT}/.well-known/oauth-authorization-server`);
177
184
  console.log(` Health: GET http://localhost:${PORT}/health`);
185
+ // pm2 (wait_ready) holds the old process until the new one says it is listening, so a
186
+ // `pm2 reload` never leaves a gap with nothing accepting requests.
187
+ process.send?.("ready");
178
188
  });
179
- process.on("SIGINT", () => {
180
- console.log("Shutting down...");
181
- process.exit(0);
182
- });
189
+ /* ------------------------------------------------------------------ */
190
+ /* Graceful shutdown */
191
+ /* ------------------------------------------------------------------ */
192
+ // A restart used to be process.exit(0) on SIGINT only (pm2 sends SIGINT, then SIGKILL), which cut
193
+ // in-flight tool calls off. Now: stop accepting, let running requests finish, then exit. /health
194
+ // answers 503 while draining so a load balancer or deploy script stops sending new work.
195
+ const SHUTDOWN_GRACE_MS = Number(process.env.SHUTDOWN_GRACE_MS) || 8000; // keep below pm2 kill_timeout
196
+ function shutdown(signal) {
197
+ if (shuttingDown)
198
+ return;
199
+ shuttingDown = true;
200
+ console.log(`${signal} received, draining (up to ${SHUTDOWN_GRACE_MS} ms)...`);
201
+ httpServer.close((err) => {
202
+ if (err)
203
+ console.error("Error while closing the HTTP server:", err);
204
+ console.log("Drained, exiting.");
205
+ process.exit(err ? 1 : 0);
206
+ });
207
+ httpServer.closeIdleConnections();
208
+ setTimeout(() => {
209
+ console.error("Grace period over, closing remaining connections.");
210
+ httpServer.closeAllConnections();
211
+ process.exit(0);
212
+ }, SHUTDOWN_GRACE_MS).unref();
213
+ }
214
+ process.on("SIGINT", () => shutdown("SIGINT"));
215
+ process.on("SIGTERM", () => shutdown("SIGTERM"));
package/build/prompts.js CHANGED
@@ -1,5 +1,4 @@
1
1
  import { z } from "zod";
2
- import { experimentalEnabled } from "./experimental.js";
3
2
  export function registerPrompts(server) {
4
3
  const configurePrompts = [];
5
4
  // 1. design_factsops_workflow (configure mode)
@@ -168,8 +167,8 @@ Rules:
168
167
  - Load inistate://schema/configure resource if you need valid field types, colors, or actor types
169
168
  - Access rules are changed with set_module_access, never through update_module (read them with get_module_access). A position grant is {"profileField": "Position", "in": ["Manager"]}. Preview with dryRun, show the user the changes, and confirm with them before anything that lets more people in
170
169
  - Listings (which entries people see, e.g. "own records only") are made and changed one at a time with save_listing, never through update_module
171
- ${experimentalEnabled() ? `
172
- - Automations are read with get_module_automations and saved one at a time with save_automation, with the tests that prove them, never through update_module. Dry-run first; switching one on needs its tests passing and the user's explicit yes` : ""}`,
170
+
171
+ - Automations are read with get_module_automations and saved one at a time with save_automation, with the tests that prove them, never through update_module. Dry-run first; switching one on needs its tests passing and the user's explicit yes`,
173
172
  },
174
173
  },
175
174
  ],
@@ -25,7 +25,8 @@ export function designWriteHeaders(client) {
25
25
  const headers = {
26
26
  [CLIENT_HEADER]: headerValue(named ?? ctx?.client ?? "mcp-client") || "mcp-client",
27
27
  };
28
- const session = ctx ? ctx.sessionId : processSession;
28
+ // Every tool call has a context (stdio too), so ask the transport, not whether one exists.
29
+ const session = ctx?.overHttp ? ctx.sessionId : processSession;
29
30
  if (session)
30
31
  headers[SESSION_HEADER] = headerValue(session);
31
32
  return headers;
package/build/server.js CHANGED
@@ -9,6 +9,7 @@ import { requestContext } from "./context.js";
9
9
  import { setUserMode } from "./mode-store.js";
10
10
  import { CloudBackend } from "./backend.js";
11
11
  import { capabilityMessage } from "./capability.js";
12
+ import { strictArguments } from "./strict-arguments.js";
12
13
  export function createServer(options = {}) {
13
14
  const { backend = new CloudBackend(), initialMode, name = "inistate-mcp", version = pkgVersion } = options;
14
15
  const caps = backend.capabilities();
@@ -16,7 +17,7 @@ export function createServer(options = {}) {
16
17
  // MCP instructions surface it as context). Encodes the canonical flows so
17
18
  // agents don't spend turns rediscovering them.
18
19
  const instructions = `Inistate MCP — canonical flows (minimize tool calls):
19
- - Orient: list_workspaces (auto-selects if exactly one match) -> set_workspace. Both return the workspace's module list; list_modules is only for refreshing it.
20
+ - Orient: list_workspaces (returns the module list itself when exactly one workspace matches) or set_workspace (looks one up by id or name). Both return the workspace's module list; list_modules is only for refreshing it. The MCP keeps no state between calls: pass workspaceId on every call (omit it only when INISTATE_WORKSPACE_ID is configured).
20
21
  - Read: list_entries with the fields parameter (keeps payloads small) and filters; get_entry for one record; aggregate_entries for counts and totals (never add up list_entries pages).
21
22
  - Write: get_form once per (module, activity), then submit_activity; reuse the form schema for more entries of the same kind. Use submit_activities for bulk writes (max 100 per call).
22
23
  - Design: design_workflow -> create_module (validates internally; validate_design is an optional dry-run). Modify: get_module_canvas -> edit -> update_module (full-canvas payloads validate internally). Who can do what: get_module_access -> set_module_access (dryRun first; confirmed only after the user approves a widening); which entries people see: save_listing.${caps.automations ? " Automations: get_module_automations -> save_automation with its tests (dryRun first; a new one is saved off, and switching on needs its tests passing and confirmed:true after the admin's yes) -> get_automation_runs to watch its first live runs." : ""}${caps.designRecord ? " Every create_module / update_module carries ai.reasoning (why the design changes, kept in the module history); before changing or removing an existing item, read get_module_history — a recent change with a stated reason is a decision, so ask before undoing it." : ""}${caps.designApprovals ? " A design write answered design_approval_required needs a person: report the reasons and offer to send it with approval; never send unasked." : ""}
@@ -59,9 +60,11 @@ export function createServer(options = {}) {
59
60
  let currentMode = startMode;
60
61
  server.registerTool("switch_mode", {
61
62
  description: "Switch tool surface. 'configure' (default) = entry CRUD + module design tools and design resources. 'runtime' = entry CRUD plus get_module_schema (available in every mode). 'frontend' = configure + the inistate://frontend-guide resource (REST reference for building Vue/React UIs that call the Inistate API directly) — use it when the user wants a custom UI. The tool/resource list refreshes via list_changed after this call.",
62
- inputSchema: {
63
+ // Registered here rather than through tools.ts registerTool, so it refuses an unknown argument
64
+ // the same way (strict-arguments.ts); its handler reads only `mode`.
65
+ inputSchema: strictArguments("switch_mode", {
63
66
  mode: z.enum(["runtime", "configure", "frontend"]).describe("Target mode"),
64
- },
67
+ }).schema,
65
68
  annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false, idempotentHint: true },
66
69
  }, async ({ mode }) => {
67
70
  if (!caps.modes.includes(mode)) {
@@ -0,0 +1,20 @@
1
+ /**
2
+ * The argument an unknown name most likely meant, or undefined when none is close: the same name
3
+ * spelt another way (entry_id → entryId), a word for a write's values (payload → input), or a typo
4
+ * within two edits (one for a name of four letters or fewer).
5
+ */
6
+ export declare function closestArgument(unknown: string, known: readonly string[]): string | undefined;
7
+ /** The refusal an agent reads: which names are not arguments, what each likely meant, and the tool's arguments. */
8
+ export declare function unknownArgumentsMessage(tool: string, unknown: readonly string[], known: readonly string[]): string;
9
+ export interface StrictArguments {
10
+ /** The inputSchema to register: the same arguments, refusing any other. Unchanged when it has no argument shape. */
11
+ schema: unknown;
12
+ /** The tool does not declare workspaceId, so it was added as accepted-and-ignored: drop it before the handler. */
13
+ ignoresWorkspaceId: boolean;
14
+ }
15
+ /**
16
+ * A tool's inputSchema that refuses an argument it does not have, naming the closest real one. The
17
+ * advertised JSON Schema is the same as before (additionalProperties: false either way), apart from
18
+ * workspaceId on a tool that had no use for it.
19
+ */
20
+ export declare function strictArguments(tool: string, schema: unknown): StrictArguments;
@@ -0,0 +1,112 @@
1
+ import { z } from "zod";
2
+ /**
3
+ * Every tool refuses an argument it does not have (KY 2026-11-14, "MCP must stay generic").
4
+ *
5
+ * Why: zod's default object parsing STRIPS unknown keys, while tools/list advertises every input
6
+ * schema with additionalProperties: false. So a misnamed argument vanished without a word and the
7
+ * call went ahead without it: submit_activity { module, payload: {...} } (for `input`) created an
8
+ * entry with no values and answered success. On any tool, a typo in an argument's name changed what
9
+ * the call did, and the agent had no way to notice.
10
+ *
11
+ * The check is of top-level argument names only. What an argument holds keeps its own rules: an
12
+ * open map (input's fields, a canvas part declared .passthrough()) stays open.
13
+ *
14
+ * workspaceId is the one argument any call may carry (the server instructions ask for it on every
15
+ * call), so a tool that has no use for it accepts it and its handler never sees it.
16
+ */
17
+ const WORKSPACE_ID = "workspaceId";
18
+ /** Words agents use for the argument that carries a write's values. */
19
+ const VALUE_WORDS = new Set([
20
+ "input", "inputs", "items", "payload", "data", "values", "fields", "body", "form", "record", "params", "arguments", "args",
21
+ ]);
22
+ /** The arguments that do carry a write's values, in the order a suggestion prefers them. */
23
+ const VALUE_ARGUMENTS = ["input", "items"];
24
+ const squash = (key) => key.toLowerCase().replace(/[^a-z0-9]/g, "");
25
+ function editDistance(a, b) {
26
+ const row = Array.from({ length: b.length + 1 }, (_, j) => j);
27
+ for (let i = 1; i <= a.length; i++) {
28
+ let diagonal = row[0];
29
+ row[0] = i;
30
+ for (let j = 1; j <= b.length; j++) {
31
+ const above = row[j];
32
+ row[j] = Math.min(row[j] + 1, row[j - 1] + 1, diagonal + (a[i - 1] === b[j - 1] ? 0 : 1));
33
+ diagonal = above;
34
+ }
35
+ }
36
+ return row[b.length];
37
+ }
38
+ /**
39
+ * The argument an unknown name most likely meant, or undefined when none is close: the same name
40
+ * spelt another way (entry_id → entryId), a word for a write's values (payload → input), or a typo
41
+ * within two edits (one for a name of four letters or fewer).
42
+ */
43
+ export function closestArgument(unknown, known) {
44
+ const name = squash(unknown);
45
+ const same = known.find((k) => squash(k) === name);
46
+ if (same)
47
+ return same;
48
+ if (VALUE_WORDS.has(name)) {
49
+ const carrier = VALUE_ARGUMENTS.find((k) => known.includes(k));
50
+ if (carrier)
51
+ return carrier;
52
+ }
53
+ let best;
54
+ let bestDistance = Infinity;
55
+ for (const k of known) {
56
+ const d = editDistance(name, squash(k));
57
+ if (d < bestDistance) {
58
+ best = k;
59
+ bestDistance = d;
60
+ }
61
+ }
62
+ return bestDistance <= (name.length <= 4 ? 1 : 2) ? best : undefined;
63
+ }
64
+ /** The refusal an agent reads: which names are not arguments, what each likely meant, and the tool's arguments. */
65
+ export function unknownArgumentsMessage(tool, unknown, known) {
66
+ const quoted = unknown.map((k) => `'${k}'`).join(", ");
67
+ const guesses = unknown
68
+ .map((k) => [k, closestArgument(k, known)])
69
+ .filter((pair) => pair[1] !== undefined)
70
+ .map(([k, meant]) => (unknown.length === 1 ? `did you mean '${meant}'?` : `'${meant}' for '${k}'?`));
71
+ const lead = unknown.length === 1
72
+ ? `${quoted} is not an argument of ${tool}`
73
+ : `${quoted} are not arguments of ${tool}`;
74
+ const guess = guesses.length === 0 ? "." : unknown.length === 1 ? `; ${guesses[0]}` : `; did you mean ${guesses.join(", ")}`;
75
+ return `${lead}${guess} Nothing was done. Resend the call with ${tool}'s own arguments: ${known.join(", ")}.`;
76
+ }
77
+ const isZodType = (v) => typeof v === "object" && v !== null && "_def" in v && typeof v.safeParse === "function";
78
+ /** The argument shape of a tool's inputSchema: a raw shape, or a z.object that strips (the default). */
79
+ function shapeOf(schema) {
80
+ if (schema instanceof z.ZodObject) {
81
+ return schema._def.unknownKeys === "strip" ? schema.shape : undefined;
82
+ }
83
+ if (typeof schema !== "object" || schema === null || isZodType(schema))
84
+ return undefined;
85
+ const values = Object.values(schema);
86
+ return values.length > 0 && values.every(isZodType) ? schema : undefined;
87
+ }
88
+ /**
89
+ * A tool's inputSchema that refuses an argument it does not have, naming the closest real one. The
90
+ * advertised JSON Schema is the same as before (additionalProperties: false either way), apart from
91
+ * workspaceId on a tool that had no use for it.
92
+ */
93
+ export function strictArguments(tool, schema) {
94
+ const shape = shapeOf(schema);
95
+ if (!shape)
96
+ return { schema, ignoresWorkspaceId: false };
97
+ const known = Object.keys(shape);
98
+ const ignoresWorkspaceId = !known.includes(WORKSPACE_ID);
99
+ const full = ignoresWorkspaceId
100
+ ? {
101
+ ...shape,
102
+ [WORKSPACE_ID]: z
103
+ .union([z.string(), z.number()])
104
+ .optional()
105
+ .describe("Not used by this tool: accepted, and ignored, so a call that carries it is not refused."),
106
+ }
107
+ : shape;
108
+ const errorMap = (issue, ctx) => issue.code === z.ZodIssueCode.unrecognized_keys
109
+ ? { message: unknownArgumentsMessage(tool, issue.keys, known) }
110
+ : { message: ctx.defaultError };
111
+ return { schema: z.object(full, { errorMap }).strict(), ignoresWorkspaceId };
112
+ }