suppa-mcp-2 1.0.0
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 +21 -0
- package/README.md +59 -0
- package/dist/auth.js +612 -0
- package/dist/bin.js +11 -0
- package/dist/config.js +168 -0
- package/dist/httpClient.js +269 -0
- package/dist/registry.js +111 -0
- package/dist/server.js +1533 -0
- package/dist/store.js +120 -0
- package/dist/tenants.js +408 -0
- package/dist/tools/automation.js +776 -0
- package/dist/tools/docs.js +534 -0
- package/dist/tools/entity.js +831 -0
- package/dist/tools/forms.js +550 -0
- package/dist/tools/migrate.js +936 -0
- package/dist/tools/nameMap.js +134 -0
- package/dist/tools/tasks.js +423 -0
- package/dist/tools/v1Fields.js +0 -0
- package/dist/tools/workspace.js +121 -0
- package/dist/utils.js +391 -0
- package/package.json +26 -0
package/dist/bin.js
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* stdio entrypoint for the Suppa MCP server (npm `suppa-mcp-2`).
|
|
4
|
+
*
|
|
5
|
+
* Builds the server (all 74 tools) and connects it to stdio, exactly like the
|
|
6
|
+
* Python package's console script. Faithful 1:1 port.
|
|
7
|
+
*/
|
|
8
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
9
|
+
import { buildServer } from "./server.js";
|
|
10
|
+
const server = buildServer();
|
|
11
|
+
await server.connect(new StdioServerTransport());
|
package/dist/config.js
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Configuration loaded from environment variables or .env file.
|
|
3
|
+
*
|
|
4
|
+
* Faithful 1:1 port of the Python `suppa_mcp/config.py`.
|
|
5
|
+
*/
|
|
6
|
+
import { existsSync, readFileSync, statSync } from "node:fs";
|
|
7
|
+
import { dirname, join, resolve } from "node:path";
|
|
8
|
+
import { fileURLToPath } from "node:url";
|
|
9
|
+
/**
|
|
10
|
+
* Return candidate .env locations, in priority order.
|
|
11
|
+
*
|
|
12
|
+
* Searches the current working directory and every parent up to the
|
|
13
|
+
* filesystem root, then the packaged project root. This makes the server
|
|
14
|
+
* work no matter which directory an MCP client launches it from.
|
|
15
|
+
*/
|
|
16
|
+
export function candidateEnvFiles() {
|
|
17
|
+
const candidates = [];
|
|
18
|
+
const cwd = process.cwd();
|
|
19
|
+
// cwd, then every parent up to the filesystem root (mirrors Path.cwd().parents).
|
|
20
|
+
let folder = resolve(cwd);
|
|
21
|
+
while (true) {
|
|
22
|
+
candidates.push(join(folder, ".env"));
|
|
23
|
+
const parent = dirname(folder);
|
|
24
|
+
if (parent === folder) {
|
|
25
|
+
break; // reached the filesystem root
|
|
26
|
+
}
|
|
27
|
+
folder = parent;
|
|
28
|
+
}
|
|
29
|
+
// Project root relative to this module (…/suppa-mcp-node/.env). In Python
|
|
30
|
+
// this is Path(__file__).resolve().parent.parent.parent; here we walk up from
|
|
31
|
+
// the compiled module location to the package root (the dir with package.json).
|
|
32
|
+
const packageRoot = findPackageRoot(dirname(fileURLToPath(import.meta.url)));
|
|
33
|
+
candidates.push(join(packageRoot, ".env"));
|
|
34
|
+
// De-duplicate while preserving order.
|
|
35
|
+
const seen = new Set();
|
|
36
|
+
const unique = [];
|
|
37
|
+
for (const c of candidates) {
|
|
38
|
+
if (!seen.has(c)) {
|
|
39
|
+
seen.add(c);
|
|
40
|
+
unique.push(c);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return unique;
|
|
44
|
+
}
|
|
45
|
+
/** Walk up from `start` to the nearest ancestor that contains a package.json. */
|
|
46
|
+
function findPackageRoot(start) {
|
|
47
|
+
let dir = resolve(start);
|
|
48
|
+
while (true) {
|
|
49
|
+
if (existsSync(join(dir, "package.json"))) {
|
|
50
|
+
return dir;
|
|
51
|
+
}
|
|
52
|
+
const parent = dirname(dir);
|
|
53
|
+
if (parent === dir) {
|
|
54
|
+
// No package.json found; fall back to the Python-equivalent
|
|
55
|
+
// parent.parent.parent (…/<pkg>/src/config.ts -> …/<pkg>).
|
|
56
|
+
return resolve(start, "..", "..");
|
|
57
|
+
}
|
|
58
|
+
dir = parent;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Import SUPPA_*-prefixed keys from one .env file into the process env.
|
|
63
|
+
*
|
|
64
|
+
* Only SUPPA_* keys are loaded: the walk-up search can land on an unrelated
|
|
65
|
+
* project's .env, and importing its entire contents would both leak that
|
|
66
|
+
* project's secrets into this process and let foreign variables silently
|
|
67
|
+
* reconfigure the server. Real env vars always win over the file.
|
|
68
|
+
*/
|
|
69
|
+
function loadEnvFile(path) {
|
|
70
|
+
const contents = readFileSync(path, { encoding: "utf-8" });
|
|
71
|
+
for (const rawLine of contents.split(/\r?\n/)) {
|
|
72
|
+
const line = rawLine.trim();
|
|
73
|
+
if (!line || line.startsWith("#") || !line.includes("=")) {
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
const eq = line.indexOf("=");
|
|
77
|
+
const key = line.slice(0, eq).trim();
|
|
78
|
+
let value = line.slice(eq + 1).trim();
|
|
79
|
+
value = stripQuotes(value);
|
|
80
|
+
if (key.startsWith("SUPPA_") && !(key in process.env)) {
|
|
81
|
+
process.env[key] = value;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
/** Strip a single layer of surrounding single or double quotes (Python's .strip("\"'")). */
|
|
86
|
+
function stripQuotes(value) {
|
|
87
|
+
// Python's str.strip("\"'") removes any leading/trailing run of the
|
|
88
|
+
// characters " and ' (both, in any combination), not a matched pair.
|
|
89
|
+
let start = 0;
|
|
90
|
+
let end = value.length;
|
|
91
|
+
while (start < end && (value[start] === '"' || value[start] === "'")) {
|
|
92
|
+
start++;
|
|
93
|
+
}
|
|
94
|
+
while (end > start && (value[end - 1] === '"' || value[end - 1] === "'")) {
|
|
95
|
+
end--;
|
|
96
|
+
}
|
|
97
|
+
return value.slice(start, end);
|
|
98
|
+
}
|
|
99
|
+
/** Minimal .env loader — no external dependency. First match wins. */
|
|
100
|
+
function loadDotenv() {
|
|
101
|
+
for (const candidate of candidateEnvFiles()) {
|
|
102
|
+
let isFile = false;
|
|
103
|
+
try {
|
|
104
|
+
isFile = statSync(candidate).isFile();
|
|
105
|
+
}
|
|
106
|
+
catch {
|
|
107
|
+
isFile = false;
|
|
108
|
+
}
|
|
109
|
+
if (isFile) {
|
|
110
|
+
loadEnvFile(candidate);
|
|
111
|
+
break;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
loadDotenv();
|
|
116
|
+
const BASE_URL = (process.env.SUPPA_BASE_URL || "https://modern.suppa.me").replace(/\/+$/, "");
|
|
117
|
+
const API_KEY = process.env.SUPPA_API_KEY || process.env.SUPPA_TOKEN || "";
|
|
118
|
+
const REFRESH_TOKEN = process.env.SUPPA_REFRESH_TOKEN || "";
|
|
119
|
+
const LANG = process.env.SUPPA_LANG || "en";
|
|
120
|
+
const TZ = process.env.SUPPA_TZ || "Europe/Kyiv";
|
|
121
|
+
const TASKS_ENTITY_ID = parseInt(process.env.SUPPA_TASKS_ENTITY_ID || "37", 10);
|
|
122
|
+
// Default per-request timeout (seconds); uploads use at least 120s.
|
|
123
|
+
const HTTP_TIMEOUT = parseInt(process.env.SUPPA_HTTP_TIMEOUT || "60", 10);
|
|
124
|
+
// When truthy, log each request line (method, URL, status, duration) to stderr.
|
|
125
|
+
const DEBUG = ["1", "true", "yes"].includes((process.env.SUPPA_MCP_DEBUG || "").toLowerCase());
|
|
126
|
+
// ---------------------------------------------------------------------------
|
|
127
|
+
// Suppa 1.0 (source platform) — used by the migration connector
|
|
128
|
+
// ---------------------------------------------------------------------------
|
|
129
|
+
const V1_BASE_URL = (process.env.SUPPA_V1_BASE_URL || "https://sp.modern-expo.com").replace(/\/+$/, "");
|
|
130
|
+
const V1_API_KEY = process.env.SUPPA_V1_API_KEY || process.env.SUPPA_V1_TOKEN || "";
|
|
131
|
+
const V1_ACCESS_TOKEN = process.env.SUPPA_V1_ACCESS_TOKEN || "";
|
|
132
|
+
// ---------------------------------------------------------------------------
|
|
133
|
+
// Google login (browser loopback) — used by suppa_login
|
|
134
|
+
// ---------------------------------------------------------------------------
|
|
135
|
+
// Shared across all tenants (the Suppa product's Google OAuth client). The
|
|
136
|
+
// loopback origin http://localhost:<LOGIN_PORT> must be added to this client's
|
|
137
|
+
// "Authorized JavaScript origins" in Google Cloud for the in-browser flow.
|
|
138
|
+
const GOOGLE_CLIENT_ID = process.env.SUPPA_GOOGLE_CLIENT_ID ||
|
|
139
|
+
"294101885657-gl7ee19of4e2h5g8fj99q21ct74l0etg.apps.googleusercontent.com";
|
|
140
|
+
const LOGIN_PORT = parseInt(process.env.SUPPA_MCP_LOGIN_PORT || "8080", 10);
|
|
141
|
+
/** Return a masked preview of a secret for safe logging. */
|
|
142
|
+
export function maskedKey(value = "") {
|
|
143
|
+
const secret = value || API_KEY;
|
|
144
|
+
if (!secret) {
|
|
145
|
+
return "(not set)";
|
|
146
|
+
}
|
|
147
|
+
if (secret.length <= 12) {
|
|
148
|
+
return "set";
|
|
149
|
+
}
|
|
150
|
+
return `${secret.slice(0, 6)}…${secret.slice(-4)} (len=${secret.length})`;
|
|
151
|
+
}
|
|
152
|
+
export const config = {
|
|
153
|
+
BASE_URL,
|
|
154
|
+
API_KEY,
|
|
155
|
+
REFRESH_TOKEN,
|
|
156
|
+
LANG,
|
|
157
|
+
TZ,
|
|
158
|
+
TASKS_ENTITY_ID,
|
|
159
|
+
HTTP_TIMEOUT,
|
|
160
|
+
DEBUG,
|
|
161
|
+
V1_BASE_URL,
|
|
162
|
+
V1_API_KEY,
|
|
163
|
+
V1_ACCESS_TOKEN,
|
|
164
|
+
GOOGLE_CLIENT_ID,
|
|
165
|
+
LOGIN_PORT,
|
|
166
|
+
candidateEnvFiles,
|
|
167
|
+
maskedKey,
|
|
168
|
+
};
|
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared HTTP client for the Suppa REST API.
|
|
3
|
+
*
|
|
4
|
+
* Faithful 1:1 port of the Python `suppa_mcp/http_client.py`. Uses the native
|
|
5
|
+
* global `fetch` in place of `urllib`, with an AbortController for timeouts.
|
|
6
|
+
*/
|
|
7
|
+
import { config } from "./config.js";
|
|
8
|
+
import * as tenants from "./tenants.js";
|
|
9
|
+
// HTTP statuses that signal a transient upstream problem worth one retry.
|
|
10
|
+
const TRANSIENT_CODES = new Set([429, 502, 503, 504]);
|
|
11
|
+
function debug(msg) {
|
|
12
|
+
if (config.DEBUG) {
|
|
13
|
+
process.stderr.write(`[suppa-mcp] ${msg}\n`);
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* True when a retry cannot duplicate a write.
|
|
18
|
+
*
|
|
19
|
+
* GETs are safe by definition; the platform's read actions are POSTs to
|
|
20
|
+
* /search and /select, which are semantically read-only. Inserts/updates/
|
|
21
|
+
* removes must NOT be retried blindly — a retry could double-apply them.
|
|
22
|
+
*/
|
|
23
|
+
function isSafeRequest(method, url) {
|
|
24
|
+
return method === "GET" || url.includes("/search") || url.includes("/select");
|
|
25
|
+
}
|
|
26
|
+
function headers(ctx, token, extra) {
|
|
27
|
+
const h = {
|
|
28
|
+
Authorization: `Bearer ${token}`,
|
|
29
|
+
Accept: "application/json, text/plain, */*",
|
|
30
|
+
"x-current-language": ctx.lang,
|
|
31
|
+
"x-timezone": ctx.tz,
|
|
32
|
+
"x-view-mode": "view",
|
|
33
|
+
};
|
|
34
|
+
// The platform authenticates the browser via the accessToken cookie (its
|
|
35
|
+
// preferred path). Send it only for JWTs — putting a non-JWT API key in the
|
|
36
|
+
// cookie can make the server reject it, so those keep the Bearer-only path.
|
|
37
|
+
if ((token.match(/\./g) || []).length === 2) {
|
|
38
|
+
h.Cookie = `accessToken=${token}`;
|
|
39
|
+
}
|
|
40
|
+
if (extra) {
|
|
41
|
+
Object.assign(h, extra);
|
|
42
|
+
}
|
|
43
|
+
return h;
|
|
44
|
+
}
|
|
45
|
+
function noTokenError(ctx) {
|
|
46
|
+
return new Error(`NOT SIGNED IN to Suppa tenant '${ctx.host}'. This is expected on first use ` +
|
|
47
|
+
"and is not a failure to report back as 'broken'. ACTION REQUIRED: call the " +
|
|
48
|
+
"suppa_login tool now — it opens a Google sign-in page in the browser — then " +
|
|
49
|
+
"retry this call. Do NOT ask the user for an API key or token; end users " +
|
|
50
|
+
"don't have one. (A SUPPA_API_KEY env var is an optional CI-only alternative.)");
|
|
51
|
+
}
|
|
52
|
+
// Keys a paginated envelope wraps its payload under, and the only sibling keys
|
|
53
|
+
// such an envelope may carry. The Suppa data endpoints return bare lists today,
|
|
54
|
+
// so this is a forward-compatible safety net — and it must NEVER strip a real
|
|
55
|
+
// record that merely happens to own a field called "data" (e.g. a Form).
|
|
56
|
+
const ENVELOPE_KEYS = ["data", "rows", "items", "result"];
|
|
57
|
+
const ENVELOPE_META_KEYS = new Set([
|
|
58
|
+
"total",
|
|
59
|
+
"count",
|
|
60
|
+
"totalCount",
|
|
61
|
+
"limit",
|
|
62
|
+
"offset",
|
|
63
|
+
"page",
|
|
64
|
+
"pages",
|
|
65
|
+
"pageCount",
|
|
66
|
+
"totalPages",
|
|
67
|
+
"hasMore",
|
|
68
|
+
"hasNext",
|
|
69
|
+
]);
|
|
70
|
+
/**
|
|
71
|
+
* Return the inner payload iff `result` is a pagination envelope.
|
|
72
|
+
*
|
|
73
|
+
* An envelope is a dict with exactly one recognised wrapper key holding a
|
|
74
|
+
* **list**, whose only other keys are pagination metadata. Anything else
|
|
75
|
+
* (a real record, a schema object) is returned unchanged.
|
|
76
|
+
*/
|
|
77
|
+
export function unwrapEnvelope(result) {
|
|
78
|
+
if (result === null || typeof result !== "object" || Array.isArray(result)) {
|
|
79
|
+
return result;
|
|
80
|
+
}
|
|
81
|
+
const obj = result;
|
|
82
|
+
for (const key of ENVELOPE_KEYS) {
|
|
83
|
+
if (key in obj && Array.isArray(obj[key])) {
|
|
84
|
+
const siblings = Object.keys(obj).filter((k) => k !== key);
|
|
85
|
+
if (siblings.every((k) => ENVELOPE_META_KEYS.has(k))) {
|
|
86
|
+
return obj[key];
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
return result;
|
|
91
|
+
}
|
|
92
|
+
/** Best-effort read of a headers-like object's text; tolerates a Map mock. */
|
|
93
|
+
function safeStatusText(res) {
|
|
94
|
+
try {
|
|
95
|
+
return res.statusText ?? "";
|
|
96
|
+
}
|
|
97
|
+
catch {
|
|
98
|
+
return "";
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
async function sendWithReauth(ctx, buildHeaders, method, url, data, timeout, opts) {
|
|
102
|
+
let refreshed = false;
|
|
103
|
+
let transientRetried = false;
|
|
104
|
+
const retriable = isSafeRequest(method, url);
|
|
105
|
+
// eslint-disable-next-line no-constant-condition
|
|
106
|
+
while (true) {
|
|
107
|
+
const token = ctx.getToken();
|
|
108
|
+
if (!token) {
|
|
109
|
+
throw noTokenError(ctx);
|
|
110
|
+
}
|
|
111
|
+
const controller = new AbortController();
|
|
112
|
+
const timer = setTimeout(() => controller.abort(), timeout * 1000);
|
|
113
|
+
const started = Date.now();
|
|
114
|
+
let res;
|
|
115
|
+
try {
|
|
116
|
+
res = await fetch(url, {
|
|
117
|
+
method,
|
|
118
|
+
headers: buildHeaders(token),
|
|
119
|
+
body: data,
|
|
120
|
+
signal: controller.signal,
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
catch (e) {
|
|
124
|
+
clearTimeout(timer);
|
|
125
|
+
const err = e;
|
|
126
|
+
if (err && err.name === "AbortError") {
|
|
127
|
+
// Timeout while connecting or reading the response body.
|
|
128
|
+
debug(`${method} ${url} -> timeout after ${timeout}s`);
|
|
129
|
+
throw new Error(`Request to ${ctx.host} timed out after ${timeout}s. ` +
|
|
130
|
+
"The platform may be slow — retry, or narrow the request (smaller limit/fields).");
|
|
131
|
+
}
|
|
132
|
+
const reason = e instanceof Error ? e.message : String(e);
|
|
133
|
+
debug(`${method} ${url} -> URLError ${reason}`);
|
|
134
|
+
if (retriable && !transientRetried) {
|
|
135
|
+
transientRetried = true;
|
|
136
|
+
await sleep(500);
|
|
137
|
+
continue;
|
|
138
|
+
}
|
|
139
|
+
throw new Error(`Connection error: ${reason}`);
|
|
140
|
+
}
|
|
141
|
+
finally {
|
|
142
|
+
clearTimeout(timer);
|
|
143
|
+
}
|
|
144
|
+
const code = res.status;
|
|
145
|
+
if (code >= 400) {
|
|
146
|
+
debug(`${method} ${url} -> HTTP ${code} (${((Date.now() - started) / 1000).toFixed(2)}s)`);
|
|
147
|
+
if (code === 401 && !refreshed && (await tenants.reauth(ctx))) {
|
|
148
|
+
refreshed = true;
|
|
149
|
+
continue; // token refreshed — retry once
|
|
150
|
+
}
|
|
151
|
+
if (TRANSIENT_CODES.has(code) && retriable && !transientRetried) {
|
|
152
|
+
transientRetried = true;
|
|
153
|
+
await sleep(500);
|
|
154
|
+
continue;
|
|
155
|
+
}
|
|
156
|
+
let errorBody = "";
|
|
157
|
+
try {
|
|
158
|
+
errorBody = await res.text();
|
|
159
|
+
}
|
|
160
|
+
catch {
|
|
161
|
+
// ignore
|
|
162
|
+
}
|
|
163
|
+
if (code === 401) {
|
|
164
|
+
throw new Error(`HTTP 401 for tenant '${ctx.host}': session could not be refreshed. ` +
|
|
165
|
+
`Run suppa_login. ${errorBody}`);
|
|
166
|
+
}
|
|
167
|
+
throw new Error(`HTTP ${code} ${safeStatusText(res)}: ${errorBody}`);
|
|
168
|
+
}
|
|
169
|
+
const raw = await res.text();
|
|
170
|
+
if (config.DEBUG) {
|
|
171
|
+
debug(`${method} ${url} -> ${code} (${((Date.now() - started) / 1000).toFixed(2)}s)`);
|
|
172
|
+
}
|
|
173
|
+
if (!raw || !raw.trim()) {
|
|
174
|
+
return null;
|
|
175
|
+
}
|
|
176
|
+
const result = JSON.parse(raw);
|
|
177
|
+
return opts.unwrap ? unwrapEnvelope(result) : result;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
function sleep(ms) {
|
|
181
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* Make an HTTP request to a Suppa tenant. Returns parsed JSON or null.
|
|
185
|
+
*
|
|
186
|
+
* Targets the active tenant unless an explicit `ctx` is given.
|
|
187
|
+
*/
|
|
188
|
+
export async function makeRequest(method, path, body = null, opts = {}) {
|
|
189
|
+
const ctx = opts.ctx ?? tenants.current();
|
|
190
|
+
await tenants.ensureValid(ctx);
|
|
191
|
+
const timeout = opts.timeout ?? config.HTTP_TIMEOUT;
|
|
192
|
+
const url = path.startsWith("/") ? `${ctx.baseUrl}${path}` : path;
|
|
193
|
+
let data = null;
|
|
194
|
+
const extra = { ...(opts.extraHeaders ?? {}) };
|
|
195
|
+
if (body !== null && body !== undefined) {
|
|
196
|
+
data = JSON.stringify(body);
|
|
197
|
+
extra["Content-Type"] = "application/json; charset=UTF-8";
|
|
198
|
+
}
|
|
199
|
+
return sendWithReauth(ctx, (t) => headers(ctx, t, extra), method, url, data, timeout, { unwrap: !opts.raw });
|
|
200
|
+
}
|
|
201
|
+
/** Make a raw-bytes request (for multipart uploads). */
|
|
202
|
+
export async function makeRequestRawBytes(method, path, data, contentType, opts = {}) {
|
|
203
|
+
const ctx = tenants.current();
|
|
204
|
+
await tenants.ensureValid(ctx);
|
|
205
|
+
const timeout = opts.timeout ?? Math.max(120, config.HTTP_TIMEOUT); // uploads need headroom
|
|
206
|
+
const url = path.startsWith("/") ? `${ctx.baseUrl}${path}` : path;
|
|
207
|
+
return sendWithReauth(ctx, (t) => headers(ctx, t, { "Content-Type": contentType }), method, url, data, timeout, { unwrap: false });
|
|
208
|
+
}
|
|
209
|
+
// ---------------------------------------------------------------------------
|
|
210
|
+
// High-level entity helpers
|
|
211
|
+
// ---------------------------------------------------------------------------
|
|
212
|
+
export function dataUrl(entity, action) {
|
|
213
|
+
return `/api/core/data/${entity}/${action}`;
|
|
214
|
+
}
|
|
215
|
+
export function customOrderUrl(entity) {
|
|
216
|
+
return `/api/core/data/custom-order/${entity}`;
|
|
217
|
+
}
|
|
218
|
+
export async function searchEntity(entity, filters = null, fields = null, limit = 50, offset = 0, orderBy = null, searchValue = "", operator = "and") {
|
|
219
|
+
const body = {
|
|
220
|
+
conditions: { operator, filters: filters !== null ? filters : [] },
|
|
221
|
+
fields: fields || { id: true },
|
|
222
|
+
// The platform rejects limit<=0 and a negative offset — clamp instead of
|
|
223
|
+
// surfacing that opaque 400. The upper bound is a backstop against
|
|
224
|
+
// context-window blowouts; tools cap lower.
|
|
225
|
+
limit: Math.max(1, Math.min(limit, 1000)),
|
|
226
|
+
offset: Math.max(0, offset),
|
|
227
|
+
orderBy: orderBy !== null ? orderBy : [{ field: "createdAt", order: "desc" }],
|
|
228
|
+
searchValue,
|
|
229
|
+
getAccessByFields: true,
|
|
230
|
+
includeDeletedRelations: false,
|
|
231
|
+
};
|
|
232
|
+
const result = await makeRequest("POST", dataUrl(entity, "search"), body);
|
|
233
|
+
return Array.isArray(result) ? result : [];
|
|
234
|
+
}
|
|
235
|
+
export async function selectEntity(entity, filters, fields = null) {
|
|
236
|
+
const body = {
|
|
237
|
+
conditions: { operator: "and", filters },
|
|
238
|
+
fields: fields || { id: true },
|
|
239
|
+
getAccessByFields: true,
|
|
240
|
+
includeDeletedRelations: false,
|
|
241
|
+
};
|
|
242
|
+
const result = await makeRequest("POST", dataUrl(entity, "select") + "?markAsView=false", body);
|
|
243
|
+
// The select endpoint returns a list of matching rows; return the first.
|
|
244
|
+
if (Array.isArray(result)) {
|
|
245
|
+
return (result.length ? result[0] : null);
|
|
246
|
+
}
|
|
247
|
+
return result !== null && typeof result === "object"
|
|
248
|
+
? result
|
|
249
|
+
: null;
|
|
250
|
+
}
|
|
251
|
+
export async function insertEntity(entity, fieldsList, returning = null) {
|
|
252
|
+
const body = { fields: fieldsList };
|
|
253
|
+
if (returning) {
|
|
254
|
+
body.returning = returning;
|
|
255
|
+
}
|
|
256
|
+
const result = await makeRequest("POST", dataUrl(entity, "insert"), body);
|
|
257
|
+
if (Array.isArray(result)) {
|
|
258
|
+
return result;
|
|
259
|
+
}
|
|
260
|
+
return result ? [result] : [];
|
|
261
|
+
}
|
|
262
|
+
export async function updateEntity(entity, instanceId, fields) {
|
|
263
|
+
const body = { fields };
|
|
264
|
+
return makeRequest("POST", dataUrl(entity, "update") + `/${instanceId}`, body);
|
|
265
|
+
}
|
|
266
|
+
export async function removeEntity(entity, filters) {
|
|
267
|
+
const body = { conditions: { operator: "and", filters } };
|
|
268
|
+
return makeRequest("POST", dataUrl(entity, "remove"), body);
|
|
269
|
+
}
|
package/dist/registry.js
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Non-secret registry of known tenants, keyed by host.
|
|
3
|
+
*
|
|
4
|
+
* Stored as JSON under the user config dir (`~/.suppa-mcp/tenants.json` by
|
|
5
|
+
* default, overridable with `SUPPA_MCP_HOME`). Contains no secrets — tokens
|
|
6
|
+
* live in the OS keychain (see `store.ts`). Keyed by **host**
|
|
7
|
+
* (`testing.modern.me`) so tenants on different domains that share a first
|
|
8
|
+
* label never collide; the friendly `alias` is just a field.
|
|
9
|
+
*
|
|
10
|
+
* Schema: `{ host: {"alias": string, "base_url": string} }`.
|
|
11
|
+
*
|
|
12
|
+
* Faithful 1:1 port of the Python `suppa_mcp/registry.py`.
|
|
13
|
+
*
|
|
14
|
+
* PYTHON INTEROP: the on-disk file is byte-compatible with the Python server —
|
|
15
|
+
* same location, same schema with snake_case `base_url`, same pretty JSON
|
|
16
|
+
* (`indent=2`, non-ASCII kept literal) — so both runtimes read/write one file.
|
|
17
|
+
*/
|
|
18
|
+
import { mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
|
|
19
|
+
import { homedir } from "node:os";
|
|
20
|
+
import { join } from "node:path";
|
|
21
|
+
/**
|
|
22
|
+
* Base config dir. Reads `SUPPA_MCP_HOME` at CALL time (not cached at import),
|
|
23
|
+
* so an env override set after import still takes effect.
|
|
24
|
+
*/
|
|
25
|
+
export function homeDir() {
|
|
26
|
+
return process.env.SUPPA_MCP_HOME || join(homedir(), ".suppa-mcp");
|
|
27
|
+
}
|
|
28
|
+
/** Path to the tenant registry JSON file. */
|
|
29
|
+
export function path() {
|
|
30
|
+
return join(homeDir(), "tenants.json");
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Coerce stored data into host-keyed form, tolerating the legacy alias-keyed
|
|
34
|
+
* shape `{alias: {host, base_url}}` from earlier builds.
|
|
35
|
+
*/
|
|
36
|
+
function normalize(data) {
|
|
37
|
+
const out = {};
|
|
38
|
+
for (const [key, val] of Object.entries(data)) {
|
|
39
|
+
if (typeof val !== "object" || val === null || Array.isArray(val)) {
|
|
40
|
+
continue;
|
|
41
|
+
}
|
|
42
|
+
const v = val;
|
|
43
|
+
if (!("base_url" in v)) {
|
|
44
|
+
continue;
|
|
45
|
+
}
|
|
46
|
+
const baseUrl = v["base_url"];
|
|
47
|
+
if ("host" in v) {
|
|
48
|
+
// Legacy alias-keyed entry.
|
|
49
|
+
const host = v["host"];
|
|
50
|
+
out[host] = { alias: key, base_url: baseUrl };
|
|
51
|
+
}
|
|
52
|
+
else {
|
|
53
|
+
// Already host-keyed.
|
|
54
|
+
const alias = typeof v["alias"] === "string" ? v["alias"] : key.split(".", 1)[0];
|
|
55
|
+
out[key] = { alias, base_url: baseUrl };
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
return out;
|
|
59
|
+
}
|
|
60
|
+
/** Return `{host: {alias, base_url}}` (empty if none). Never throws. */
|
|
61
|
+
export function load() {
|
|
62
|
+
const p = path();
|
|
63
|
+
let isFile = false;
|
|
64
|
+
try {
|
|
65
|
+
isFile = statSync(p).isFile();
|
|
66
|
+
}
|
|
67
|
+
catch {
|
|
68
|
+
return {};
|
|
69
|
+
}
|
|
70
|
+
if (!isFile) {
|
|
71
|
+
return {};
|
|
72
|
+
}
|
|
73
|
+
try {
|
|
74
|
+
const data = JSON.parse(readFileSync(p, "utf-8"));
|
|
75
|
+
if (typeof data === "object" && data !== null && !Array.isArray(data)) {
|
|
76
|
+
return normalize(data);
|
|
77
|
+
}
|
|
78
|
+
return {};
|
|
79
|
+
}
|
|
80
|
+
catch {
|
|
81
|
+
// Corrupt file: start fresh rather than crash.
|
|
82
|
+
return {};
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Persist the registry with an atomic write: a crash mid-write must not leave a
|
|
87
|
+
* corrupt tenants.json (load() would then silently discard every tenant).
|
|
88
|
+
*/
|
|
89
|
+
export function save(reg) {
|
|
90
|
+
const p = path();
|
|
91
|
+
mkdirSync(homeDir(), { recursive: true });
|
|
92
|
+
const tmp = join(homeDir(), "tenants.json.tmp");
|
|
93
|
+
writeFileSync(tmp, JSON.stringify(reg, null, 2), "utf-8");
|
|
94
|
+
renameSync(tmp, p);
|
|
95
|
+
}
|
|
96
|
+
/** Register (or overwrite) a tenant. */
|
|
97
|
+
export function add(host, alias, baseUrl) {
|
|
98
|
+
const reg = load();
|
|
99
|
+
reg[host] = { alias, base_url: baseUrl };
|
|
100
|
+
save(reg);
|
|
101
|
+
}
|
|
102
|
+
/** Remove a tenant. Returns `true` iff it was present. */
|
|
103
|
+
export function remove(host) {
|
|
104
|
+
const reg = load();
|
|
105
|
+
if (host in reg) {
|
|
106
|
+
delete reg[host];
|
|
107
|
+
save(reg);
|
|
108
|
+
return true;
|
|
109
|
+
}
|
|
110
|
+
return false;
|
|
111
|
+
}
|