formlab-mcp 0.6.22 → 0.6.24

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
@@ -29,7 +29,7 @@ Ask Claude (or another MCP client) things like:
29
29
  | Tool | Purpose |
30
30
  |---|---|
31
31
  | `list_formulations` | Filtered list of recipes |
32
- | `get_formulation` | Full record + flattened wt-% composition (sub-formulas expanded), the ordered **step procedure**, user **custom fields**, and any **process-factor values** (DOE inputs — cure temp, mix time, RPM, pH…) |
32
+ | `get_formulation` | Full record + flattened wt-% composition (sub-formulas expanded), the ordered **step procedure**, user **custom fields**, any **process-factor values** (DOE inputs — cure temp, mix time, RPM, pH…), and the declared **finishedDensity** (g/mL of the mixed product; volume-targeted batches scale by it) |
33
33
  | `find_similar_formulations` | Find formulas using a given ingredient ≥ threshold % |
34
34
  | `compare_formulations` | Pairwise side-by-side composition diff |
35
35
  | `list_ingredients` | Filtered list of raw materials. Filters: `family`, `supplier`, `name_contains`, `in_stock_only`, `ingredient_class` (small-molecule / surfactant / polymer / extract / fragrance / pigment / sequence / mixture), `sequence_contains` (e.g. `KTTKS` → Matrixyl), `taxon_contains` (e.g. `Centella`) |
@@ -39,7 +39,7 @@ Ask Claude (or another MCP client) things like:
39
39
  | `get_supplier` | One supplier in full: record, every ingredient it's an approved source for, every lot from it, and the **recall trace** (batches that consumed those lots → products, shipments, samples, sub-batches; lots on hold flagged) |
40
40
  | `list_inventory` | Portfolio stock rollup — one row per ingredient with on-hand qty, summed lot balance, nearest expiry, and a low-stock flag (on-hand ≤ `reorderThreshold`, or zero). Filters: `low_stock_only`, `expiring_within_days`, `family` |
41
41
  | `list_batches` | Filtered list of production / lab-prep events |
42
- | `get_batch` | Full record + actual composition, measured/derived **actual volume** (mass ÷ density, never a sum of per-ingredient volumes) and **actual mass** (yield, else summed inputs, else measured volume × density), the **process** method + any **process-factor values** (DOE inputs), samples + blend lineage, and — as a finished-goods lot — its storage **`location`** + finished-goods **`stockLedger`** (shipments out + adjustments; `shippedQty` total) |
42
+ | `get_batch` | Full record + actual composition, measured/derived **actual volume** (mass ÷ density, never a sum of per-ingredient volumes) and **actual mass** (yield, else summed as-prepared inputs — mL rows through that ingredient's density — else measured volume × density), **estimatedVolume** (mass ÷ the formula's finished density when no actual exists, flagged `estimate: true`), **plannedMass** for volume-target batches (target × finished density) and **formulaFinishedDensity**, the **process** method + any **process-factor values** (DOE inputs), samples + blend lineage, and — as a finished-goods lot — its storage **`location`** + finished-goods **`stockLedger`** (shipments out + adjustments; `shippedQty` total) |
43
43
  | `list_samples` | Filtered list of physical specimens |
44
44
  | `get_sample` | Full record + canonical variant + test reports + blend lineage |
45
45
  | `list_test_results` | Filtered list of test reports (by sample, parameter, **measured-value range** (`value_min`/`value_max`), date, or lab) |
@@ -56,13 +56,13 @@ Ask Claude (or another MCP client) things like:
56
56
  | `get_doe_design` | One design in full: constraints in plain language, the model it was optimised for, generation settings (run budget, replicates, centre points, seed) and the complete run matrix with the formulation each run became |
57
57
  | `find_by_smarts` | SMARTS-pattern substructure search across every ingredient with a SMILES. Requires `@rdkit/rdkit` (optional dependency — install with `npm install @rdkit/rdkit` in `mcp/` if you get a "not installed" error). Examples: `c1ccccc1` (any aromatic 6-ring), `[OX2H1]` (any hydroxyl), `C(=O)O` (carboxylic acid), `[F,Cl,Br,I]` (any halogen). |
