formlab-mcp 0.6.99 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -168,7 +168,7 @@ Or from the unpacked package:
168
168
  }
169
169
  ```
170
170
 
171
- Restart Claude Desktop. You should see a hammer icon indicating tools are available, and FormLab's 45 tools become callable in any conversation.
171
+ Restart Claude Desktop. You should see a hammer icon indicating tools are available, and FormLab's 46 tools become callable in any conversation.
172
172
 
173
173
  ## Wire it up to Claude Code
174
174
 
package/calibration.js CHANGED
@@ -18,6 +18,7 @@ function ctx() {
18
18
  vm.runInContext(src + `
19
19
  ;function __calStatus(json, today) { return JSON.stringify(eqCalStatus(JSON.parse(json), today)); }
20
20
  ;function __calHistory(json) { return JSON.stringify(eqCalHistory(JSON.parse(json))); }
21
+ ;function __calWindows(json, today) { return JSON.stringify(eqCalWindows(JSON.parse(json), today)); }
21
22
  ;function __doubt(json, today) {
22
23
  const p = JSON.parse(json), insOf = (m) => ({ name: m.instrument || '', equipmentId: m.equipmentId || '' });
23
24
  const idx = eqCalDoubtIndex(p.equipment, p.tests, insOf, today), out = {};
@@ -53,3 +54,7 @@ export function readingDoubts(db, resolveIns, today) {
53
54
  _doubtMemo = { db, at: now, out };
54
55
  return out;
55
56
  }
57
+
58
+ // A failed / out-of-tolerance calibration's window of doubt, newest first (the app's eqCalWindows): open until its
59
+ // review is closed with a reason; later calibrations never close it.
60
+ export function calibrationWindows(e, today) { return JSON.parse(ctx().__calWindows(_slim(e), today || _today())); }
package/index.js CHANGED
@@ -7,7 +7,7 @@
7
7
  // FORMLAB_EXPORT=/path/to/export.json node index.js
8
8
  // formlab-mcp /path/to/export.json (when installed via npm)
9
9
  //
10
- // Exposes 45 tools (see ./tools/) over stdio. The MCP host (Claude
10
+ // Exposes 46 tools (see ./tools/) over stdio. The MCP host (Claude
11
11
  // Desktop, Claude Code, etc.) handles tool discovery, invocation
12
12
  // and response formatting. We just register handlers and stay out
13
13
  // of the way.
@@ -146,7 +146,14 @@ const PKG_VERSION = (() => {
146
146
 
147
147
  // 0.6.95: the lab's time zone, so a stored UTC time ("…Z") is told as the local day and time (an evening time west of
148
148
  // Greenwich is already tomorrow in UTC). Plain dates are calendar days as entered.
149
- const INSTRUCTIONS = `Times ending in "Z" (createdAt, updatedAt, holdAt, releasedAt, issuedAt, shipment dates…) are UTC. This lab's time zone is ${LOCAL_TZ}: when you give a date or time from one, convert it to ${LOCAL_TZ} first (late evening there can already be the next day in UTC). Plain dates with no time (testDate, preparedDate, expiryDate, best-by) are calendar days as entered: give them as they are. Day fields the server works out (asOf, a report's day when it has no test date, a supplier's lastReceived) are already ${LOCAL_TZ} days.`;
149
+ const INSTRUCTIONS = `Times ending in "Z" (createdAt, updatedAt, holdAt, releasedAt, issuedAt, shipment dates…) are UTC. This lab's time zone is ${LOCAL_TZ}: when you give a date or time from one, convert it to ${LOCAL_TZ} first (late evening there can already be the next day in UTC). Plain dates with no time (testDate, preparedDate, expiryDate, best-by) are calendar days as entered: give them as they are. Day fields the server works out (asOf, a report's day when it has no test date, a supplier's lastReceived) are already ${LOCAL_TZ} days.
150
+
151
+ FormLab's QC definitions (answer by these; never infer them):
152
+ - In doubt (a reading): its instrument failed or was found out of tolerance at a calibration, and the reading falls between the last good calibration before it (with none on record, one calibration interval back, 12 months if no interval is set) and the repair's pass (or today while it still fails), or it was saved while the instrument was Out of service. Later calibrations do not clear it; a retest replaces the reading, or someone closes the instrument's review with a reason. The value and pass/fail stand. Tools: list_test_results in_doubt, get_test_result inDoubt, get_equipment doubtWindows.
153
+ - Retest: repeats only a report's out-of-spec and in-doubt readings, linked (retestOf); it replaces them in rollups and on the CoA.
154
+ - Same-day readings: one point per test date; a day's readings average only under one spec; when two panels judged the same parameter that day, the later report stands.
155
+ - Holds: a held batch cannot ship until released (the Dashboard counts held batches with stock left); a lot on hold has status "hold" (incoming QC puts a received lot on hold until its QC releases it; FormLab does not set "quarantine" or "rejected" today, so a lot awaiting QC is on hold, not quarantined).
156
+ - Certificate of Analysis: latest result per parameter against its spec; required results come from the formula's releasePanel when set, else every panel used. Hard blocks: on hold, not made, no results. Out of spec ("Does not conform") and missing required results ("Not tested") can be issued with an override and a reason; a reading in doubt is only a warning.`;
150
157
  const server = new Server(
151
158
  { name: 'formlab-mcp', version: PKG_VERSION },
152
159
  { capabilities: { tools: {} }, instructions: INSTRUCTIONS }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "formlab-mcp",
3
- "version": "0.6.99",
3
+ "version": "0.7.1",
4
4
  "mcpName": "io.github.juliu1980/formlab-mcp",
5
5
  "description": "Read-only Model Context Protocol server for FormLab. Lets Claude and other MCP clients read and analyze your FormLab data, from a local export file or your live cloud workspace.",
6
6
  "homepage": "https://formvix.com/mcp",
package/server.json CHANGED
@@ -2,13 +2,13 @@
2
2
  "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",
3
3
  "name": "io.github.juliu1980/formlab-mcp",
4
4
  "description": "Read-only MCP server for FormLab formulation data: a local export file or your live cloud workspace.",
5
- "version": "0.6.99",
5
+ "version": "0.7.1",
6
6
  "websiteUrl": "https://formvix.com/mcp",
7
7
  "packages": [
8
8
  {
9
9
  "registryType": "npm",
10
10
  "identifier": "formlab-mcp",
11
- "version": "0.6.99",
11
+ "version": "0.7.1",
12
12
  "runtimeHint": "npx",
13
13
  "transport": {
14
14
  "type": "stdio"
@@ -224,7 +224,7 @@ const list_test_results = {
224
224
  const get_test_result = {
225
225
  definition: {
226
226
  name: 'get_test_result',
227
- description: 'Get full details for a single test result report: every measurement\'s value, unit, type, acceptance criteria, captured run CONDITIONS (e.g. {Storage:"40 °C / 75% RH"} — the storage/temp/RPM the reading was measured under, so it is self-describing and comparable across runs; present only when captured), and the INSTRUMENT that produced it. instrument is RESOLVED (measurement override → the parameter\'s Test Method equipment → the report default) with instrumentSource telling you which — treat source "run" as an inherited assumption, not evidence. For complex measurements a `representative` value is included (time_series → final point, distribution → D50); a time_series also carries `aggregated` (per-timestamp mean ± sd) and `pointReplicates` (true when a timestamp has repeat readings — POINT replicates, averaged per t). The report-level `seriesReplicates` lists parameters measured 2+ times as SEPARATE rows (SERIES replicates). These two notions are different: point replicates are within one run, series replicates are repeated runs. A measurement carries `inDoubt` (the reason) when its instrument failed (or was found out of tolerance at) a calibration after its last good one and the reading falls in that window, or the instrument was Out of service when the report was saved; the value and passFail are unchanged, but say so and recommend a retest before relying on it. Accepts internal id or UID.',
227
+ description: 'Get full details for a single test result report: every measurement\'s value, unit, type, acceptance criteria, captured run CONDITIONS (e.g. {Storage:"40 °C / 75% RH"} — the storage/temp/RPM the reading was measured under, so it is self-describing and comparable across runs; present only when captured), and the INSTRUMENT that produced it. instrument is RESOLVED (measurement override → the parameter\'s Test Method equipment → the report default) with instrumentSource telling you which — treat source "run" as an inherited assumption, not evidence. For complex measurements a `representative` value is included (time_series → final point, distribution → D50); a time_series also carries `aggregated` (per-timestamp mean ± sd) and `pointReplicates` (true when a timestamp has repeat readings — POINT replicates, averaged per t). The report-level `seriesReplicates` lists parameters measured 2+ times as SEPARATE rows (SERIES replicates). These two notions are different: point replicates are within one run, series replicates are repeated runs. A measurement carries `inDoubt` (the reason) when its instrument failed (or was found out of tolerance at) a calibration after its last good one and the reading falls in that window (to the repair, or today while it still fails), or the instrument was Out of service when the report was saved. Later calibrations never clear it; a retest replaces the reading, or a closed review (get_equipment doubtWindows) ends it. The value and passFail are unchanged, but say so and recommend a retest before relying on it. Accepts internal id or UID.',
228
228
  inputSchema: {
229
229
  type: 'object',
230
230
  properties: {
@@ -681,6 +681,17 @@ function _mcpCellValue(r) {
681
681
  return r.value;
682
682
  }
683
683
 
684
+ // The app's flSameDayOneSpec (js/utils.js): a day's readings average only when they share a spec; when two reports
685
+ // judged the parameter on different specs (different panels), the later report of that day stands.
686
+ function _mcpSameDayOneSpec(entries, specOf, testOf) {
687
+ if (!Array.isArray(entries) || entries.length < 2) return entries;
688
+ if (new Set(entries.map(testOf)).size < 2) return entries;
689
+ const sk = e => { try { return JSON.stringify(specOf(e) || null); } catch (_) { return 'null'; } };
690
+ if (new Set(entries.map(sk)).size < 2) return entries;
691
+ const when = e => { const t = testOf(e); return String((t && (t.createdAt || t.testDate)) || ''); };
692
+ const last = testOf(entries.slice().sort((a, b) => when(a).localeCompare(when(b)))[entries.length - 1]);
693
+ return entries.filter(e => testOf(e) === last);
694
+ }
684
695
  function _mcpFlattenReadings(tests, indexes, paramFilter) {
685
696
  const norm = (s) => String(s || '').toLowerCase();
686
697
  const groups = new Map(); const order = [];
@@ -1097,7 +1108,9 @@ function _mcpCoverageRows(flat, grain, indexes) {
1097
1108
  }
1098
1109
  for (const row of rows.values()) {
1099
1110
  row.cells = new Map();
1100
- for (const [param, { date, list }] of row.latest) {
1111
+ for (const [param, { date, list: _all }] of row.latest) {
1112
+ // Same-day readings under different specs: the day's later report stands (the app's flSameDayOneSpec, 30 Nov).
1113
+ const list = _mcpSameDayOneSpec(_all, x => (_resolveSpec(x.m, x.test && x.test.templateId, getStore().db) || {}).spec || null, x => x.test);
1101
1114
  const nums = list.map(x => x.numeric).filter(v => v != null && isFinite(v));
1102
1115
  const mean = nums.length ? nums.reduce((a, b) => a + b, 0) / nums.length : null;
1103
1116
  const pf = list.some(x => x.pf === 'fail') ? 'fail' : list.some(x => x.pf === 'pass') ? 'pass' : list[0].pf;
@@ -31,6 +31,8 @@ function _trimFormulation(f) {
31
31
  // Target shelf life (months): sets finished-goods expiry AND is what
32
32
  // get_stability judges the projected shelf life against.
33
33
  shelfLifeMonths: f.shelfLifeMonths ?? null,
34
+ // The panel a batch is released on: its CoA requires that panel's required results only (else every panel used).
35
+ releasePanel: f.releasePanelId ? (() => { const t = (getStore().db.templates || []).find(x => x && x.id === f.releasePanelId); return { id: f.releasePanelId, name: t ? (t.name || t.uid || '') : null }; })() : null,
34
36
  // Its own stability pull schedule (Stability → Time points → Pull schedule, or its Edit): long = below 35 °C,
35
37
  // accel = 35 °C and up; a number is months, "2w" two weeks; null = the standard schedule. get_stability's timePoints
36
38
  // follow it.
package/tools/library.js CHANGED
@@ -12,7 +12,7 @@
12
12
  // ============================================================
13
13
 
14
14
  import { getStore, resolveById, localDay } from '../data.js';
15
- import { calibrationStatus, calibrationHistory } from '../calibration.js';
15
+ import { calibrationStatus, calibrationHistory, calibrationWindows } from '../calibration.js';
16
16
  import { _evalPassFail, _mcpRepNumber, _mcpMeasType, _resolveSpec, _mcpCondSig, _mcpCondLabel, _mcpCondTags, _mcpParamGroupsOf } from './analytics.js';
17
17
 
18
18
  // ── Usage roll-ups (mirror the Usage tabs on the Panel / Method / Equipment
@@ -181,7 +181,7 @@ const list_equipment = {
181
181
  const get_equipment = {
182
182
  definition: {
183
183
  name: 'get_equipment',
184
- description: 'Get one equipment record by UID (e.g. EQP-001) or id, including `usedIn` (everywhere its DEFINITION is referenced: test panels, step presets, test methods, formula steps, batches, plus testReports = reports with a measurement resolved to it), `usage` (those reports: totals, last used, distinct formulas/batches/samples, pass rate, top formulas) and `measured` (per parameter: readings and mean on this unit vs readings/mean on all OTHER instruments, with biasPct — the calibration question). Instrument resolution follows the app: named on the measurement → the Test Method\'s equipment → the report\'s run default. `calibration` (state ok | soon (≤30 days) | overdue | failed | never, nextDue, lastCalibrated, intervalMonths) and `calibrationHistory` (newest first: date, by, result pass | adjusted | fail, nextDue, certificate, notes) when the instrument is tracked.',
184
+ description: 'Get one equipment record by UID (e.g. EQP-001) or id, including `usedIn` (everywhere its DEFINITION is referenced: test panels, step presets, test methods, formula steps, batches, plus testReports = reports with a measurement resolved to it), `usage` (those reports: totals, last used, distinct formulas/batches/samples, pass rate, top formulas) and `measured` (per parameter: readings and mean on this unit vs readings/mean on all OTHER instruments, with biasPct — the calibration question). Instrument resolution follows the app: named on the measurement → the Test Method\'s equipment → the report\'s run default. `calibration` (state ok | soon (≤30 days) | overdue | failed | never, nextDue, lastCalibrated, intervalMonths) and `calibrationHistory` (newest first: date, by, result pass | adjusted | fail, nextDue, certificate, notes) when the instrument is tracked. `doubtWindows`: each failed (or out-of-tolerance) calibration, the window of readings it puts in doubt (since the last good calibration, or one interval back (lookBackMonths) when none is on record, until the repair or today), and reviewOpen (true = those readings are In doubt; closed = by, at, reason). Later calibrations never close a window; only a closed review or a retest does.',
185
185
  inputSchema: {
186
186
  type: 'object',
187
187
  properties: { id: { type: 'string', description: 'Equipment UID or internal id.' } },
@@ -225,7 +225,11 @@ const get_equipment = {
225
225
  const usedIn = _equipUsage(e, db);
226
226
  usedIn.testReports = tests.length;
227
227
  const calHistory = calibrationHistory(e).map(c => ({ date: c.date || null, by: c.by || '', result: c.result || '', nextDue: c.nextDue || null, ...(c.certificateRef ? { certificate: c.certificateRef } : {}), ...(c.certificateId ? { certificateFile: ((e.fileAttachments || []).find(a => a && a.id === c.certificateId) || {}).name || c.certificateId } : {}), ...(c.notes ? { notes: c.notes } : {}) }));
228
- return { ...(_trimEquipment(e)), ...(calHistory.length ? { calibrationHistory: calHistory } : {}), usedIn, usage: _usageRollup(db, tests, mine), measured };
228
+ // Windows of doubt (0.7.0): each failure / out-of-tolerance finding, the readings window, and whether its review is
229
+ // still open (readings in it are In doubt) or was closed (by whom, when, why).
230
+ const windows = calibrationWindows(e).map(w => ({ failedOn: w.at, kind: w.kind === 'adjusted' ? 'out_of_tolerance' : 'fail', since: w.since || null, lookBackMonths: w.lookBack || null, until: w.until || null,
231
+ repairedOn: w.fixedAt || null, reviewOpen: !w.review, ...(w.review ? { reviewClosed: { by: w.review.by || '', at: w.review.at || null, reason: w.review.reason || '' } } : {}) }));
232
+ return { ...(_trimEquipment(e)), ...(calHistory.length ? { calibrationHistory: calHistory } : {}), ...(windows.length ? { doubtWindows: windows } : {}), usedIn, usage: _usageRollup(db, tests, mine), measured };
229
233
  },
230
234
  };
231
235
 
@@ -145,6 +145,21 @@ function eqCalReviewOf(e, calId) {
145
145
  return last && !last.reopened ? last : null;
146
146
  }
147
147
  // Every window, newest first: { calId, kind, at, since, until, fixedAt, review }.
148
+ // A failure with no good calibration on record before it looks back this far when the instrument has no interval set.
149
+ const EQ_CAL_LOOKBACK_MONTHS = 12;
150
+ function _eqCalSubMonths(iso, months) {
151
+ const [y, m, d] = String(iso).split('-').map(Number);
152
+ const last = new Date(Date.UTC(y, m - 1 - months + 1, 0)).getUTCDate();
153
+ const t = new Date(Date.UTC(y, m - 1 - months, Math.min(d, last)));
154
+ return t.toISOString().slice(0, 10); // a calendar date built in UTC, not "today": no time-zone shift
155
+ }
156
+ // Where a window starts, in words: "since its last good calibration (2026-08-28)", or for a look-back
157
+ // "since 2025-11-22 (one calibration interval before the failure; no good calibration on record before it)".
158
+ function eqCalSinceText(w) {
159
+ if (!w || !w.since) return 'before any good calibration on record';
160
+ if (!w.lookBack) return `since its last good calibration (${w.since})`;
161
+ return `since ${w.since} (${w.lookBackDefault ? `${w.lookBack} months` : 'one calibration interval'} before the failure; no good calibration on record before it)`;
162
+ }
148
163
  function eqCalWindows(e, todayIso) {
149
164
  const hist = eqCalHistory(e);
150
165
  const res = (c) => String((c && c.result) || '').trim().toLowerCase();
@@ -156,7 +171,14 @@ function eqCalWindows(e, todayIso) {
156
171
  const before = hist.slice(i + 1).find(good);
157
172
  let fixed = null; for (let j = i - 1; j >= 0; j--) { if (good(hist[j])) { fixed = hist[j]; break; } }
158
173
  const until = kind === 'adjusted' ? (bad.date || '') : ((fixed && fixed.date) || todayIso || _eqCalToday());
159
- out.push({ calId: bad.id || '', kind, at: bad.date || '', since: (before && before.date) || '', until, fixedAt: kind === 'fail' && fixed ? (fixed.date || '') : '', review: bad.id ? eqCalReviewOf(e, bad.id) : null });
174
+ // No good calibration on record before the failure (Jun, 1 Dec: "One interval back"): the window reaches back one
175
+ // calibration interval from the failure (12 months when no interval is set), not to the instrument's first reading.
176
+ let since = (before && before.date) || '', lookBack = 0, lookBackDefault = false;
177
+ if (!since && _EQ_CAL_ISO.test(String(bad.date || ''))) {
178
+ lookBack = eqCalInterval(e) || EQ_CAL_LOOKBACK_MONTHS; lookBackDefault = !eqCalInterval(e);
179
+ since = _eqCalSubMonths(bad.date, lookBack);
180
+ }
181
+ out.push({ calId: bad.id || '', kind, at: bad.date || '', since, lookBack, lookBackDefault, until, fixedAt: kind === 'fail' && fixed ? (fixed.date || '') : '', review: bad.id ? eqCalReviewOf(e, bad.id) : null });
160
182
  });
161
183
  return out;
162
184
  }
@@ -178,7 +200,7 @@ function eqCalSuspect(e, tests, todayIso) {
178
200
  const b = sm && sm.batchId ? (db.batches || []).find(x => x && x.id === sm.batchId && !x._trashed) : null;
179
201
  if (b && !batches.includes(b)) batches.push(b);
180
202
  });
181
- return { calId: w.calId, kind: w.kind, at: w.at, since: w.since, until: w.until, fixedAt: w.fixedAt, tests: hit, batches, open: open.length };
203
+ return { calId: w.calId, kind: w.kind, at: w.at, since: w.since, lookBack: w.lookBack, lookBackDefault: w.lookBackDefault, until: w.until, fixedAt: w.fixedAt, tests: hit, batches, open: open.length };
182
204
  }
183
205
 
184
206
  // ---- Readings in doubt (Jun, 30 Nov: "Flag doubtful readings"; shared with the MCP server) ----
@@ -199,7 +221,7 @@ function eqCalDoubtIndex(equipment, tests, insOf, todayIso) {
199
221
  open.forEach(w => {
200
222
  const hit = _eqCalWindowTests(w, used);
201
223
  if (!hit.length) return;
202
- const from = w.since ? `after its last good calibration (${w.since})` : 'before any good calibration on record';
224
+ const from = eqCalSinceText(w).replace(/^since its last/, 'after its last');
203
225
  const why = w.kind === 'adjusted' ? `Taken on ${name} ${from}; it was found out of tolerance on ${w.at}.`
204
226
  : w.fixedAt ? `Taken on ${name} ${from} and before the repair passed on ${w.fixedAt}; it failed calibration on ${w.at}.`
205
227
  : `Taken on ${name} ${from}; it failed calibration on ${w.at} and has not passed since.`;
@@ -258,7 +280,7 @@ function eqCalCardHtml(e) {
258
280
  const susHtml = sus && sus.tests.length ? (() => {
259
281
  const uids = sus.tests.map(t => t.uid).filter(Boolean);
260
282
  // Counts, not a run of eight batch links and "+79" (30 Nov layout check): the Equipment report and Test Reports list them.
261
- const when = sus.since ? `since its last good calibration (${esc(sus.since)})` : 'before any good calibration on record';
283
+ const when = esc(eqCalSinceText(sus));
262
284
  const n = `<strong>${sus.tests.length} test report${sus.tests.length === 1 ? '' : 's'}</strong>${sus.batches.length ? ` and <strong>${sus.batches.length} batch${sus.batches.length === 1 ? '' : 'es'}</strong>` : ''}`;
263
285
  const head = sus.kind === 'adjusted' ? `Found out of tolerance on ${esc(sus.at)}: ${n} used it ${when}.`
264
286
  : sus.fixedAt ? `Failed on ${esc(sus.at)}, passed again on ${esc(sus.fixedAt)}: ${n} used it ${when} until then.`