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,237 @@
1
+ import { randomUUID } from "node:crypto";
2
+ const CODE_TTL_MS = 5 * 60 * 1000; // 5 minutes
3
+ /** Decode a JWT payload without verifying the signature. Returns `undefined` if malformed. */
4
+ function decodeJwtExp(jwt) {
5
+ const parts = jwt.split(".");
6
+ if (parts.length < 2)
7
+ return undefined;
8
+ try {
9
+ const payload = Buffer.from(parts[1], "base64url").toString("utf8");
10
+ const claims = JSON.parse(payload);
11
+ return typeof claims.exp === "number" ? claims.exp : undefined;
12
+ }
13
+ catch {
14
+ return undefined;
15
+ }
16
+ }
17
+ /** Decode the `sub` claim from a JWT payload without verifying the signature. */
18
+ export function decodeJwtSub(jwt) {
19
+ const parts = jwt.split(".");
20
+ if (parts.length < 2)
21
+ return undefined;
22
+ try {
23
+ const payload = Buffer.from(parts[1], "base64url").toString("utf8");
24
+ const claims = JSON.parse(payload);
25
+ return typeof claims.sub === "string" ? claims.sub : undefined;
26
+ }
27
+ catch {
28
+ return undefined;
29
+ }
30
+ }
31
+ function expiresInFromExp(exp) {
32
+ if (exp === undefined)
33
+ return undefined;
34
+ const remaining = exp - Math.floor(Date.now() / 1000);
35
+ return remaining > 0 ? remaining : 0;
36
+ }
37
+ class InMemoryClientsStore {
38
+ clients = new Map();
39
+ getClient(clientId) {
40
+ return this.clients.get(clientId);
41
+ }
42
+ registerClient(client) {
43
+ const full = {
44
+ ...client,
45
+ client_id: randomUUID(),
46
+ client_id_issued_at: Math.floor(Date.now() / 1000),
47
+ };
48
+ this.clients.set(full.client_id, full);
49
+ return full;
50
+ }
51
+ }
52
+ /* ------------------------------------------------------------------ */
53
+ /* Provider */
54
+ /* ------------------------------------------------------------------ */
55
+ export class InistateOAuthProvider {
56
+ clientsStore;
57
+ codes = new Map();
58
+ pendingAuth = new Map();
59
+ tokens = new Map();
60
+ baseUrl;
61
+ appUrl;
62
+ mcpUrl;
63
+ loginPath;
64
+ constructor(inistateBaseUrl, appUrl, mcpUrl, loginPath = "/#/login") {
65
+ this.clientsStore = new InMemoryClientsStore();
66
+ this.baseUrl = inistateBaseUrl;
67
+ this.appUrl = appUrl.replace(/\/$/, "");
68
+ this.mcpUrl = mcpUrl;
69
+ this.loginPath = loginPath.startsWith("/") ? loginPath : `/${loginPath}`;
70
+ // Periodic cleanup of expired codes and pending auths
71
+ setInterval(() => this.cleanup(), 60_000);
72
+ }
73
+ /* ---- authorize: redirect to app.inistate.com login ---- */
74
+ async authorize(client, params, res) {
75
+ const nonce = randomUUID();
76
+ this.pendingAuth.set(nonce, {
77
+ clientId: client.client_id,
78
+ params,
79
+ createdAt: Date.now(),
80
+ });
81
+ // Redirect to the app's login page with MCP callback params.
82
+ // The path is configurable via INISTATE_APP_LOGIN_PATH; defaults to "/#/login"
83
+ // (Vue hash routing places query params after the hash).
84
+ // mcp_client_name is forwarded so the login banner can read e.g.
85
+ // "Sign in to authorize Claude" instead of "authorize mcp.inistate.com".
86
+ // The name comes from DCR (RFC 7591), so it's client-supplied — Vue must
87
+ // treat it as untrusted display text (no HTML, length-cap on render side).
88
+ const callbackUrl = `${this.mcpUrl}/authorize/callback`;
89
+ const query = new URLSearchParams({
90
+ mcp_nonce: nonce,
91
+ mcp_callback: callbackUrl,
92
+ });
93
+ if (client.client_name) {
94
+ query.set("mcp_client_name", client.client_name);
95
+ }
96
+ const loginUrl = `${this.appUrl}${this.loginPath}?${query.toString()}`;
97
+ res.redirect(302, loginUrl);
98
+ }
99
+ /**
100
+ * Called by the /authorize/callback route after the user logs in.
101
+ * Returns the redirect URL with the authorization code.
102
+ */
103
+ completeAuthorization(nonce, jwt, refreshToken) {
104
+ const pending = this.pendingAuth.get(nonce);
105
+ if (!pending)
106
+ throw new Error("Invalid or expired authorization nonce");
107
+ if (Date.now() - pending.createdAt > CODE_TTL_MS) {
108
+ this.pendingAuth.delete(nonce);
109
+ throw new Error("Authorization session expired");
110
+ }
111
+ this.pendingAuth.delete(nonce);
112
+ const code = randomUUID();
113
+ this.codes.set(code, {
114
+ codeChallenge: pending.params.codeChallenge,
115
+ redirectUri: pending.params.redirectUri,
116
+ clientId: pending.clientId,
117
+ state: pending.params.state,
118
+ jwt,
119
+ refreshToken,
120
+ createdAt: Date.now(),
121
+ });
122
+ const url = new URL(pending.params.redirectUri);
123
+ url.searchParams.set("code", code);
124
+ if (pending.params.state)
125
+ url.searchParams.set("state", pending.params.state);
126
+ return { redirectUrl: url.toString() };
127
+ }
128
+ /* ---- PKCE ---- */
129
+ async challengeForAuthorizationCode(_client, authorizationCode) {
130
+ const stored = this.codes.get(authorizationCode);
131
+ if (!stored)
132
+ throw new Error("Unknown authorization code");
133
+ return stored.codeChallenge;
134
+ }
135
+ /* ---- Token exchange ---- */
136
+ async exchangeAuthorizationCode(client, authorizationCode) {
137
+ const stored = this.codes.get(authorizationCode);
138
+ if (!stored)
139
+ throw new Error("Unknown or expired authorization code");
140
+ if (stored.clientId !== client.client_id)
141
+ throw new Error("Client mismatch");
142
+ if (Date.now() - stored.createdAt > CODE_TTL_MS) {
143
+ this.codes.delete(authorizationCode);
144
+ throw new Error("Authorization code expired");
145
+ }
146
+ // Single-use
147
+ this.codes.delete(authorizationCode);
148
+ // Track the token for verification
149
+ this.tokens.set(stored.jwt, {
150
+ clientId: client.client_id,
151
+ jwt: stored.jwt,
152
+ createdAt: Date.now(),
153
+ });
154
+ const tokens = {
155
+ access_token: stored.jwt,
156
+ token_type: "bearer",
157
+ };
158
+ const expiresIn = expiresInFromExp(decodeJwtExp(stored.jwt));
159
+ if (expiresIn !== undefined)
160
+ tokens.expires_in = expiresIn;
161
+ if (stored.refreshToken)
162
+ tokens.refresh_token = stored.refreshToken;
163
+ return tokens;
164
+ }
165
+ /* ---- Refresh ---- */
166
+ async exchangeRefreshToken(_client, refreshToken) {
167
+ // Forward to Inistate /token with grant_type=refresh_token
168
+ const params = new URLSearchParams();
169
+ params.set("grant_type", "refresh_token");
170
+ params.set("refresh_token", refreshToken);
171
+ const res = await fetch(`${this.baseUrl}/token`, {
172
+ method: "POST",
173
+ headers: { "Content-Type": "application/x-www-form-urlencoded", Accept: "application/json" },
174
+ body: params.toString(),
175
+ });
176
+ if (!res.ok) {
177
+ const text = await res.text();
178
+ throw new Error(`Token refresh failed: ${text}`);
179
+ }
180
+ const data = (await res.json());
181
+ const token = (data.token ?? data.access_token ?? data.jwt);
182
+ this.tokens.set(token, {
183
+ clientId: _client.client_id,
184
+ jwt: token,
185
+ createdAt: Date.now(),
186
+ });
187
+ const tokens = {
188
+ access_token: token,
189
+ token_type: "bearer",
190
+ };
191
+ const expiresIn = expiresInFromExp(decodeJwtExp(token));
192
+ if (expiresIn !== undefined)
193
+ tokens.expires_in = expiresIn;
194
+ const rt = data.refreshToken ?? data.refresh_token;
195
+ if (typeof rt === "string")
196
+ tokens.refresh_token = rt;
197
+ return tokens;
198
+ }
199
+ /* ---- Token verification ---- */
200
+ async verifyAccessToken(token) {
201
+ const expiresAt = decodeJwtExp(token);
202
+ // Check our in-memory store first
203
+ const stored = this.tokens.get(token);
204
+ if (stored) {
205
+ return {
206
+ token,
207
+ clientId: stored.clientId,
208
+ scopes: [],
209
+ ...(expiresAt !== undefined ? { expiresAt } : {}),
210
+ };
211
+ }
212
+ // For tokens not issued through OAuth (e.g. direct API key / legacy),
213
+ // accept them but mark with a generic clientId
214
+ return {
215
+ token,
216
+ clientId: "legacy",
217
+ scopes: [],
218
+ ...(expiresAt !== undefined ? { expiresAt } : {}),
219
+ };
220
+ }
221
+ /* ---- Revocation ---- */
222
+ async revokeToken(_client, request) {
223
+ this.tokens.delete(request.token);
224
+ }
225
+ /* ---- Cleanup ---- */
226
+ cleanup() {
227
+ const now = Date.now();
228
+ for (const [key, val] of this.codes) {
229
+ if (now - val.createdAt > CODE_TTL_MS)
230
+ this.codes.delete(key);
231
+ }
232
+ for (const [key, val] of this.pendingAuth) {
233
+ if (now - val.createdAt > CODE_TTL_MS)
234
+ this.pendingAuth.delete(key);
235
+ }
236
+ }
237
+ }
@@ -0,0 +1,172 @@
1
+ import { z } from "zod";
2
+ export function registerPrompts(server) {
3
+ const configurePrompts = [];
4
+ // 1. design_factsops_workflow (configure mode)
5
+ configurePrompts.push(server.registerPrompt("design_factsops_workflow", {
6
+ description: "Guide an AI agent through designing a complete FACTSOps workflow module from scratch.",
7
+ argsSchema: {
8
+ entity: z
9
+ .string()
10
+ .describe("What entity is this workflow about? (e.g., 'leave request', 'invoice', 'KYC application')"),
11
+ industry: z
12
+ .string()
13
+ .optional()
14
+ .describe("Industry context for compliance-aware defaults"),
15
+ },
16
+ }, async ({ entity, industry }) => {
17
+ const industryLine = industry
18
+ ? `\nIndustry context: ${industry}. Apply compliance-aware defaults for this industry.`
19
+ : "";
20
+ return {
21
+ messages: [
22
+ {
23
+ role: "user",
24
+ content: {
25
+ type: "text",
26
+ text: `You are designing a FACTSOps workflow module for: ${entity}${industryLine}
27
+
28
+ Follow this sequence:
29
+ 1. Define the entity's information fields (what data is captured)
30
+ 2. Define the lifecycle states (where the entity can be)
31
+ 3. Define activities (what actions move the entity between states)
32
+ 4. Define flows (which activities connect which states)
33
+ 5. Assign actor types to each activity (human, ai, hybrid)
34
+ 6. Set confidence thresholds for AI-executed activities
35
+ 7. Add ai_hints to guide AI agents
36
+ 8. Assign state colors using the FACTSOps color system:
37
+ - #5A6070 (grey) = not started, idle, queued
38
+ - #2968A8 (blue) = waiting for action, no urgency
39
+ - #2A7B50 (green) = active work in progress
40
+ - #A07828 (amber) = deadline approaching, flagged
41
+ - #C0392B (red) = SLA breached, escalation required
42
+ - #6B4D91 (purple) = blocked by external dependency
43
+ - #1E6B45 (dark green) = terminal success
44
+ - #8B2D2D (dark red) = terminal failure
45
+
46
+ Rules:
47
+ - Every activity must be referenced by at least one flow
48
+ - Every activity field must reference a field defined in information
49
+ - Exactly one state must be initial
50
+ - Terminal states need no outgoing flows
51
+ - Use the Three Laws: No transition without a form. No actor without a trail. No automation without escalation.
52
+
53
+ Use these tools in sequence:
54
+ 1. Call design_workflow with a description synthesized from user answers
55
+ 2. Complete the returned template
56
+ 3. Call validate_design to check for errors
57
+ 4. Present the schema to the user for review
58
+ 5. Call create_module to persist it
59
+ 6. Call get_module_schema to confirm
60
+
61
+ Output a complete ModuleSchema JSON object.`,
62
+ },
63
+ },
64
+ ],
65
+ };
66
+ }));
67
+ // 2. execute_activity (always on)
68
+ server.registerPrompt("execute_activity", {
69
+ description: "Guide an AI agent through executing a specific activity on an entry.",
70
+ argsSchema: {
71
+ module: z.string().describe("Module name"),
72
+ activity: z.string().describe("Activity to execute"),
73
+ entryId: z
74
+ .string()
75
+ .optional()
76
+ .describe("Entry ID (omit for create)"),
77
+ },
78
+ }, async ({ module: moduleName, activity, entryId }) => {
79
+ const entryLine = entryId
80
+ ? `\nTarget entry ID: ${entryId}`
81
+ : "\nThis is a create operation — no existing entry.";
82
+ return {
83
+ messages: [
84
+ {
85
+ role: "user",
86
+ content: {
87
+ type: "text",
88
+ text: `You are executing the "${activity}" activity on module "${moduleName}".${entryLine}
89
+
90
+ Follow this sequence:
91
+ 1. Call get_form(module="${moduleName}", activity="${activity}"${entryId ? `, entryId=${entryId}` : ""})
92
+ 2. Review the required fields, their types, and available options
93
+ 3. Check if confidence_threshold is present — if so, assess your confidence
94
+ 4. Prepare the input object with display-name-keyed field values
95
+ 5. If your confidence is below the threshold, include ai.confidence in the submission — the platform will flag it for human review
96
+ 6. Call submit_activity with the prepared input
97
+ 7. Report the result to the user
98
+
99
+ Always include the ai object with reasoning, sources, model, and confidence.`,
100
+ },
101
+ },
102
+ ],
103
+ };
104
+ });
105
+ // 3. diagnose_entry
106
+ server.registerPrompt("diagnose_entry", {
107
+ description: "Guide an AI agent through investigating the current state and history of an entry.",
108
+ argsSchema: {
109
+ module: z.string().describe("Module name"),
110
+ entryId: z.string().describe("Entry ID to diagnose"),
111
+ },
112
+ }, async ({ module: moduleName, entryId }) => {
113
+ return {
114
+ messages: [
115
+ {
116
+ role: "user",
117
+ content: {
118
+ type: "text",
119
+ text: `You are diagnosing entry ${entryId} in module "${moduleName}".
120
+
121
+ Follow this sequence:
122
+ 1. Call get_entry(module="${moduleName}", entryId=${entryId}) to see current state and field values
123
+ 2. Call get_entry_history(module="${moduleName}", entryId=${entryId}) to see the full audit trail
124
+ 3. Call get_module_schema(module="${moduleName}", tier="extended") to understand available activities
125
+ 4. Identify: current state, how it got there, what actions are available next, any flagged intentions
126
+ 5. Summarize findings to the user`,
127
+ },
128
+ },
129
+ ],
130
+ };
131
+ });
132
+ // 4. modify_module (configure mode)
133
+ configurePrompts.push(server.registerPrompt("modify_module", {
134
+ description: "Guide an AI agent through modifying an existing module's schema — adding fields, states, activities, or flows.",
135
+ argsSchema: {
136
+ module: z.string().describe("Module name to modify"),
137
+ change: z
138
+ .string()
139
+ .describe("Description of the change to make (e.g., 'add a Priority field', 'add an Escalate activity')"),
140
+ },
141
+ }, async ({ module: moduleName, change }) => {
142
+ return {
143
+ messages: [
144
+ {
145
+ role: "user",
146
+ content: {
147
+ type: "text",
148
+ text: `You are modifying the module "${moduleName}".
149
+ Change requested: ${change}
150
+
151
+ Follow this sequence:
152
+ 1. Call get_module_canvas(module="${moduleName}") to get the full definition with stable IDs
153
+ 2. Review the current schema — fields, states, activities, and flows
154
+ 3. Apply the requested change while preserving all existing stable IDs
155
+ 4. Call validate_design with the modified schema (mode="update") to check structural integrity
156
+ 5. If errors: fix and re-validate
157
+ 6. Present the changes to the user for review
158
+ 7. Call update_module with the modified schema
159
+
160
+ Rules:
161
+ - Always use get_module_canvas (not get_module_schema) to get stable IDs for update
162
+ - Match existing items by their id field to enable renaming without data loss
163
+ - Every new activity must be referenced by at least one flow
164
+ - Every activity field must reference a field defined in information
165
+ - Load inistate://schema resource if you need valid field types, colors, or actor types`,
166
+ },
167
+ },
168
+ ],
169
+ };
170
+ }));
171
+ return { configurePrompts };
172
+ }
@@ -0,0 +1,104 @@
1
+ import { ResourceTemplate, } from "@modelcontextprotocol/sdk/server/mcp.js";
2
+ import * as api from "./api.js";
3
+ import { SCHEMA_RUNTIME, SCHEMA_CONFIGURE, DESIGN_GUIDE, FRONTEND_GUIDE } from "./schema.js";
4
+ export function registerResources(server) {
5
+ const configureResources = [];
6
+ const frontendResources = [];
7
+ // 1. inistate://modules — list all discoverable modules
8
+ server.registerResource("modules", "inistate://modules", {
9
+ description: "List of all FACTSOps modules in the workspace — quick capability indexing",
10
+ mimeType: "application/json",
11
+ }, async (uri) => {
12
+ const data = await api.get("/api/mcp/");
13
+ return {
14
+ contents: [{ uri: uri.href, text: JSON.stringify(data) }],
15
+ };
16
+ });
17
+ // 2. inistate://modules/{name}/canvas — basic canvas schema
18
+ server.registerResource("module-canvas", new ResourceTemplate("inistate://modules/{name}/canvas", {
19
+ list: undefined,
20
+ }), {
21
+ description: "Base schema for a module: information fields and states",
22
+ mimeType: "application/json",
23
+ }, async (uri, { name }) => {
24
+ const moduleName = Array.isArray(name) ? name[0] : name;
25
+ const data = await api.get(`/api/mcp/${api.enc(moduleName)}?tier=basic`);
26
+ return {
27
+ contents: [{ uri: uri.href, text: JSON.stringify(data) }],
28
+ };
29
+ });
30
+ // 3. inistate://modules/{name}/canvas/extended — extended canvas schema
31
+ server.registerResource("module-canvas-extended", new ResourceTemplate("inistate://modules/{name}/canvas/extended", {
32
+ list: undefined,
33
+ }), {
34
+ description: "Full schema for a module: fields, states, activities, and flows",
35
+ mimeType: "application/json",
36
+ }, async (uri, { name }) => {
37
+ const moduleName = Array.isArray(name) ? name[0] : name;
38
+ const data = await api.get(`/api/mcp/${api.enc(moduleName)}?tier=extended`);
39
+ return {
40
+ contents: [{ uri: uri.href, text: JSON.stringify(data) }],
41
+ };
42
+ });
43
+ // 4. inistate://guardrails — server-side submit_activity rules
44
+ server.registerResource("guardrails", "inistate://guardrails", {
45
+ description: "Server-enforced rules for submit_activity. Read once per session — they apply silently and only surface as structured errors when triggered.",
46
+ mimeType: "text/markdown",
47
+ }, async (uri) => ({
48
+ contents: [
49
+ {
50
+ uri: uri.href,
51
+ text: `# submit_activity guard rules
52
+
53
+ The MCP server enforces four rules before forwarding submissions to the API.
54
+ Each rule, when triggered, returns a structured error with an \`agent_action\`
55
+ field telling you exactly what to do.
56
+
57
+ 1. **Human actor** — activities with \`actor: "human"\` are rejected. AI cannot execute them under any condition. \`confirmed\` does not unlock.
58
+ 2. **Hybrid actor** — activities with \`actor: "hybrid"\` require \`confirmed: true\`. Show the planned submission to the user, get explicit approval, then retry with \`confirmed: true\`.
59
+ 3. **State change** — \`activity: "changeStatus"\` and any \`state\` override require \`confirmed: true\`. Do not initiate state changes on your own.
60
+ 4. **Confidence inflation** — after a \`flagged: true\` response, resubmitting the same \`(module, entryId, activity)\` with higher confidence is rejected. Surface the flag to the user; only retry with \`confirmed: true\` if they explicitly authorize.
61
+
62
+ Standard activities (\`create\`, \`edit\`, \`delete\`, \`comment\`, \`duplicate\`, \`manage\`, \`view\`) skip the actor check but still trigger the state-change and confidence-inflation rules where applicable.
63
+ `,
64
+ },
65
+ ],
66
+ }));
67
+ // 4a. inistate://schema/runtime — runtime operations (default)
68
+ server.registerResource("schema-runtime", "inistate://schema/runtime", {
69
+ description: "DEFAULT resource — load this at session start for runtime operations: listing/reading entries, submitting activities, uploading/downloading files, reading history. Contains only the tools and types needed to USE existing modules: list_entries, get_entry, get_form, submit_activity, get_history, request_upload_url + confirm_upload (ALWAYS the default upload flow), download_file, upload_file (fallback only — use only if the presigned flow fails), plus field value shapes (File/Image/Module/User) and filter operators. Does NOT include module design content — if the user asks to create or update a module, load inistate://schema/configure + inistate://design-guide instead. Loading this AND configure together doubles context cost — pick one.",
70
+ mimeType: "application/json",
71
+ }, async (uri) => {
72
+ return {
73
+ contents: [{ uri: uri.href, text: JSON.stringify(SCHEMA_RUNTIME) }],
74
+ };
75
+ });
76
+ // 4b. inistate://schema/configure — module design & configuration (configure mode)
77
+ configureResources.push(server.registerResource("schema-configure", "inistate://schema/configure", {
78
+ description: "Load ONLY when the user asks to create a new module, edit a module schema, or design a workflow. Contains ModuleSchema write format, FieldDefinition/StateDefinition/ActivityDefinition/FlowDefinition, state color palette with decision rules and keyword hints, module_types (workflow vs record list), and the configure-mode tools (get_module_schema, create_module, update_module). Pair with inistate://design-guide for a complete design context. Do NOT load for runtime data operations — use inistate://schema/runtime instead.",
79
+ mimeType: "application/json",
80
+ }, async (uri) => {
81
+ return {
82
+ contents: [{ uri: uri.href, text: JSON.stringify(SCHEMA_CONFIGURE) }],
83
+ };
84
+ }));
85
+ // 5. inistate://design-guide — FACTS module design guide (configure mode)
86
+ configureResources.push(server.registerResource("design-guide", "inistate://design-guide", {
87
+ description: "FACTS Module Design Guide — requirements gathering questions, state color system, SVG workflow diagram specification, and module design rules. Load this in design mode alongside inistate://schema/configure to generate workflow diagrams and ask structured requirements questions. Do NOT load for runtime operations.",
88
+ mimeType: "text/markdown",
89
+ }, async (uri) => {
90
+ return {
91
+ contents: [{ uri: uri.href, text: DESIGN_GUIDE }],
92
+ };
93
+ }));
94
+ // 6. inistate://frontend-guide — REST API reference for generated UIs (frontend mode)
95
+ frontendResources.push(server.registerResource("frontend-guide", "inistate://frontend-guide", {
96
+ description: "Load ONLY in frontend mode. REST API reference for hand-written Vue/React/etc. UIs that call api.inistate.com directly (no MCP). Covers: auth header + wsid, workspace/module discovery, list/read/form/submit/history endpoints, filter operator syntax, field value shapes (File/Image/User/Module), two-step presigned uploads, error shapes, and a framework-agnostic client plus minimal Vue and React reference patterns. Token is user-supplied at runtime — never hardcoded. Pair with get_module_schema(tier=extended) for the target module.",
97
+ mimeType: "text/markdown",
98
+ }, async (uri) => {
99
+ return {
100
+ contents: [{ uri: uri.href, text: FRONTEND_GUIDE }],
101
+ };
102
+ }));
103
+ return { configureResources, frontendResources };
104
+ }