58
58
  | `list_equipment` | Filtered list of the Equipment registry (mixers, ovens, viscometers, balances…). Filters: `category`, `status`, `manufacturer`, `name_contains` |
59
- | `get_equipment` | Full equipment record + a summary of where it's used (panels, step presets, test methods, formulas, batches) |
59
+ | `get_equipment` | Full equipment record + `usedIn` (panels, step presets, test methods, formula steps, batches, testReports resolved to it), `usage` (reports / formulas / batches / samples / pass rate / top formulas) and `measured` (per parameter: mean here vs mean on other instruments, biasPct) |
60
60
  | `list_test_methods` | Filtered list of Test Methods (the parameter library). Filter by `analyte` (the property measured, e.g. `Viscosity` — finds every method for it), `category`, `name_contains`, `include_retired` |
61
- | `get_test_method` | Full method definition (SOP / sample prep / equipment / calculation / acceptance spec) + sibling methods sharing its analyte |
61
+ | `get_test_method` | One Test Method: full definition, run conditions, analyte siblings, using panels, plus `usage`, `valueSummary` (mean / sd / min / max) and `byInstrument` |
62
62
  | `list_step_presets` | Filtered list of Step Presets (reusable procedure steps: duration / temp / RPM / equipment). Filters: `industry`, `name_contains` |
63
63
  | `get_step_preset` | Full step-preset record incl. the multi-value equipment list (`{name, equipmentId}`) |
64
64
  | `list_test_panels` | Filtered list of Test Panels (reusable column-sets — the parameters measured together on a sample). Filters: `industry`, `name_contains` |
65
- | `get_test_panel` | Full panel record — ordered parameter list (each with resolved Test Method UID, unit, spec) + instruments |
65
+ | `get_test_panel` | One Test Panel: ordered parameters with resolved method UIDs + specs, plus `usage` (reports created from it) and `performanceByParameter` |
66
66
  | `list_projects` | Filtered list of projects (the buckets formulations are filed under) + per-project formulation count. Filters: `status`, `name_contains` |
67
67
  | `get_project` | Full project record + the formulations filed under it |
68
68
  | `list_notebook_entries` | ELN feed — dated authored notes attached to records. Filters: `entity_type`, `entity_id`, `author`, `text_contains`, `since`, `until` |
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "formlab-mcp",
3
- "version": "0.6.22",
3
+ "version": "0.6.24",
4
4
  "mcpName": "io.github.juliu1980/formlab-mcp",
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.",
5
+ "description": "Read-only Model Context Protocol server for FormLab \u2014 lets Claude (and other MCP clients) read and analyze your FormLab data, from a local export file OR your live cloud workspace.",
6
6
  "type": "module",
7
7
  "bin": {
8
8
  "formlab-mcp": "./index.js"
@@ -913,6 +913,7 @@ const get_stability = {
913
913
  },
914
914
  };
915
915
 
