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/LICENSE +190 -0
- package/README.md +255 -0
- package/build/activity-guard.js +261 -0
- package/build/api.js +181 -0
- package/build/context.js +2 -0
- package/build/http.js +146 -0
- package/build/index.js +21 -0
- package/build/mode-store.js +25 -0
- package/build/oauth-provider.js +237 -0
- package/build/prompts.js +172 -0
- package/build/resources.js +104 -0
- package/build/schema.js +505 -0
- package/build/server.js +76 -0
- package/build/setup.js +233 -0
- package/build/tools.js +988 -0
- package/package.json +77 -0
- package/server.json +42 -0
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
import * as api from "./api.js";
|
|
2
|
+
import { requestContext } from "./context.js";
|
|
3
|
+
const REF_FIELD_TYPES = new Set(["User", "Users", "Module", "Modules"]);
|
|
4
|
+
// Standard activities are inherent platform operations and have no actor in the
|
|
5
|
+
// module schema. They bypass the actor check (but state-change checks still run).
|
|
6
|
+
const STANDARD_ACTIVITIES = new Set([
|
|
7
|
+
"create",
|
|
8
|
+
"edit",
|
|
9
|
+
"delete",
|
|
10
|
+
"comment",
|
|
11
|
+
"duplicate",
|
|
12
|
+
"manage",
|
|
13
|
+
"view",
|
|
14
|
+
"changeStatus",
|
|
15
|
+
]);
|
|
16
|
+
const SCHEMA_TTL_MS = 5 * 60 * 1000;
|
|
17
|
+
const schemaCache = new Map();
|
|
18
|
+
function cacheKey(prefix, parts) {
|
|
19
|
+
const ctx = requestContext.getStore();
|
|
20
|
+
const wsid = ctx?.workspaceId || api.getWorkspaceId() || "_";
|
|
21
|
+
const user = ctx?.userId || "_";
|
|
22
|
+
return [prefix, user, wsid, ...parts.map((p) => String(p ?? "_"))].join("::");
|
|
23
|
+
}
|
|
24
|
+
async function getExtendedSchema(moduleName) {
|
|
25
|
+
const key = cacheKey("schema", [moduleName]);
|
|
26
|
+
const now = Date.now();
|
|
27
|
+
const cached = schemaCache.get(key);
|
|
28
|
+
if (cached && now - cached.at < SCHEMA_TTL_MS)
|
|
29
|
+
return cached.schema;
|
|
30
|
+
try {
|
|
31
|
+
const schema = (await api.get(`/api/mcp/${api.enc(moduleName)}?tier=extended`));
|
|
32
|
+
schemaCache.set(key, { schema, at: now });
|
|
33
|
+
return schema;
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
return null;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
async function getActivityDef(moduleName, activity) {
|
|
40
|
+
const schema = await getExtendedSchema(moduleName);
|
|
41
|
+
return schema?.activities?.find((a) => a.name === activity) ?? null;
|
|
42
|
+
}
|
|
43
|
+
const FLAG_TTL_MS = 60 * 60 * 1000;
|
|
44
|
+
const flaggedCache = new Map();
|
|
45
|
+
function flagKey(moduleName, entryId, activity) {
|
|
46
|
+
return cacheKey("flag", [moduleName, entryId === undefined ? "_new" : String(entryId), activity]);
|
|
47
|
+
}
|
|
48
|
+
export function recordFlagged(moduleName, entryId, activity, confidence) {
|
|
49
|
+
flaggedCache.set(flagKey(moduleName, entryId, activity), { confidence, at: Date.now() });
|
|
50
|
+
}
|
|
51
|
+
export function clearFlagged(moduleName, entryId, activity) {
|
|
52
|
+
flaggedCache.delete(flagKey(moduleName, entryId, activity));
|
|
53
|
+
}
|
|
54
|
+
export function getPriorFlag(moduleName, entryId, activity) {
|
|
55
|
+
const k = flagKey(moduleName, entryId, activity);
|
|
56
|
+
const rec = flaggedCache.get(k);
|
|
57
|
+
if (!rec)
|
|
58
|
+
return undefined;
|
|
59
|
+
if (Date.now() - rec.at > FLAG_TTL_MS) {
|
|
60
|
+
flaggedCache.delete(k);
|
|
61
|
+
return undefined;
|
|
62
|
+
}
|
|
63
|
+
return rec;
|
|
64
|
+
}
|
|
65
|
+
export async function evaluateActivity(input) {
|
|
66
|
+
const { module: moduleName, activity, entryId, entryIds, state, confidence, confirmed } = input;
|
|
67
|
+
// Rule 1 — confidence inflation after a prior flag.
|
|
68
|
+
const targets = entryIds && entryIds.length > 0 ? entryIds : [entryId];
|
|
69
|
+
for (const target of targets) {
|
|
70
|
+
const prior = getPriorFlag(moduleName, target, activity);
|
|
71
|
+
if (prior && confidence > prior.confidence + 1e-6 && !confirmed) {
|
|
72
|
+
return {
|
|
73
|
+
ok: false,
|
|
74
|
+
structured: {
|
|
75
|
+
error: "confidence_inflation_blocked",
|
|
76
|
+
message: "This activity was previously flagged for human review (confidence below threshold). Resubmitting with a higher confidence score is not permitted — surface the flag to the user.",
|
|
77
|
+
activity,
|
|
78
|
+
entryId: target,
|
|
79
|
+
previous_flagged_confidence: prior.confidence,
|
|
80
|
+
current_confidence: confidence,
|
|
81
|
+
agent_action: "Stop. Tell the user the activity was flagged. Do not retry with a higher confidence on your own. If the user explicitly authorizes proceeding, resubmit with confirmed: true.",
|
|
82
|
+
},
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
// Rule 2a — `changeStatus` is the explicit state-change override.
|
|
87
|
+
if (activity === "changeStatus" && !confirmed) {
|
|
88
|
+
return {
|
|
89
|
+
ok: false,
|
|
90
|
+
structured: {
|
|
91
|
+
error: "state_change_requires_confirmation",
|
|
92
|
+
message: "The 'changeStatus' activity bypasses the workflow to change an entry's state directly. AI agents must not call it on their own initiative.",
|
|
93
|
+
activity,
|
|
94
|
+
agent_action: "Ask the user explicitly whether to change the entry's state. After they confirm, resubmit with confirmed: true.",
|
|
95
|
+
},
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
// Rule 2b — explicit `state` parameter overrides the activity's target state.
|
|
99
|
+
if (state && !confirmed) {
|
|
100
|
+
return {
|
|
101
|
+
ok: false,
|
|
102
|
+
structured: {
|
|
103
|
+
error: "state_override_requires_confirmation",
|
|
104
|
+
message: "Passing 'state' overrides the target state of the activity. This is a state change and requires explicit user authorization.",
|
|
105
|
+
activity,
|
|
106
|
+
state,
|
|
107
|
+
agent_action: "Confirm with the user that you may set the target state explicitly, then resubmit with confirmed: true.",
|
|
108
|
+
},
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
// Rules 3 & 4 apply to custom (workflow-defined) activities only.
|
|
112
|
+
if (STANDARD_ACTIVITIES.has(activity))
|
|
113
|
+
return { ok: true };
|
|
114
|
+
const def = await getActivityDef(moduleName, activity);
|
|
115
|
+
if (!def)
|
|
116
|
+
return { ok: true }; // unknown activity — let the API decide.
|
|
117
|
+
const actor = (def.actor || "").toLowerCase();
|
|
118
|
+
if (actor === "human") {
|
|
119
|
+
return {
|
|
120
|
+
ok: false,
|
|
121
|
+
structured: {
|
|
122
|
+
error: "human_actor_blocked",
|
|
123
|
+
message: `Activity '${activity}' is marked actor='human'. AI agents are not permitted to execute human-only activities.`,
|
|
124
|
+
activity,
|
|
125
|
+
actor: "human",
|
|
126
|
+
agent_action: "Do not retry — confirmed: true does NOT unlock this. Tell the user the activity must be performed by a human, then stop.",
|
|
127
|
+
},
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
if (actor === "hybrid" && !confirmed) {
|
|
131
|
+
return {
|
|
132
|
+
ok: false,
|
|
133
|
+
structured: {
|
|
134
|
+
error: "hybrid_requires_confirmation",
|
|
135
|
+
message: `Activity '${activity}' is marked actor='hybrid'. Show the planned submission to the user and obtain explicit confirmation before proceeding.`,
|
|
136
|
+
activity,
|
|
137
|
+
actor: "hybrid",
|
|
138
|
+
agent_action: "Present the planned action (module, activity, input fields) to the user. After explicit user approval, resubmit with confirmed: true.",
|
|
139
|
+
},
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
return { ok: true };
|
|
143
|
+
}
|
|
144
|
+
function checkSingleRef(field, type, value, index) {
|
|
145
|
+
const locator = index !== undefined ? `${field}[${index}]` : field;
|
|
146
|
+
const isUserType = type === "User" || type === "Users";
|
|
147
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
148
|
+
const shape = isUserType
|
|
149
|
+
? `{ id, value, username } (e.g. { id: 42, value: "John Doe", username: "jdoe" })`
|
|
150
|
+
: `{ id, value } (e.g. { id: 42, value: "Acme Corp" })`;
|
|
151
|
+
return {
|
|
152
|
+
field,
|
|
153
|
+
type,
|
|
154
|
+
received: value,
|
|
155
|
+
message: `${type} field '${locator}' must be an object with ${shape}.`,
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
const obj = value;
|
|
159
|
+
const idOk = (typeof obj.id === "string" && obj.id.length > 0) ||
|
|
160
|
+
(typeof obj.id === "number" && Number.isFinite(obj.id));
|
|
161
|
+
const valueOk = typeof obj.value === "string";
|
|
162
|
+
const usernameOk = !isUserType ||
|
|
163
|
+
(typeof obj.username === "string" && obj.username.length > 0);
|
|
164
|
+
if (idOk && valueOk && usernameOk)
|
|
165
|
+
return null;
|
|
166
|
+
const missing = [];
|
|
167
|
+
if (!idOk)
|
|
168
|
+
missing.push("id (string|number)");
|
|
169
|
+
if (!valueOk)
|
|
170
|
+
missing.push("value (string)");
|
|
171
|
+
if (!usernameOk)
|
|
172
|
+
missing.push("username (string)");
|
|
173
|
+
const required = isUserType ? "'id', 'value', and 'username'" : "both 'id' and 'value'";
|
|
174
|
+
return {
|
|
175
|
+
field,
|
|
176
|
+
type,
|
|
177
|
+
received: value,
|
|
178
|
+
message: `${type} field '${locator}' must include ${required}. Missing/invalid: ${missing.join(", ")}.`,
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
function checkRefValue(field, type, value) {
|
|
182
|
+
// null/undefined clears the field — allowed.
|
|
183
|
+
if (value === null || value === undefined)
|
|
184
|
+
return null;
|
|
185
|
+
const isPlural = type === "Users" || type === "Modules";
|
|
186
|
+
if (isPlural) {
|
|
187
|
+
if (!Array.isArray(value)) {
|
|
188
|
+
const itemShape = type === "Users" ? "{ id, value, username }" : "{ id, value }";
|
|
189
|
+
return {
|
|
190
|
+
field,
|
|
191
|
+
type,
|
|
192
|
+
received: value,
|
|
193
|
+
message: `${type} field '${field}' must be an array of ${itemShape} objects.`,
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
for (let i = 0; i < value.length; i++) {
|
|
197
|
+
const e = checkSingleRef(field, type, value[i], i);
|
|
198
|
+
if (e)
|
|
199
|
+
return e;
|
|
200
|
+
}
|
|
201
|
+
return null;
|
|
202
|
+
}
|
|
203
|
+
return checkSingleRef(field, type, value);
|
|
204
|
+
}
|
|
205
|
+
/**
|
|
206
|
+
* Build a field-name → field-type map for a module. Returns null when the
|
|
207
|
+
* schema cannot be loaded (callers should let the server decide). The
|
|
208
|
+
* underlying schema is cached by getExtendedSchema, so repeat calls are cheap.
|
|
209
|
+
*
|
|
210
|
+
* Split out so bulk callers (submit_activities) can fetch once and reuse the
|
|
211
|
+
* map across items via validateInputShapesWith.
|
|
212
|
+
*/
|
|
213
|
+
export async function getModuleFieldTypes(moduleName) {
|
|
214
|
+
const schema = await getExtendedSchema(moduleName);
|
|
215
|
+
const info = schema?.information;
|
|
216
|
+
if (!info || info.length === 0)
|
|
217
|
+
return null;
|
|
218
|
+
const types = new Map();
|
|
219
|
+
for (const f of info) {
|
|
220
|
+
if (f?.name && f?.type)
|
|
221
|
+
types.set(f.name, f.type);
|
|
222
|
+
}
|
|
223
|
+
return types;
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* Synchronous shape check against a pre-built field-type map. Use this in
|
|
227
|
+
* bulk loops to avoid rebuilding the map per item. When `types` is null
|
|
228
|
+
* (schema unavailable), returns [] so the server makes the final call.
|
|
229
|
+
*/
|
|
230
|
+
export function validateInputShapesWith(types, input) {
|
|
231
|
+
if (!input || !types)
|
|
232
|
+
return [];
|
|
233
|
+
const errors = [];
|
|
234
|
+
for (const [key, val] of Object.entries(input)) {
|
|
235
|
+
const type = types.get(key);
|
|
236
|
+
if (!type || !REF_FIELD_TYPES.has(type))
|
|
237
|
+
continue;
|
|
238
|
+
const e = checkRefValue(key, type, val);
|
|
239
|
+
if (e)
|
|
240
|
+
errors.push(e);
|
|
241
|
+
}
|
|
242
|
+
return errors;
|
|
243
|
+
}
|
|
244
|
+
/**
|
|
245
|
+
* Validate that User/Module/Users/Modules fields in `input` carry the
|
|
246
|
+
* correct shape. Convenience wrapper around getModuleFieldTypes +
|
|
247
|
+
* validateInputShapesWith — use this for one-shot calls (submit_activity).
|
|
248
|
+
* Bulk callers should fetch the map once and use validateInputShapesWith
|
|
249
|
+
* directly.
|
|
250
|
+
*/
|
|
251
|
+
export async function validateInputShapes(moduleName, input) {
|
|
252
|
+
if (!input)
|
|
253
|
+
return [];
|
|
254
|
+
const types = await getModuleFieldTypes(moduleName);
|
|
255
|
+
return validateInputShapesWith(types, input);
|
|
256
|
+
}
|
|
257
|
+
// Test-only helpers.
|
|
258
|
+
export function __resetGuardCaches() {
|
|
259
|
+
schemaCache.clear();
|
|
260
|
+
flaggedCache.clear();
|
|
261
|
+
}
|
package/build/api.js
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
import { requestContext } from "./context.js";
|
|
2
|
+
const BASE_URL = (process.env.INISTATE_API_BASE ||
|
|
3
|
+
process.env.INISTATE_API_URL ||
|
|
4
|
+
process.env.INISTATE_BASE_URL ||
|
|
5
|
+
"https://api.inistate.com").replace(/\/+$/, "");
|
|
6
|
+
const LOG_ENABLED = process.env.INISTATE_LOG !== "0";
|
|
7
|
+
function log(message, data) {
|
|
8
|
+
if (!LOG_ENABLED)
|
|
9
|
+
return;
|
|
10
|
+
const entry = {
|
|
11
|
+
ts: new Date().toISOString(),
|
|
12
|
+
msg: message,
|
|
13
|
+
...data,
|
|
14
|
+
};
|
|
15
|
+
console.error(JSON.stringify(entry));
|
|
16
|
+
}
|
|
17
|
+
// Fallback auth from env vars (used when no per-request auth is provided).
|
|
18
|
+
// Stdio mode authenticates exclusively via this API token; HTTP mode prefers
|
|
19
|
+
// the per-request Authorization header from the OAuth flow.
|
|
20
|
+
const ENV_API_KEY = process.env.INISTATE_ACCESS_TOKEN ||
|
|
21
|
+
process.env.INISTATE_API_TOKEN ||
|
|
22
|
+
process.env.INISTATE_API_KEY;
|
|
23
|
+
let workspaceId = process.env.INISTATE_WORKSPACE_ID ?? null;
|
|
24
|
+
export function setWorkspaceId(wsid) {
|
|
25
|
+
const ctx = requestContext.getStore();
|
|
26
|
+
if (ctx) {
|
|
27
|
+
// HTTP mode: write to per-request context, not the global
|
|
28
|
+
ctx.workspaceId = wsid;
|
|
29
|
+
}
|
|
30
|
+
else {
|
|
31
|
+
// stdio/session mode: write to the global
|
|
32
|
+
workspaceId = wsid;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
export function getWorkspaceId() {
|
|
36
|
+
return workspaceId;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Resolve the effective workspace ID.
|
|
40
|
+
* Priority: per-request context header > tool param (via setWorkspaceId) > env var
|
|
41
|
+
*/
|
|
42
|
+
function effectiveWorkspaceId() {
|
|
43
|
+
const ctx = requestContext.getStore();
|
|
44
|
+
return ctx?.workspaceId || workspaceId;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Resolve the effective Authorization header value.
|
|
48
|
+
* Priority: per-request context header (HTTP/OAuth flow) > env API key (stdio).
|
|
49
|
+
*/
|
|
50
|
+
function effectiveAuthorization() {
|
|
51
|
+
const ctx = requestContext.getStore();
|
|
52
|
+
if (ctx?.authorization)
|
|
53
|
+
return ctx.authorization;
|
|
54
|
+
if (ENV_API_KEY)
|
|
55
|
+
return `fsk ${ENV_API_KEY}`;
|
|
56
|
+
return null;
|
|
57
|
+
}
|
|
58
|
+
function buildHeaders(contentType) {
|
|
59
|
+
const h = { Accept: "application/json" };
|
|
60
|
+
if (contentType)
|
|
61
|
+
h["Content-Type"] = contentType;
|
|
62
|
+
const auth = effectiveAuthorization();
|
|
63
|
+
if (auth)
|
|
64
|
+
h["Authorization"] = auth;
|
|
65
|
+
const wsid = effectiveWorkspaceId();
|
|
66
|
+
if (wsid)
|
|
67
|
+
h["wsid"] = wsid;
|
|
68
|
+
return h;
|
|
69
|
+
}
|
|
70
|
+
function headers() {
|
|
71
|
+
return buildHeaders("application/json");
|
|
72
|
+
}
|
|
73
|
+
function authHeader() {
|
|
74
|
+
return buildHeaders();
|
|
75
|
+
}
|
|
76
|
+
function agentAction(status) {
|
|
77
|
+
switch (status) {
|
|
78
|
+
case 400:
|
|
79
|
+
return "Check the error message, correct the input, and retry.";
|
|
80
|
+
case 401:
|
|
81
|
+
return "API key or token is invalid or expired. Check credentials and retry.";
|
|
82
|
+
case 403:
|
|
83
|
+
return "User lacks access to this resource. Inform the user.";
|
|
84
|
+
case 404:
|
|
85
|
+
return "Resource not found. Verify the module name or entry ID.";
|
|
86
|
+
case 422:
|
|
87
|
+
return "Validation failed. Check details[].field and details[].message for specifics.";
|
|
88
|
+
default:
|
|
89
|
+
return "Unexpected error. Report to user.";
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
async function handleResponse(res) {
|
|
93
|
+
const text = await res.text();
|
|
94
|
+
if (!res.ok) {
|
|
95
|
+
let body = {};
|
|
96
|
+
try {
|
|
97
|
+
body = text ? JSON.parse(text) : {};
|
|
98
|
+
}
|
|
99
|
+
catch {
|
|
100
|
+
/* not JSON */
|
|
101
|
+
}
|
|
102
|
+
const error = {
|
|
103
|
+
error: body.error || `HTTP ${res.status}`,
|
|
104
|
+
message: body.message || text || res.statusText,
|
|
105
|
+
details: body.details || null,
|
|
106
|
+
agent_action: agentAction(res.status),
|
|
107
|
+
};
|
|
108
|
+
log("api_error", { status: res.status, url: res.url, error: error.error, message: error.message, details: error.details });
|
|
109
|
+
throw Object.assign(new Error(String(error.message)), { structured: error });
|
|
110
|
+
}
|
|
111
|
+
if (!text)
|
|
112
|
+
return null;
|
|
113
|
+
const data = JSON.parse(text);
|
|
114
|
+
// §14.8 — truncate large list responses to avoid blowing up agent context
|
|
115
|
+
if (text.length > 30_000 &&
|
|
116
|
+
data &&
|
|
117
|
+
typeof data === "object" &&
|
|
118
|
+
Array.isArray(data.list)) {
|
|
119
|
+
data.list = data.list.slice(0, 10);
|
|
120
|
+
data._truncated = true;
|
|
121
|
+
data._truncated_message = `Response truncated to 10 of ${data.totalItems ?? "unknown"} items. Use pagination (currentPage, pageSize) to retrieve more.`;
|
|
122
|
+
}
|
|
123
|
+
return data;
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Core request function. The MCP server no longer manages tokens itself —
|
|
127
|
+
* stdio uses a long-lived API token, HTTP/OAuth passes the client's bearer
|
|
128
|
+
* through. On 401, the caller (or in HTTP mode the OAuth client) is
|
|
129
|
+
* responsible for refreshing.
|
|
130
|
+
*/
|
|
131
|
+
async function request(url, init, getHeaders) {
|
|
132
|
+
const method = init.method || "GET";
|
|
133
|
+
log("request", { method, url });
|
|
134
|
+
const start = Date.now();
|
|
135
|
+
const res = await fetch(url, { ...init, headers: getHeaders() });
|
|
136
|
+
log("response", { method, url, status: res.status, ms: Date.now() - start });
|
|
137
|
+
return res;
|
|
138
|
+
}
|
|
139
|
+
export async function get(path) {
|
|
140
|
+
const res = await request(`${BASE_URL}${path}`, {}, headers);
|
|
141
|
+
return handleResponse(res);
|
|
142
|
+
}
|
|
143
|
+
export async function post(path, body) {
|
|
144
|
+
const res = await request(`${BASE_URL}${path}`, {
|
|
145
|
+
method: "POST",
|
|
146
|
+
body: body !== undefined ? JSON.stringify(body) : undefined,
|
|
147
|
+
}, headers);
|
|
148
|
+
return handleResponse(res);
|
|
149
|
+
}
|
|
150
|
+
export async function put(path, body) {
|
|
151
|
+
const res = await request(`${BASE_URL}${path}`, {
|
|
152
|
+
method: "PUT",
|
|
153
|
+
body: body !== undefined ? JSON.stringify(body) : undefined,
|
|
154
|
+
}, headers);
|
|
155
|
+
return handleResponse(res);
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* Upload a file via multipart/form-data.
|
|
159
|
+
*/
|
|
160
|
+
export async function uploadFormData(path, formData) {
|
|
161
|
+
const res = await request(`${BASE_URL}${path}`, { method: "POST", body: formData }, authHeader);
|
|
162
|
+
return handleResponse(res);
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* GET with manual redirect for download_file — returns redirect URL instead of following.
|
|
166
|
+
*/
|
|
167
|
+
export async function getRaw(path) {
|
|
168
|
+
const res = await request(`${BASE_URL}${path}`, { redirect: "manual" }, authHeader);
|
|
169
|
+
if (res.status === 302 || res.status === 301) {
|
|
170
|
+
return {
|
|
171
|
+
redirectUrl: res.headers.get("Location"),
|
|
172
|
+
status: res.status,
|
|
173
|
+
body: null,
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
const data = await handleResponse(res);
|
|
177
|
+
return { redirectUrl: null, status: res.status, body: data };
|
|
178
|
+
}
|
|
179
|
+
export function enc(s) {
|
|
180
|
+
return encodeURIComponent(s);
|
|
181
|
+
}
|
package/build/context.js
ADDED
package/build/http.js
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Stateless Streamable-HTTP transport for the Inistate MCP server
|
|
4
|
+
* with MCP OAuth 2.0 authorization (Google, Apple, password).
|
|
5
|
+
*/
|
|
6
|
+
import "dotenv/config";
|
|
7
|
+
import express from "express";
|
|
8
|
+
import { mcpAuthRouter } from "@modelcontextprotocol/sdk/server/auth/router.js";
|
|
9
|
+
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
|
10
|
+
import { createServer } from "./server.js";
|
|
11
|
+
import { requestContext } from "./context.js";
|
|
12
|
+
import { InistateOAuthProvider, decodeJwtSub } from "./oauth-provider.js";
|
|
13
|
+
import { getUserMode } from "./mode-store.js";
|
|
14
|
+
const PORT = parseInt(process.env.PORT || "3000", 10);
|
|
15
|
+
const BASE_URL = process.env.INISTATE_API_BASE ||
|
|
16
|
+
process.env.INISTATE_API_URL ||
|
|
17
|
+
process.env.INISTATE_BASE_URL ||
|
|
18
|
+
"https://api.inistate.com";
|
|
19
|
+
const ISSUER_URL = process.env.OAUTH_ISSUER_URL || `http://localhost:${PORT}`;
|
|
20
|
+
const APP_URL = process.env.INISTATE_APP_URL || "https://app.inistate.com";
|
|
21
|
+
const APP_LOGIN_PATH = process.env.INISTATE_APP_LOGIN_PATH || "/#/login";
|
|
22
|
+
const app = express();
|
|
23
|
+
/* ------------------------------------------------------------------ */
|
|
24
|
+
/* CORS (must come before routes) */
|
|
25
|
+
/* ------------------------------------------------------------------ */
|
|
26
|
+
app.use((_req, res, next) => {
|
|
27
|
+
res.setHeader("Access-Control-Allow-Origin", "*");
|
|
28
|
+
res.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS");
|
|
29
|
+
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, mcp-session-id, mcp-protocol-version, Last-Event-ID, x-workspace-id");
|
|
30
|
+
res.setHeader("Access-Control-Expose-Headers", "mcp-session-id");
|
|
31
|
+
if (_req.method === "OPTIONS") {
|
|
32
|
+
res.status(204).end();
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
next();
|
|
36
|
+
});
|
|
37
|
+
/* ------------------------------------------------------------------ */
|
|
38
|
+
/* OAuth 2.0 provider */
|
|
39
|
+
/* ------------------------------------------------------------------ */
|
|
40
|
+
const oauthProvider = new InistateOAuthProvider(BASE_URL, APP_URL, ISSUER_URL, APP_LOGIN_PATH);
|
|
41
|
+
const PROTECTED_RESOURCE_METADATA_URL = `${ISSUER_URL.replace(/\/$/, "")}/.well-known/oauth-protected-resource/mcp`;
|
|
42
|
+
// Mount the SDK's OAuth router at root
|
|
43
|
+
// Handles: /.well-known/oauth-authorization-server, /authorize, /token, /register
|
|
44
|
+
app.use(mcpAuthRouter({
|
|
45
|
+
provider: oauthProvider,
|
|
46
|
+
issuerUrl: new URL(ISSUER_URL),
|
|
47
|
+
baseUrl: new URL(ISSUER_URL),
|
|
48
|
+
resourceServerUrl: new URL("/mcp", ISSUER_URL),
|
|
49
|
+
}));
|
|
50
|
+
/* ------------------------------------------------------------------ */
|
|
51
|
+
/* OAuth authorize callback (login page POSTs here) */
|
|
52
|
+
/* ------------------------------------------------------------------ */
|
|
53
|
+
app.post("/authorize/callback", express.urlencoded({ extended: false }), (req, res) => {
|
|
54
|
+
try {
|
|
55
|
+
const { nonce, jwt, refreshToken } = req.body;
|
|
56
|
+
if (!nonce || !jwt) {
|
|
57
|
+
res.status(400).send("Missing nonce or jwt");
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
const { redirectUrl } = oauthProvider.completeAuthorization(nonce, jwt, refreshToken || undefined);
|
|
61
|
+
res.redirect(302, redirectUrl);
|
|
62
|
+
}
|
|
63
|
+
catch (error) {
|
|
64
|
+
console.error("Authorize callback error:", error);
|
|
65
|
+
res.status(400).send(error instanceof Error ? error.message : "Authorization failed");
|
|
66
|
+
}
|
|
67
|
+
});
|
|
68
|
+
/* ------------------------------------------------------------------ */
|
|
69
|
+
/* Health check */
|
|
70
|
+
/* ------------------------------------------------------------------ */
|
|
71
|
+
app.get("/health", (_req, res) => {
|
|
72
|
+
res.json({ status: "ok" });
|
|
73
|
+
});
|
|
74
|
+
/* ------------------------------------------------------------------ */
|
|
75
|
+
/* MCP endpoint (stateless) */
|
|
76
|
+
/* ------------------------------------------------------------------ */
|
|
77
|
+
function sendUnauthorized(res, description) {
|
|
78
|
+
res.set("WWW-Authenticate", `Bearer realm="mcp", error="invalid_token", error_description="${description}", resource_metadata="${PROTECTED_RESOURCE_METADATA_URL}"`);
|
|
79
|
+
res.status(401).json({
|
|
80
|
+
jsonrpc: "2.0",
|
|
81
|
+
error: { code: -32001, message: description },
|
|
82
|
+
id: null,
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
app.get("/mcp", (_req, res) => sendUnauthorized(res, "Missing Authorization header"));
|
|
86
|
+
app.delete("/mcp", (_req, res) => sendUnauthorized(res, "Missing Authorization header"));
|
|
87
|
+
app.post("/mcp", express.raw({ type: "*/*", limit: "4mb" }), async (req, res) => {
|
|
88
|
+
try {
|
|
89
|
+
const authHeader = req.headers["authorization"];
|
|
90
|
+
if (!authHeader || !/^Bearer\s+\S+/i.test(authHeader)) {
|
|
91
|
+
sendUnauthorized(res, "Missing or malformed Authorization header");
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
const body = JSON.parse(req.body.toString());
|
|
95
|
+
// Extract per-request auth context from HTTP headers
|
|
96
|
+
const bearer = authHeader.replace(/^Bearer\s+/i, "");
|
|
97
|
+
const userId = decodeJwtSub(bearer);
|
|
98
|
+
const mode = userId ? getUserMode(userId) : undefined;
|
|
99
|
+
const ctx = {
|
|
100
|
+
authorization: authHeader,
|
|
101
|
+
workspaceId: req.headers["x-workspace-id"],
|
|
102
|
+
userId,
|
|
103
|
+
mode,
|
|
104
|
+
};
|
|
105
|
+
await requestContext.run(ctx, async () => {
|
|
106
|
+
const transport = new StreamableHTTPServerTransport({
|
|
107
|
+
sessionIdGenerator: undefined,
|
|
108
|
+
});
|
|
109
|
+
const server = createServer(mode);
|
|
110
|
+
await server.connect(transport);
|
|
111
|
+
await transport.handleRequest(req, res, body);
|
|
112
|
+
await transport.close();
|
|
113
|
+
await server.close();
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
catch (error) {
|
|
117
|
+
console.error("MCP error:", error);
|
|
118
|
+
if (!res.headersSent) {
|
|
119
|
+
res.status(500).json({
|
|
120
|
+
jsonrpc: "2.0",
|
|
121
|
+
error: { code: -32603, message: "Internal server error" },
|
|
122
|
+
id: null,
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
});
|
|
127
|
+
app.get("/.well-known/openai-apps-challenge", (_, res) => {
|
|
128
|
+
const data = process.env.OPENAI_VERIFICATION_TOKEN;
|
|
129
|
+
if (!data) {
|
|
130
|
+
res.status(404).type('text/plain').send("Not found");
|
|
131
|
+
}
|
|
132
|
+
res.status(200).type("text/plain").send(data);
|
|
133
|
+
});
|
|
134
|
+
/* ------------------------------------------------------------------ */
|
|
135
|
+
/* Start */
|
|
136
|
+
/* ------------------------------------------------------------------ */
|
|
137
|
+
app.listen(PORT, () => {
|
|
138
|
+
console.log(`Inistate MCP HTTP server listening on port ${PORT}`);
|
|
139
|
+
console.log(` MCP: POST http://localhost:${PORT}/mcp`);
|
|
140
|
+
console.log(` OAuth: GET http://localhost:${PORT}/.well-known/oauth-authorization-server`);
|
|
141
|
+
console.log(` Health: GET http://localhost:${PORT}/health`);
|
|
142
|
+
});
|
|
143
|
+
process.on("SIGINT", () => {
|
|
144
|
+
console.log("Shutting down...");
|
|
145
|
+
process.exit(0);
|
|
146
|
+
});
|
package/build/index.js
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import "dotenv/config";
|
|
3
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
4
|
+
import { createServer } from "./server.js";
|
|
5
|
+
async function main() {
|
|
6
|
+
const setupRequested = process.argv.slice(2).includes("setup");
|
|
7
|
+
const interactive = process.stdin.isTTY && process.env.INISTATE_MCP_NO_SETUP !== "1";
|
|
8
|
+
if (setupRequested || interactive) {
|
|
9
|
+
const { runSetup } = await import("./setup.js");
|
|
10
|
+
await runSetup();
|
|
11
|
+
return;
|
|
12
|
+
}
|
|
13
|
+
const server = createServer();
|
|
14
|
+
const transport = new StdioServerTransport();
|
|
15
|
+
await server.connect(transport);
|
|
16
|
+
console.error("Inistate MCP server running on stdio");
|
|
17
|
+
}
|
|
18
|
+
main().catch((error) => {
|
|
19
|
+
console.error("Fatal error:", error);
|
|
20
|
+
process.exit(1);
|
|
21
|
+
});
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Per-user mode store. Survives across the stateless HTTP transport's
|
|
3
|
+
* per-request `createServer()` lifecycle, so a user's `switch_mode` choice
|
|
4
|
+
* is remembered for subsequent requests on the same JWT subject.
|
|
5
|
+
*
|
|
6
|
+
* In-memory only — a process restart resets everyone to the env/default mode.
|
|
7
|
+
* For multi-replica deployments, swap the Map for a shared store (Redis, etc.)
|
|
8
|
+
* with the same getUserMode/setUserMode shape.
|
|
9
|
+
*/
|
|
10
|
+
const TTL_MS = 24 * 60 * 60 * 1000;
|
|
11
|
+
const userModes = new Map();
|
|
12
|
+
export function getUserMode(userId) {
|
|
13
|
+
const entry = userModes.get(userId);
|
|
14
|
+
if (!entry)
|
|
15
|
+
return undefined;
|
|
16
|
+
if (Date.now() - entry.lastUsed > TTL_MS) {
|
|
17
|
+
userModes.delete(userId);
|
|
18
|
+
return undefined;
|
|
19
|
+
}
|
|
20
|
+
entry.lastUsed = Date.now();
|
|
21
|
+
return entry.mode;
|
|
22
|
+
}
|
|
23
|
+
export function setUserMode(userId, mode) {
|
|
24
|
+
userModes.set(userId, { mode, lastUsed: Date.now() });
|
|
25
|
+
}
|