@velaro/mcp-server 0.6.103 → 0.6.104

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
@@ -154,6 +154,12 @@ This works with any MCP client that supports HTTP/SSE transport — including Cl
154
154
  |------|-------------|
155
155
  | `site_info` | Get site settings, active channels, subscription features, and resource counts |
156
156
 
157
+ ### Email Signatures
158
+ | Tool | What It Does |
159
+ |------|-------------|
160
+ | `signature_policy_get` | Read the company email signature policy: mode, company signature, legal disclaimer, per-team overrides (admin only) |
161
+ | `signature_policy_set` | Change the signature policy (locked, company-default or personal-only), the company signature, the optional legal disclaimer, company-wide or for one team (admin only) |
162
+
157
163
  ### Live Operations
158
164
  | Tool | What It Does |
159
165
  |------|-------------|
package/log-search.js ADDED
@@ -0,0 +1,252 @@
1
+ // Complete Velaro Logger reads (2026-10-14).
2
+ //
3
+ // WHY: velaro-messaging's /superadmin/logs/search and /internal/logs/search silently under-reported text queries.
4
+ // Proven live that day: q=[HttpFallback] over 3.9 h returned 0-2 rows while 136 existed, and q=AsrsNegotiateFailed
5
+ // (no level) returned 0 while 4 existed. The AI-search path only saw the newest 1,000 candidates and its answer was
6
+ // final; the exact path only saw the newest 5,000 rows of the window before filtering. Neither said so.
7
+ //
8
+ // TWO MODES, picked automatically from the first response:
9
+ // * CURSOR mode (server with velaro-messaging PR #2510, response carries `truncated`/`scannedRows`): the server scans the
10
+ // window newest-first applying level/site AND text (as an escaped regex, which also forces the exact path) while it
11
+ // scans, reports `truncated`, and returns `nextCursor` whenever more rows may exist. We follow the cursor until it is
12
+ // null, so a 2 h window is a handful of requests instead of hundreds.
13
+ // * BISECT mode (older server): never send q=; push level/site/etc server side; includeTotal=true reports
14
+ // totalCountCapped for a slice; a capped slice is bisected until none is capped; text is filtered client side.
15
+ // Either way the result says COMPLETE or INCOMPLETE, so a 0 is never ambiguous. Hard caps: maxRequests and maxSeconds.
16
+ //
17
+ // KEEP IN SYNC: this file is duplicated byte for byte in mcp/log-search.js (the npm packages ship separately);
18
+ // cli/lib/log-search.test.js fails if the two copies drift.
19
+
20
+ const MIN_SLICE_MS = 2000;
21
+
22
+ export const escapeRegex = (s) => String(s).replace(/[\\^$.*+?()[\]{}|]/g, '\\$&');
23
+
24
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
25
+ const tsOf = (e) => { const t = Date.parse(e.timestamp ?? e.LogTimestamp ?? ''); return Number.isNaN(t) ? 0 : t; };
26
+
27
+ /**
28
+ * fetch that retries ONLY 429 (honouring Retry-After, seconds, capped at 30 s) for up to `retries` attempts and returns the final Response.
29
+ * `init` may be a function so each attempt gets a fresh AbortSignal.
30
+ */
31
+ export async function fetchRetry429(url, init = {}, { retries = 3, fetchImpl = fetch, sleepImpl = sleep } = {}) {
32
+ for (let attempt = 0; ; attempt++) {
33
+ const res = await fetchImpl(url, typeof init === 'function' ? init() : init);
34
+ if (res.status === 429 && attempt < retries) {
35
+ // Number(null) is 0, which would turn a 429 without Retry-After into an immediate retry: a missing header means the 5 s default.
36
+ const raw = res.headers?.get?.('retry-after');
37
+ const ra = raw == null || raw === '' ? NaN : Number(raw);
38
+ await sleepImpl(Math.min(Number.isFinite(ra) && ra >= 0 ? ra : 5, 30) * 1000);
39
+ continue;
40
+ }
41
+ return res;
42
+ }
43
+ }
44
+
45
+ /** fetchRetry429 + JSON. Any non-2xx throws an Error carrying `.status` and the response text. */
46
+ export async function fetchJsonRetry(url, init = {}, opts = {}) {
47
+ const res = await fetchRetry429(url, init, opts);
48
+ if (!res.ok) {
49
+ const err = new Error(`HTTP ${res.status}: ${(await res.text().catch(() => '')).slice(0, 400)}`);
50
+ err.status = res.status;
51
+ throw err;
52
+ }
53
+ return res.json();
54
+ }
55
+
56
+ /**
57
+ * @param {object} o
58
+ * @param {(query: string) => Promise<any>} o.fetchJson GET `...search?<query>` and return parsed JSON (caller adds auth/timeout)
59
+ * @param {Date} o.from
60
+ * @param {Date} o.to
61
+ * @param {object} [o.params] server-side filters: level, siteId, source, integration, platform, environment, correlationId
62
+ * @param {string} [o.contains] case-insensitive substring of the message
63
+ * @param {string} [o.regex] regex on the message
64
+ * @param {string} [o.logger] substring of the logger name
65
+ * @param {number} [o.maxRequests=200]
66
+ * @param {number} [o.maxSeconds=120] wall-clock budget for the whole read
67
+ * @param {number} [o.wanted=Infinity] CURSOR mode: stop once this many matches were collected (newest first); the result is then `satisfied`
68
+ */
69
+ export async function completeLogSearch({ fetchJson, from, to, params = {}, contains, regex, logger, maxRequests = 200, maxSeconds = 120, wanted = Infinity }) {
70
+ const server = {};
71
+ for (const k of ['level', 'siteId', 'source', 'integration', 'platform', 'environment', 'correlationId']) {
72
+ if (params[k] !== undefined && params[k] !== null && params[k] !== '') server[k] = String(k === 'level' ? String(params[k]).toUpperCase() : params[k]);
73
+ }
74
+ const byId = new Map();
75
+ const unresolved = [];
76
+ const started = Date.now();
77
+ let requests = 0;
78
+ let slices = 0;
79
+ let scanned = 0;
80
+ let budgetExhausted = false;
81
+ let timeExhausted = false;
82
+
83
+ const canRequest = () => {
84
+ if (requests >= maxRequests) { budgetExhausted = true; return false; }
85
+ if ((Date.now() - started) / 1000 >= maxSeconds && requests > 0) { timeExhausted = true; return false; }
86
+ return true;
87
+ };
88
+ const norm = (r) => (Array.isArray(r) ? { entries: r } : (r || {}));
89
+ const add = (e) => byId.set(e.id ?? `${e.timestamp}|${e.message}`, e);
90
+
91
+ // ---- text handling shared by both modes ----
92
+ const textQ = regex ?? (contains ? escapeRegex(contains) : undefined);
93
+ const textLogger = logger ? escapeRegex(logger) : undefined;
94
+
95
+ // ---- probe: first CURSOR-mode page, doubles as the new-server detector ----
96
+ const cursorQuery = (cursor) => {
97
+ const q = new URLSearchParams({ from: from.toISOString(), to: to.toISOString(), take: '500', ...server });
98
+ if (textQ) q.set('q', textQ);
99
+ if (textLogger) q.set('logger', textLogger);
100
+ if (textQ || textLogger) q.set('regex', 'true'); // regex also forces the exact path (the AI-search path is never consulted)
101
+ q.set('fallthrough', 'false');
102
+ if (cursor) q.set('cursor', cursor);
103
+ return q.toString();
104
+ };
105
+
106
+ let mode = 'bisect';
107
+ let satisfied = false;
108
+ let cursorDone = false;
109
+
110
+ if (canRequest()) {
111
+ requests++;
112
+ const probe = norm(await fetchJson(cursorQuery(null)));
113
+ if (typeof probe.truncated === 'boolean') {
114
+ mode = 'cursor';
115
+ scanned += Number(probe.scannedRows ?? 0);
116
+ for (const e of probe.entries ?? []) add(e);
117
+ let page = probe;
118
+ let cursor = probe.nextCursor || null;
119
+ for (;;) {
120
+ // The ONLY way a cursor read is COMPLETE: the last page said truncated === false and carried no cursor. `truncated: true` with no
121
+ // cursor means the server stopped scanning (deadline/cap) and could not say where to continue: INCOMPLETE, never COMPLETE.
122
+ if (!cursor) {
123
+ if (page.truncated === false) cursorDone = true;
124
+ else unresolved.push('the server stopped scanning (truncated) without a cursor to continue from');
125
+ break;
126
+ }
127
+ if (byId.size >= wanted) { satisfied = true; break; }
128
+ if (!canRequest()) { unresolved.push(`cursor ${cursor} (${timeExhausted ? 'time budget' : 'request budget'})`); break; }
129
+ requests++;
130
+ const next = norm(await fetchJson(cursorQuery(cursor)));
131
+ scanned += Number(next.scannedRows ?? 0);
132
+ for (const e of next.entries ?? []) add(e);
133
+ if (next.nextCursor && next.nextCursor === cursor) {
134
+ unresolved.push('no progress: the server returned the cursor it was given (its scan budget ended before reaching any row)');
135
+ break;
136
+ }
137
+ page = next;
138
+ cursor = next.nextCursor || null;
139
+ }
140
+ slices = 1;
141
+ }
142
+ }
143
+
144
+ // ---- BISECT mode (older server) ----
145
+ if (mode === 'bisect' && !budgetExhausted) {
146
+ const call = async (a, b, cursor, total) => {
147
+ if (!canRequest()) return null;
148
+ requests++;
149
+ const q = new URLSearchParams({ from: a.toISOString(), to: b.toISOString(), take: '500', ...server });
150
+ if (total) q.set('includeTotal', 'true');
151
+ if (cursor) q.set('cursor', cursor);
152
+ return norm(await fetchJson(q.toString()));
153
+ };
154
+ const walk = async (a, b) => {
155
+ const r = await call(a, b, null, true);
156
+ if (!r) { unresolved.push(`${a.toISOString()}..${b.toISOString()} (${timeExhausted ? 'time' : 'request'} budget)`); return; }
157
+ if (r.totalCountCapped === true && (b - a) > MIN_SLICE_MS) {
158
+ const mid = new Date(a.getTime() + Math.floor((b - a) / 2));
159
+ await walk(a, mid);
160
+ await walk(mid, b);
161
+ return;
162
+ }
163
+ if (r.totalCountCapped === true) unresolved.push(`${a.toISOString()}..${b.toISOString()} (still capped at <=2s: a log storm; add level/site)`);
164
+ slices++;
165
+ scanned += Number(r.totalCount ?? (r.entries?.length ?? 0));
166
+ for (const e of r.entries ?? []) add(e);
167
+ let cursor = r.nextCursor;
168
+ while (cursor) {
169
+ const r2 = await call(a, b, cursor, false);
170
+ if (!r2) { unresolved.push(`${a.toISOString()}..${b.toISOString()} (budget while paging)`); break; }
171
+ for (const e of r2.entries ?? []) add(e);
172
+ cursor = r2.nextCursor;
173
+ }
174
+ };
175
+ await walk(from, to);
176
+ }
177
+
178
+ let rows = [...byId.values()];
179
+ const msg = (e) => String(e.message ?? e.Message ?? '');
180
+ if (mode === 'bisect') {
181
+ if (contains) { const c = contains.toLowerCase(); rows = rows.filter((e) => msg(e).toLowerCase().includes(c)); }
182
+ if (regex) { const re = new RegExp(regex, 'i'); rows = rows.filter((e) => re.test(msg(e))); }
183
+ if (logger) { const l = logger.toLowerCase(); rows = rows.filter((e) => String(e.logger ?? e.Logger ?? '').toLowerCase().includes(l)); }
184
+ }
185
+ rows.sort((x, y) => tsOf(y) - tsOf(x)); // compare as instants: fractional-second digit counts differ between rows
186
+
187
+ const complete = mode === 'cursor' ? (cursorDone && unresolved.length === 0) : (unresolved.length === 0 && !budgetExhausted && !timeExhausted);
188
+ return { entries: rows, fetched: byId.size, scanned, requests, slices, mode, complete, satisfied, unresolved, budgetExhausted, timeExhausted };
189
+ }
190
+
191
+ /** One line a human or an LLM can trust: says COMPLETE or INCOMPLETE and how much the SERVER actually scanned. */
192
+ export function describeCompleteness(r) {
193
+ const base = `${r.entries.length} matched (${r.fetched} fetched; server scanned ${r.scanned} rows) in ${r.requests} request(s), ${r.mode} mode`;
194
+ if (r.satisfied) return `${base}; showing the newest matches, more may exist beyond what was asked for (stopped early on purpose).`;
195
+ return r.complete
196
+ ? `${base}; COMPLETE (the whole window was covered), so 0 matches means nothing was logged.`
197
+ : `${base}; INCOMPLETE (${r.unresolved.length} part(s) not covered${r.budgetExhausted ? ', request budget exhausted' : ''}${r.timeExhausted ? ', time budget exhausted' : ''}): narrow the window or add level/site; a short or empty result is NOT proof of absence.`;
198
+ }
199
+
200
+ /** For raw (server-side q=) responses: surfaces searchPath/scannedRows/truncated so a 0 is never ambiguous. */
201
+ export function describeRawMeta(resp) {
202
+ if (!resp || Array.isArray(resp) || resp.scannedRows === undefined) {
203
+ return 'server did not report scan metadata (older deploy): treat an empty or short result as unverified, use the complete mode.';
204
+ }
205
+ const t = resp.truncated === true;
206
+ // exact=false: the answer involves the AI-search index, which is best-effort (written behind, can lag, misses text that starts mid-word).
207
+ const bestEffort = resp.exact === false ? ' exact=false (answered from the best-effort search index: it can lag and misses text that starts mid-word, so treat counts as a floor, not exact)' : '';
208
+ return `searchPath=${resp.searchPath} scannedRows=${resp.scannedRows} truncated=${t}${t ? ' (NOT proof of absence; continue with nextCursor or narrow the window)' : ''}${bestEffort}${resp.nextCursor ? ' nextCursor=present' : ''}`;
209
+ }
210
+
211
+ // ── Time window + raw query building (shared by server.js and staff-server.js velaro_logs_search) ──
212
+ // Bug fixed 2026-10-21: the tool only honored `last` and silently ignored from/to, so an explicit
213
+ // historical range returned the newest entries instead. from/to accept an ISO timestamp or a
214
+ // relative duration (30m, 2h, 1d = that long ago). `to` defaults to now, `from` to to - last (2h).
215
+ const DUR_RE = /^(\d+)(m|h|d)$/i;
216
+ const durMs = (s) => {
217
+ const m = DUR_RE.exec(String(s).trim());
218
+ const n = parseInt(m[1], 10);
219
+ const u = m[2].toLowerCase();
220
+ return u === 'm' ? n * 60000 : u === 'h' ? n * 3600000 : n * 86400000;
221
+ };
222
+ function parseWhen(label, v, nowMs) {
223
+ const s = String(v).trim();
224
+ if (DUR_RE.test(s)) return new Date(nowMs - durMs(s));
225
+ const d = new Date(s);
226
+ if (Number.isNaN(d.getTime())) throw new Error(`Invalid ${label} "${v}": use an ISO timestamp (2026-10-20T00:00:00Z) or a relative duration like 2h.`);
227
+ return d;
228
+ }
229
+ export function resolveLogWindow(args = {}, nowMs = Date.now()) {
230
+ const given = (v) => v !== undefined && v !== null && String(v).trim() !== '';
231
+ const to = given(args.to) ? parseWhen('to', args.to, nowMs) : new Date(nowMs);
232
+ const lastMs = DUR_RE.test(String(args.last ?? '').trim()) ? durMs(args.last) : 2 * 3600000;
233
+ const from = given(args.from) ? parseWhen('from', args.from, nowMs) : new Date(to.getTime() - lastMs);
234
+ if (from.getTime() >= to.getTime()) throw new Error(`Invalid window: from (${from.toISOString()}) must be before to (${to.toISOString()}).`);
235
+ return { from, to };
236
+ }
237
+
238
+ // Query string for GET /superadmin/logs/search (same params as /internal/logs/search).
239
+ export function buildRawLogQuery(args, from, to) {
240
+ const params = new URLSearchParams({ from: from.toISOString(), to: to.toISOString(), take: String(args.take ?? 50) });
241
+ if (args.q) params.set('q', args.q);
242
+ if (args.level) params.set('level', String(args.level).toUpperCase());
243
+ if (args.logger) params.set('logger', args.logger);
244
+ if (args.integration) params.set('integration', args.integration);
245
+ if (args.siteId) params.set('siteId', String(args.siteId));
246
+ if (args.source) params.set('source', args.source);
247
+ if (args.platform) params.set('platform', args.platform);
248
+ if (args.environment) params.set('environment', args.environment);
249
+ if (args.correlationId) params.set('correlationId', args.correlationId);
250
+ if (args.regex) params.set('regex', 'true');
251
+ return params.toString();
252
+ }
@@ -0,0 +1,21 @@
1
+ // Resolves the velaro-messaging API base for the MCP server.
2
+ //
3
+ // Incident 2026-10-23: the staging MCP was configured with VELARO_ADMIN_API only. Every tool that
4
+ // lives in velaro-messaging (magento_diagnose, salesforce_diagnose, sap_diagnose, ...) either threw
5
+ // "VELARO_MESSAGING_API is not configured" or, on older installs, called the ADMIN host and got a
6
+ // bare 404 for /diagnostics/test-magento. The messaging base is fully determined by which admin
7
+ // environment this process talks to, so derive it instead of requiring a second env var.
8
+ export const MESSAGING_API_HOSTS = {
9
+ staging: 'https://velaro-messaging-api-staging.azurewebsites.net',
10
+ production: 'https://api-messaging-us-east.velaro.com',
11
+ };
12
+
13
+ /** Explicit VELARO_MESSAGING_API always wins; otherwise follow the admin environment. */
14
+ export function resolveMessagingApi(explicit, adminApi) {
15
+ const e = (explicit ?? '').trim();
16
+ if (e) return e.replace(/\/$/, '');
17
+ const a = (adminApi ?? '').toLowerCase();
18
+ if (a.includes('staging')) return MESSAGING_API_HOSTS.staging;
19
+ if (a.includes('api-admin-us-east.velaro.com') || a.includes('help.velaro.com')) return MESSAGING_API_HOSTS.production;
20
+ return null; // unknown/custom admin host: stay explicit, never guess a different environment
21
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@velaro/mcp-server",
3
- "version": "0.6.103",
3
+ "version": "0.6.104",
4
4
  "description": "Velaro MCP server — connect Claude and other AI agents directly to your Velaro account: KB, workflows, bots, conversations, contacts, routing, and more.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -15,7 +15,7 @@
15
15
  },
16
16
  "overrides": {
17
17
  "qs": "^6.16.0",
18
- "hono": "^4.13.5"
18
+ "hono": "^4.13.11"
19
19
  },
20
20
  "scripts": {
21
21
  "start": "node server.js"
@@ -42,6 +42,9 @@
42
42
  "license": "MIT",
43
43
  "files": [
44
44
  "server.js",
45
+ "tool-annotations.js",
46
+ "log-search.js",
47
+ "messaging-base.js",
45
48
  "server.json",
46
49
  "README.md"
47
50
  ],