916
+ export { _evalPassFail };
916
917
  export const tools = {
917
918
  list_test_results,
918
919
  get_test_result,
@@ -23,6 +23,11 @@ function _trimFormulation(f) {
23
23
  owner: f.owner || '',
24
24
  regulatoryCategory: f.regulatoryCategory || '',
25
25
  shelfLifeMonths: f.shelfLifeMonths ?? null,
26
+ // Density of the MIXED product (g/mL), when declared — volume-targeted
27
+ // batches scale by it instead of the ideal-mix estimate. null = not set.
28
+ finishedDensity: (f.finishedDensity && isFinite(parseFloat(f.finishedDensity.value)))
29
+ ? { value: parseFloat(f.finishedDensity.value), temp: f.finishedDensity.temp ?? null, source: f.finishedDensity.source || 'manual', batchId: f.finishedDensity.batchId || null, date: f.finishedDensity.date || null }
30
+ : null,
26
31
  tags: f.tags || [],
27
32
  projectId: f.projectId || null,
28
33
  compositionRowCount: (f.composition || []).length,
package/tools/lab.js CHANGED
@@ -25,16 +25,57 @@ function _batchUnitMassKg(b) {
25
25
  const v = parseFloat(b.unitMass.value);
26
26
  return (isFinite(v) && v > 0) ? _massToKg(v, b.unitMass.unit) : null;
27
27
  }
28
- function _batchActualMassKg(b) {
28
+ // Ingredient density → kg/L (=== g/mL). Mirrors the app's _densityToKgPerL for
29
+ // the units it accepts; unknown unit → treated as g/mL (the app's default).
30
+ const _DENS_TO_KGL = { 'g/ml': 1, 'g/cm3': 1, 'g/cm³': 1, 'g/cc': 1, 'kg/l': 1, 'kg/m3': 0.001, 'kg/m³': 0.001, 'g/l': 0.001, 'lb/gal': 0.119826, 'lb/ft3': 0.0160185, 'lb/ft³': 0.0160185 };
31
+ function _densKgPerL(v, u) { const d = parseFloat(v); if (!isFinite(d) || d <= 0) return null; const f = _DENS_TO_KGL[String(u || 'g/mL').trim().toLowerCase()]; return d * (f == null ? 1 : f); }
32
+ // Density of ONE as-prepared row: the ingredient's own density, or a sub-
33
+ // formula's declared finished density. null when unknown.
34
+ function _rowDensityKgPerL(c, ingredientsById, formulationsById) {
35
+ if (c.ingredientId && ingredientsById) { const ing = ingredientsById.get(c.ingredientId); return ing ? _densKgPerL(ing.density, ing.densityUnit) : null; }
36
+ if (c.formulationId && formulationsById) { const sf = formulationsById.get(c.formulationId); return sf ? _formulaFinishedDensity(sf) : null; }
37
+ return null;
38
+ }
39
+ // The formula's DECLARED finished density (g/mL) — adopted from a measured
40
+ // batch or entered from a spec. The app also has an ideal-mix estimate from
41
+ // ingredient densities; MCP does not reproduce that (estimate) and returns
42
+ // null instead, so a null here means "the app plans with an estimate".
43
+ function _formulaFinishedDensity(f) {
44
+ const v = f && f.finishedDensity ? parseFloat(f.finishedDensity.value) : NaN;
45
+ return (isFinite(v) && v > 0) ? v : null;
46
+ }
47
+ function _finishedDensityInfo(f, batchesById) {
48
+ const v = _formulaFinishedDensity(f);
49
+ if (v == null) return null;
50
+ const fd = f.finishedDensity;
51
+ const src = (fd.batchId && batchesById) ? batchesById.get(fd.batchId) : null;
52
+ return { value: v, unit: 'g/mL', temp: fd.temp ?? null, source: fd.source || 'manual', fromBatch: src ? src.uid : null, date: fd.date || null };
53
+ }
54
+ // Σ as-prepared row masses in kg, each row through ITS OWN unit: g rows
55
+ // directly, mL rows × that ingredient's density. Mirrors sumActualRowsMassKg
56
+ // in the app (cost.js). Any volume row that can't resolve → null (never a
57
+ // partial sum that silently drops the water).
58
+ function _sumActualRowsKg(rows, ingredientsById, formulationsById) {
59
+ if (!Array.isArray(rows)) return null;
60
+ let kg = 0, n = 0;
61
+ for (const c of rows) {
62
+ if (!c || !(c.ingredientId || c.formulationId)) continue;
63
+ const a = parseFloat(c.amount); if (!isFinite(a)) continue;
64
+ const m = _massToKg(a, c.unit); if (m != null) { kg += m; n++; continue; }
65
+ const L = _volToL(a, c.unit);
66
+ if (L != null) { const d = _rowDensityKgPerL(c, ingredientsById, formulationsById); if (d == null) return null; kg += L * d; n++; }
67
+ }
68
+ return n ? kg : null;
69
+ }
70
+ function _batchActualMassKg(b, ingredientsById, formulationsById) {
29
71
  const y = parseFloat(b.actualYield);
30
72
  if (isFinite(y)) {
31
73
  const kg = _massToKg(y, b.unit); if (kg != null) return kg;
32
74
  const umk = _batchUnitMassKg(b); if (umk != null) return y * umk; // count unit × per-unit mass
33
75
  }
34
76
  if (Array.isArray(b.actualComposition)) {
35
- let t = 0, any = false;
36
- for (const c of b.actualComposition) { const kg = _massToKg(parseFloat(c.amount), c.unit); if (kg != null) { t += kg; any = true; } }
37
- if (any) return t;
77
+ const t = _sumActualRowsKg(b.actualComposition, ingredientsById, formulationsById);
78
+ if (t != null) return t;
38
79
  }
39
80
  // Volume-anchored batch (no weighed mass above): mass = measured volume ×
40
81
  // measured density (V·ρ — always valid; summing per-ingredient volumes is
@@ -49,25 +90,47 @@ function _batchActualMassKg(b) {
49
90
  }
50
91
  return null;
51
92
  }
52
- function _batchActualVolume(b) {
93
+ function _batchActualVolume(b, ingredientsById, formulationsById) {
53
94
  const mv = parseFloat(b.measuredVolume);
54
95
  if (isFinite(mv) && mv > 0) { const L = _volToL(mv, b.measuredVolumeUnit || 'L'); if (L != null) return { liters: L, source: 'measured' }; }
55
- const d = parseFloat(b.measuredDensity), m = _batchActualMassKg(b);
96
+ const d = parseFloat(b.measuredDensity), m = _batchActualMassKg(b, ingredientsById, formulationsById);
56
97
  if (isFinite(d) && d > 0 && m != null) return { liters: m / d, source: 'derived' };
57
98
  return null;
58
99
  }
59
100
  // Public shape for a batch's actual volume (or null). Includes the density used
60
101
  // (derived case) or implied by the measurement (measured case) for QC.
61
- function _actualVolumeInfo(b) {
62
- const av = _batchActualVolume(b);
102
+ function _actualVolumeInfo(b, ingredientsById, formulationsById) {
103
+ const av = _batchActualVolume(b, ingredientsById, formulationsById);
63
104
  if (!av) return null;
64
105
  const out = { liters: +av.liters.toFixed(4), unit: 'L', source: av.source };
65
106
  if (av.source === 'derived') { const d = parseFloat(b.measuredDensity); if (isFinite(d)) out.densityUsed = d; }
66
- else { const m = _batchActualMassKg(b); if (m != null && av.liters > 0) out.impliedDensity = +(m / av.liters).toFixed(4); }
107
+ else { const m = _batchActualMassKg(b, ingredientsById, formulationsById); if (m != null && av.liters > 0) out.impliedDensity = +(m / av.liters).toFixed(4); }
67
108
  return out;
68
109
  }
110
+ // ESTIMATED volume when a batch has no actual: mass (actual, else target) ÷ the
111
+ // formula's declared finished density. Never from an ideal-mix estimate, never
112
+ // an actual. Mirrors the app's _batchEstimatedVolume.
113
+ function _estimatedVolumeInfo(b, f, ingredientsById, formulationsById, batchesById) {
114
+ if (!f || _batchActualVolume(b, ingredientsById, formulationsById)) return null;
115
+ const fd = _finishedDensityInfo(f, batchesById);
116
+ if (!fd) return null;
117
+ let kg = _batchActualMassKg(b, ingredientsById, formulationsById), basis = 'actual-mass';
118
+ if (kg == null) { const t = _massToKg(parseFloat(b.targetQuantity), b.unit); if (t != null) { kg = t; basis = 'target-mass'; } }
119
+ if (kg == null || !(kg > 0)) return null;
120
+ return { liters: +(kg / fd.value).toFixed(4), unit: 'L', basis, densityUsed: fd.value, densityFromBatch: fd.fromBatch, estimate: true };
121
+ }
122
+ // A VOLUME-target batch's planned mass = target volume × the formula's finished
123
+ // density (what the weigh-out scales by). null density → the app used its
124
+ // ideal-mix estimate; say so rather than reproduce it.
125
+ function _plannedMassInfo(b, f, batchesById) {
126
+ const L = _volToL(parseFloat(b.targetQuantity), b.unit);
127
+ if (L == null || !(L > 0)) return null;
128
+ const fd = _finishedDensityInfo(f, batchesById);
129
+ if (!fd) return { kg: null, note: 'No finished density declared on the formula — the app scaled this volume target with an ideal-mix estimate from ingredient densities (volumes assumed additive).' };
130
+ return { kg: +(L * fd.value).toFixed(4), unit: 'kg', densityUsed: fd.value, densitySource: fd.source, densityFromBatch: fd.fromBatch, note: 'Each recipe row weighs out to its wt% of this mass; the balance (q.s.) row is filled to the volume mark, so pure-ingredient volumes do not sum to the target.' };
131
+ }
69
132
 
70
- function _trimBatch(b, formulationsById) {
133
+ function _trimBatch(b, formulationsById, ingredientsById, batchesById) {
71
134
  if (!b) return null;
72
135
  const f = b.formulationId ? formulationsById.get(b.formulationId) : null;
73
136
  return {
@@ -89,11 +152,20 @@ function _trimBatch(b, formulationsById) {
89
152
  densityTempC: (b.densityTemp != null && b.densityTemp !== '') ? b.densityTemp : null,
90
153
  measuredVolume: b.measuredVolume ?? null,
91
154
  measuredVolumeUnit: b.measuredVolumeUnit || '',
92
- actualVolume: _actualVolumeInfo(b),
155
+ actualVolume: _actualVolumeInfo(b, ingredientsById, formulationsById),
156
+ // No actual volume → an ESTIMATE at the formula's declared finished density
157
+ // (actual mass, else target mass). `estimate: true`; never an actual.
158
+ estimatedVolume: _estimatedVolumeInfo(b, f, ingredientsById, formulationsById, batchesById),
93
159
  // Actual MASS in kg (the conserved, additive quantity). From actual yield
94
- // (mass-unit batch), else summed weighed inputs, else measured volume ×
95
- // measured density. null when none is determinable.
96
- actualMass: (function () { const m = _batchActualMassKg(b); return (m != null && isFinite(m)) ? { kg: +m.toFixed(4), unit: 'kg' } : null; })(),
160
+ // (mass-unit batch), else summed as-prepared inputs — each row through its
161
+ // OWN unit (g directly, mL × that ingredient's density) — else measured
162
+ // volume × measured density. null when none is determinable.
163
+ actualMass: (function () { const m = _batchActualMassKg(b, ingredientsById, formulationsById); return (m != null && isFinite(m)) ? { kg: +m.toFixed(4), unit: 'kg' } : null; })(),
164
+ // Volume-target batches only: the planned mass the weigh-out scaled to.
165
+ plannedMass: _plannedMassInfo(b, f, batchesById),
166
+ // The formula's declared finished density (g/mL of the mixed product) that
167
+ // volume targets and estimates use; null = the app is on its ideal-mix estimate.
168
+ formulaFinishedDensity: _finishedDensityInfo(f, batchesById),
97
169
  preparedDate: b.preparedDate || '',
98
170
  preparedBy: b.preparedBy || '',
99
171
  // Finished-goods storage location for this batch's produced stock (Production
@@ -167,7 +239,7 @@ const list_batches = {
167
239
  return {
168
240
  totalMatching: filtered.length,
169
241
  returned: Math.min(filtered.length, limit),
170
- batches: filtered.slice(0, limit).map(b => _trimBatch(b, indexes.formulationsById)),
242
+ batches: filtered.slice(0, limit).map(b => _trimBatch(b, indexes.formulationsById, indexes.ingredientsById, indexes.batchesById)),
171
243
  };
172
244
  },
173
245
  };
@@ -202,7 +274,7 @@ const get_batch = {
202
274
  })
203
275
  : null;
204
276
  return {
205
- ..._trimBatch(b, indexes.formulationsById),
277
+ ..._trimBatch(b, indexes.formulationsById, indexes.ingredientsById, indexes.batchesById),
206
278
  notes: b.notes || '',
207
279
  equipmentUsed: b.equipmentUsed || '',
208
280
  // Multi-select equipment: full list [{name, equipmentId}]; falls back to
package/tools/library.js CHANGED
@@ -12,6 +12,55 @@
12
12
  // ============================================================
13
13
 
14
14
  import { getStore, resolveById } from '../data.js';
15
+ import { _evalPassFail } from './analytics.js';
16
+
17
+ // ── Usage roll-ups (mirror the Usage tabs on the Panel / Method / Equipment
18
+ // detail pages) ────────────────────────────────────────────────────────
19
+ // Resolve a measurement's instrument the way the app does: named on the row →
20
+ // the parameter's Test Method equipment → the report's run default.
21
+ function _resolveInstrument(m, t, db) {
22
+ if (m.equipmentId || m.instrument) return { equipmentId: m.equipmentId || '', name: m.instrument || '', source: 'row' };
23
+ const pm = m.parameterId ? (db.parameters || []).find(p => p.id === m.parameterId)
24
+ : (db.parameters || []).find(p => _norm(p.name) === _norm(m.parameter));
25
+ if (pm && (pm.equipmentId || pm.equipment)) return { equipmentId: pm.equipmentId || '', name: pm.equipment || '', source: 'method' };
26
+ if (t && (t.equipmentId || t.instrument)) return { equipmentId: t.equipmentId || '', name: t.instrument || '', source: 'run' };
27
+ return { equipmentId: '', name: '', source: '' };
28
+ }
29
+ function _num(m) { const v = parseFloat(m && m.value); return Number.isFinite(v) ? v : null; }
30
+ function _mean(a) { return a.length ? a.reduce((x, y) => x + y, 0) / a.length : null; }
31
+ function _sd(a) { if (a.length < 2) return null; const mu = _mean(a); return Math.sqrt(a.reduce((acc, x) => acc + (x - mu) ** 2, 0) / (a.length - 1)); }
32
+ function _r(v, d = 3) { return v == null ? null : +v.toFixed(d); }
33
+ // Where a set of reports (optionally restricted to measurements passing
34
+ // `measFilter`) landed: totals + by-formula breakdown (top 10). `fails` uses the
35
+ // measurement's own acceptance criteria (panel spec inheritance is app-side).
36
+ function _usageRollup(db, tests, measFilter) {
37
+ const sById = new Map((db.samples || []).map(s => [s.id, s]));
38
+ const bById = new Map((db.batches || []).map(b => [b.id, b]));
39
+ const fById = new Map((db.formulations || []).map(f => [f.id, f]));
40
+ const date = t => String(t.testDate || (t.createdAt || '').slice(0, 10) || '');
41
+ const byF = new Map(); const forms = new Set(), batches = new Set(), samples = new Set(), labs = new Set();
42
+ let readings = 0, fails = 0, withSpec = 0, last = '';
43
+ tests.forEach(t => {
44
+ const s = sById.get(t.sampleId) || null; const b = s ? bById.get(s.batchId) : null;
45
+ const f = (s && s.formulationId) ? fById.get(s.formulationId) : (b ? fById.get(b.formulationId) : null);
46
+ if (s) samples.add(s.id); if (b) batches.add(b.id); if (f) forms.add(f.id); if (t.lab) labs.add(t.lab);
47
+ const d = date(t); if (d > last) last = d;
48
+ let tf = 0;
49
+ (t.measurements || []).filter(m => !measFilter || measFilter(m, t)).forEach(m => {
50
+ readings++;
51
+ const pf = _evalPassFail(m); if (pf !== 'no-criteria' && pf !== 'untested') withSpec++; if (pf === 'fail') { fails++; tf++; }
52
+ });
53
+ const key = f ? f.id : '(no formula)';
54
+ if (!byF.has(key)) byF.set(key, { formula: f ? (f.uid || f.name) : null, formulaName: f ? f.name : null, reports: 0, lastRun: '', fails: 0 });
55
+ const g = byF.get(key); g.reports++; if (d > g.lastRun) g.lastRun = d; g.fails += tf;
56
+ });
57
+ return {
58
+ reports: tests.length, readings, lastUsed: last || null,
59
+ formulas: forms.size, batches: batches.size, samples: samples.size, labs: labs.size,
60
+ fails, passRate: withSpec ? _r(100 * (withSpec - fails) / withSpec, 0) : null,
61
+ byFormula: [...byF.values()].sort((a, b) => b.reports - a.reports).slice(0, 10),
62
+ };
63
+ }
15
64
 
16
65
  const _norm = (s) => String(s == null ? '' : s).toLowerCase();
17
66
  const _clampLimit = (n) => Math.min(1000, Math.max(1, n || 100));
@@ -99,7 +148,7 @@ const list_equipment = {
99
148
  const get_equipment = {
100
149
  definition: {
101
150
  name: 'get_equipment',
102
- description: 'Get one equipment record by UID (e.g. EQP-001) or id, including a summary of everywhere it is referenced (test panels, step presets, test methods, formulas, batches).',
151
+ 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.',
103
152
  inputSchema: {
104
153
  type: 'object',
105
154
  properties: { id: { type: 'string', description: 'Equipment UID or internal id.' } },
@@ -110,7 +159,25 @@ const get_equipment = {
110
159
  const { db } = getStore();
111
160
  const e = resolveById('equipment', args.id);
112
161
  if (!e) return { error: `No equipment found for "${args.id}".` };
113
- return { ...(_trimEquipment(e)), usedIn: _equipUsage(e, db) };
162
+ // Measurements whose RESOLVED instrument is this unit (row → method → run).
163
+ const nm = _norm(e.name);
164
+ const mine = (m, t) => { const r = _resolveInstrument(m, t, db); return r.equipmentId ? r.equipmentId === e.id : (!!nm && _norm(r.name) === nm); };
165
+ const tests = (db.testResults || []).filter(t => (t.measurements || []).some(m => mine(m, t)));
166
+ const here = new Map(), fleet = new Map();
167
+ (db.testResults || []).forEach(t => (t.measurements || []).forEach(m => {
168
+ const pn = (m.parameter || '').trim(); if (!pn) return;
169
+ const v = _num(m); const isMine = mine(m, t); const bucket = isMine ? here : fleet;
170
+ if (!bucket.has(pn)) bucket.set(pn, { parameter: pn, readings: 0, vals: [], fails: 0 });
171
+ const g = bucket.get(pn); g.readings++; if (v != null) g.vals.push(v); if (isMine && _evalPassFail(m) === 'fail') g.fails++;
172
+ }));
173
+ const measured = [...here.values()].map(g => {
174
+ const f = fleet.get(g.parameter); const mh = _mean(g.vals), me = f ? _mean(f.vals) : null;
175
+ return { parameter: g.parameter, readings: g.readings, mean: _r(mh), fails: g.fails, readingsElsewhere: f ? f.readings : 0, meanElsewhere: _r(me),
176
+ biasPct: (mh != null && me != null && me !== 0) ? _r((mh - me) / Math.abs(me) * 100, 1) : null };
177
+ }).sort((a, b) => b.readings - a.readings);
178
+ const usedIn = _equipUsage(e, db);
179
+ usedIn.testReports = tests.length;
180
+ return { ...(_trimEquipment(e)), usedIn, usage: _usageRollup(db, tests, mine), measured };
114
181
  },
115
182
  };
116
183
 
@@ -187,7 +254,7 @@ const list_test_methods = {
187
254
  const get_test_method = {
188
255
  definition: {
189
256
  name: 'get_test_method',
190
- description: 'Get one Test Method by UID (e.g. PARAM-001) or id — full definition including SOP / sample prep / equipment / calculation / acceptance spec, the declared runConditions this method varies by (the vocabulary — e.g. Storage temp/RH, spindle RPM; each measurement captures a value per condition), plus sibling methods that share its analyte (the same property measured at other conditions) and the Test Panels that use this method.',
257
+ description: 'Get one Test Method by UID (e.g. PARAM-001) or id — full definition including SOP / sample prep / equipment / calculation / acceptance spec, the declared runConditions this method varies by (the vocabulary — e.g. Storage temp/RH, spindle RPM; each measurement captures a value per condition), sibling methods that share its analyte, the Test Panels that use it, plus `usage` (reports / readings linked to this method: totals, last used, distinct formulas/batches/samples, pass rate, top formulas), `valueSummary` (mean / sd / min / max over numeric readings) and `byInstrument` (readings, mean and fails per resolved instrument — a mean that differs between units is a calibration question).',
191
258
  inputSchema: {
192
259
  type: 'object',
193
260
  properties: { id: { type: 'string', description: 'Test Method UID or internal id.' } },
@@ -208,7 +275,19 @@ const get_test_method = {
208
275
  (row.parameterId && row.parameterId === p.id) ||
209
276
  (!row.parameterId && _norm(row.parameter || row.name) === nm)
210
277
  )).map(t => t.uid || t.name).slice(0, 40);
211
- return { ...(_trimMethod(p, { full: true })), analyteSiblings: siblings, usingPanels };
278
+ // Usage = every measurement linked to this method (by id, else by exact name).
279
+ const match = (m) => (m.parameterId && m.parameterId === p.id) || (!m.parameterId && _norm(m.parameter) === nm);
280
+ const tests = (db.testResults || []).filter(r => (r.measurements || []).some(match));
281
+ const vals = [], byInst = new Map();
282
+ tests.forEach(r => (r.measurements || []).filter(match).forEach(m => {
283
+ const v = _num(m); if (v != null) vals.push(v);
284
+ const inst = _resolveInstrument(m, r, db); const key = inst.name || inst.equipmentId || '(unresolved)';
285
+ if (!byInst.has(key)) byInst.set(key, { instrument: key, readings: 0, vals: [], fails: 0 });
286
+ const g = byInst.get(key); g.readings++; if (v != null) g.vals.push(v); if (_evalPassFail(m) === 'fail') g.fails++;
287
+ }));
288
+ const byInstrument = [...byInst.values()].map(g => ({ instrument: g.instrument, readings: g.readings, mean: _r(_mean(g.vals)), fails: g.fails })).sort((a, b) => b.readings - a.readings);
289
+ const valueSummary = { readings: vals.length, mean: _r(_mean(vals)), sd: _r(_sd(vals)), min: vals.length ? Math.min(...vals) : null, max: vals.length ? Math.max(...vals) : null, unit: p.defaultUnit || '' };
290
+ return { ...(_trimMethod(p, { full: true })), analyteSiblings: siblings, usingPanels, usage: _usageRollup(db, tests, match), valueSummary, byInstrument };
212
291
  },
213
292
  };
214
293
 
@@ -356,7 +435,7 @@ const list_test_panels = {
356
435
  const get_test_panel = {
357
436
  definition: {
358
437
  name: 'get_test_panel',
359
- description: 'Get one Test Panel by UID (e.g. TMPL-001) or id — full ordered parameter list (each with its resolved Test Method UID, unit, and spec), instruments, and notes.',
438
+ description: 'Get one Test Panel by UID (e.g. TMPL-001) or id — full ordered parameter list (each with its resolved Test Method UID, unit, and spec), instruments, notes, plus `usage` (reports created from this panel: totals, last used, distinct formulas/batches/samples, pass rate, top formulas) and `performanceByParameter` (readings / fails per parameter). Usage counts reports created from the panel, not parameter overlap.',
360
439
  inputSchema: {
361
440
  type: 'object',
362
441
  properties: { id: { type: 'string', description: 'Test Panel UID or internal id.' } },
@@ -367,7 +446,19 @@ const get_test_panel = {
367
446
  const { db } = getStore();
368
447
  const t = resolveById('templates', args.id);
369
448
  if (!t) return { error: `No test panel found for "${args.id}".` };
370
- return _trimPanel(t, db, { full: true });
449
+ // Usage = reports created FROM this panel (templateId) — not parameter overlap.
450
+ const tests = (db.testResults || []).filter(r => r.templateId === t.id);
451
+ const perf = (t.parameters || []).map(row => {
452
+ const nm = _norm(row.parameter || row.name), pid = row.parameterId || '';
453
+ let n = 0, fails = 0, withSpec = 0;
454
+ tests.forEach(r => (r.measurements || []).forEach(m => {
455
+ const hit = (pid && m.parameterId === pid) || ((!m.parameterId || !pid) && _norm(m.parameter) === nm);
456
+ if (!hit) return; n++;
457
+ const pf = _evalPassFail(m); if (pf !== 'no-criteria' && pf !== 'untested') withSpec++; if (pf === 'fail') fails++;
458
+ }));
459
+ return { parameter: row.parameter || row.name, readings: n, fails, failRatePct: withSpec ? _r(100 * fails / withSpec, 0) : null };
460
+ });
461
+ return { ...(_trimPanel(t, db, { full: true })), usage: _usageRollup(db, tests, null), performanceByParameter: perf };
371
462
  },
372
463
  };
373
464