plm-upload-mcp 1.1.0 → 1.3.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.
Files changed (3) hide show
  1. package/README.md +134 -103
  2. package/index.mjs +320 -24
  3. package/package.json +2 -2
package/README.md CHANGED
@@ -1,103 +1,134 @@
1
- # plm-upload-mcp
2
-
3
- An MCP server for the **LionsBot PLM**. It **reads** the PLM — SKU folders, full
4
- component metadata, extracted drawing/BOM metadata, and product & staging BOMs — and
5
- **bulk-uploads** local files (SolidWorks STEP/PDF exports) into it, matched to a
6
- component by SKU. It runs on **your own machine**, so it reads your exported files
7
- straight off disk, and it signs in as **you** with your PLM/hub login — every read is
8
- row-level-security scoped to you, and every uploaded file is tagged with who uploaded it.
9
-
10
- Pair it with your SolidWorks MCP: that MCP knows each part's SKU and exports the files;
11
- this MCP takes `{path, sku}` pairs and pushes them into the PLM.
12
-
13
- ## Setup
14
-
15
- Add one entry to your Claude MCP config (Claude Desktop: `claude_desktop_config.json`;
16
- Claude Code: `.mcp.json` or `claude mcp add`). Use **your own** PLM email + password:
17
-
18
- ```json
19
- {
20
- "mcpServers": {
21
- "plm-upload": {
22
- "command": "npx",
23
- "args": ["-y", "plm-upload-mcp"],
24
- "env": {
25
- "PLM_EMAIL": "you@lionsbot.com",
26
- "PLM_PASSWORD": "your-plm-password"
27
- }
28
- }
29
- }
30
- }
31
- ```
32
-
33
- That's all. `npx -y` fetches and runs the latest version; no clone, no build.
34
-
35
- > Your login is the same one you use for the Hardware Tools hub / PLM. Uploads are
36
- > attributed to you and require a `@lionsbot.com` account.
37
-
38
- ## Tools
39
-
40
- ### `upload_files`
41
- Uploads one or more files, each paired with its target SKU.
42
-
43
- - `files`: array of `{ path, sku, skuName?, category? }`
44
- - `path` — absolute local path to the file
45
- - `sku` — component SKU, e.g. `MNT-1234-A0`
46
- - `skuName` — optional; only used if the SKU's Drive folder has to be created
47
- - `category` — optional PLM tag: `Default` | `Archive` | `Compliance` | `Ops`
48
- - `bucket`: `main` (default, confirmed components) or `staging` (unconfirmed)
49
-
50
- Each file lands in PLM storage and is mirrored into that SKU's Google Drive folder
51
- (created automatically if it doesn't exist). Re-uploading a file with the **same name
52
- replaces it in place** — no duplicate pile-up on re-runs.
53
-
54
- Example ask: *"Upload C:\exports\bracket.step to SKU MNT-1234-A0 and C:\exports\bracket.pdf to the same SKU."*
55
-
56
- ### `list_component_files`
57
- Lists the files currently in a component's Drive folder.
58
-
59
- - `sku`: component SKU
60
- - `bucket`: `main` (default) or `staging`
61
-
62
- ## Read-only tools
63
-
64
- All read tools query the PLM as **you** (RLS-scoped) — you only ever see what you're
65
- allowed to see. `bucket` / `classification` values are `main` (confirmed), `staging`
66
- (unconfirmed), or `all` (default).
67
-
68
- ### `list_sku_folders`
69
- Every component SKU with its Google Drive folder — the SKU→folder map (SKU, name,
70
- category, type, revision, status, staging flag, folder id/URL). Filters: `bucket`,
71
- `category`, `with_folder_only`, `limit`, `offset`.
72
-
73
- ### `get_component_metadata`
74
- Full component metadata (every column, incl. cost/supply, drawing-extracted fields,
75
- CAD provenance, compliance, and the `extract_meta` block). Pass a single `sku` for one
76
- part, or omit it to page through all. Filters: `search`, `bucket`, `category`,
77
- `status`, `limit`, `offset`.
78
-
79
- ### `list_bom_extract_metadata`
80
- The metadata machine-extracted from each part's drawing/BOM PDF (`extract_meta`): the
81
- Lionsbot-custom flag, SKU/drawing match check, per-field extracted values, and source
82
- file + who/when. Only extracted parts are returned. Filters: `sku`, `bucket`, `limit`,
83
- `offset`.
84
-
85
- ### `list_boms`
86
- BOMs across all products, each product carrying its BOM(s) + line items and a derived
87
- `staging` flag (a product is *staging* while its working BOM still contains any staging
88
- component). Working BOMs only by default. Filters: `product_sku`, `classification`,
89
- `include_snapshots`, `include_rows`, `max_rows_per_bom`.
90
-
91
- ## Config overrides (rarely needed)
92
-
93
- Baked to production defaults; override via env only if the PLM backend moves:
94
-
95
- | env | default |
96
- |---|---|
97
- | `PLM_GATEWAY` | `https://gateway-production-c13d.up.railway.app` |
98
- | `PLM_ANON_KEY` | (prod anon key) |
99
- | `PLM_EDGE_URL` | `https://plm-edge-production.up.railway.app` |
100
-
101
- ## Requirements
102
-
103
- Node.js 18+ (for built-in `fetch`).
1
+ # plm-upload-mcp
2
+
3
+ An MCP server for the **LionsBot PLM**. It **reads** the PLM — SKU folders, full
4
+ component metadata, extracted drawing/BOM metadata, and product & staging BOMs — and
5
+ **bulk-uploads** local files (SolidWorks STEP/PDF exports) into it, matched to a
6
+ component by SKU, makes components' Drive folders and **uprevs** staging prototypes. It runs on **your own machine**, so it reads your exported files
7
+ straight off disk, and it signs in as **you** with your PLM/hub login — every read is
8
+ row-level-security scoped to you, and every uploaded file is tagged with who uploaded it.
9
+
10
+ Pair it with your SolidWorks MCP: that MCP knows each part's SKU and exports the files;
11
+ this MCP takes `{path, sku}` pairs and pushes them into the PLM.
12
+
13
+ ## Setup
14
+
15
+ Add one entry to your Claude MCP config (Claude Desktop: `claude_desktop_config.json`;
16
+ Claude Code: `.mcp.json` or `claude mcp add`). Use **your own** PLM email + password:
17
+
18
+ ```json
19
+ {
20
+ "mcpServers": {
21
+ "plm-upload": {
22
+ "command": "npx",
23
+ "args": ["-y", "plm-upload-mcp@latest"],
24
+ "env": {
25
+ "PLM_EMAIL": "you@lionsbot.com",
26
+ "PLM_PASSWORD": "your-plm-password"
27
+ }
28
+ }
29
+ }
30
+ }
31
+ ```
32
+
33
+ That's all. `npx -y plm-upload-mcp@latest` fetches and runs the latest version on every start; no clone, no build.
34
+
35
+ > Your login is the same one you use for the Hardware Tools hub / PLM. Uploads are
36
+ > attributed to you and require a `@lionsbot.com` account.
37
+
38
+ ## Tools
39
+
40
+ ### `upload_files`
41
+ Uploads one or more files, each paired with its target SKU.
42
+
43
+ - `files`: array of `{ path, sku, category? }`
44
+ - `path` — absolute local path to the file
45
+ - `sku` — component SKU, e.g. `MNT-1234-A0`; it must already exist in the PLM
46
+ - `category` — optional PLM tag: `Default` | `Archive` | `Compliance` | `Ops`
47
+
48
+ Each file lands in PLM storage and is mirrored into that SKU's Google Drive folder on
49
+ the part's own drive (staging or main, from the component; created automatically if it
50
+ doesn't exist). A SKU that isn't in the PLM is refused, so a typo never leaves a stray
51
+ folder. Re-uploading a file with the **same name replaces it in place** — no duplicate
52
+ pile-up on re-runs.
53
+
54
+ A **PDF is then read** like an upload in the PLM's Files tab: a LionsBot drawing of that
55
+ SKU fills the part's title-block fields (material, colour, drawing REV, manufacturing
56
+ method). An injection moulded X revision then shows in **Injection Mold Staging**.
57
+ Another company's PDF, or a drawing of another SKU, is uploaded but not read.
58
+
59
+ Example ask: *"Upload C:\exports\bracket.step to SKU MNT-1234-A0 and C:\exports\bracket.pdf to the same SKU."*
60
+
61
+ ### `create_folder`
62
+ Finds or creates the `[SKU] Name` Drive folder of components already in the PLM, on each
63
+ part's own drive, and links it to the component. Unknown SKUs are refused. Only needed
64
+ for an empty folder: an upload makes the folder too.
65
+
66
+ - `skus`: array of component SKUs
67
+
68
+ ### `uprev_component`
69
+ Uprevs a staging prototype to its next X revision (`MNT-1234-X1` → `MNT-1234-X2`), the
70
+ same as **Uprev** in the PLM: a new component carrying the old one's details, with its
71
+ own staging Drive folder; the old revision stays as history.
72
+
73
+ - `sku`: the current staging SKU (X0–X8; releasing to A0 is a promotion request in the PLM)
74
+ - `drawing_pdf`: optional path to the new revision's drawing PDF
75
+ - `step`: optional path to the new revision's STEP model
76
+ - `proceed_despite_warnings`: optional, see below
77
+
78
+ The files are uploaded to the new revision, renamed to carry its SKU (an older revision's
79
+ SKU in the name is swapped, else `[SKU] ` is put in front), and the drawing is read into
80
+ the PLM. **The PDF is checked before anything is created**: if its title block still
81
+ shows the old SKU, no SKU or REV, or another part, nothing is uprevved and the warnings come
82
+ back. Claude shows them to you; say go ahead and it calls again with
83
+ `proceed_despite_warnings: true`. The warnings are kept in the part's history.
84
+
85
+ Example ask: *"Uprev MNT-1234-X1 with C:\exports\bracket.pdf and C:\exports\bracket.step."*
86
+
87
+ ### `list_component_files`
88
+ Lists the files currently in a component's Drive folder.
89
+
90
+ - `sku`: component SKU
91
+ - `bucket`: `main` (default) or `staging`
92
+
93
+ ## Read-only tools
94
+
95
+ All read tools query the PLM as **you** (RLS-scoped) — you only ever see what you're
96
+ allowed to see. `bucket` / `classification` values are `main` (confirmed), `staging`
97
+ (unconfirmed), or `all` (default).
98
+
99
+ ### `list_sku_folders`
100
+ Every component SKU with its Google Drive folder — the SKU→folder map (SKU, name,
101
+ category, type, revision, status, staging flag, folder id/URL). Filters: `bucket`,
102
+ `category`, `with_folder_only`, `limit`, `offset`.
103
+
104
+ ### `get_component_metadata`
105
+ Full component metadata (every column, incl. cost/supply, drawing-extracted fields,
106
+ CAD provenance, compliance, and the `extract_meta` block). Pass a single `sku` for one
107
+ part, or omit it to page through all. Filters: `search`, `bucket`, `category`,
108
+ `status`, `limit`, `offset`.
109
+
110
+ ### `list_bom_extract_metadata`
111
+ The metadata machine-extracted from each part's drawing/BOM PDF (`extract_meta`): the
112
+ Lionsbot-custom flag, SKU/drawing match check, per-field extracted values, and source
113
+ file + who/when. Only extracted parts are returned. Filters: `sku`, `bucket`, `limit`,
114
+ `offset`.
115
+
116
+ ### `list_boms`
117
+ BOMs across all products, each product carrying its BOM(s) + line items and a derived
118
+ `staging` flag (a product is *staging* while its working BOM still contains any staging
119
+ component). Working BOMs only by default. Filters: `product_sku`, `classification`,
120
+ `include_snapshots`, `include_rows`, `max_rows_per_bom`.
121
+
122
+ ## Config overrides (rarely needed)
123
+
124
+ Baked to production defaults; override via env only if the PLM backend moves:
125
+
126
+ | env | default |
127
+ |---|---|
128
+ | `PLM_GATEWAY` | `https://gateway-production-c13d.up.railway.app` |
129
+ | `PLM_ANON_KEY` | (prod anon key) |
130
+ | `PLM_EDGE_URL` | `https://plm-edge-production.up.railway.app` |
131
+
132
+ ## Requirements
133
+
134
+ Node.js 18+ (for built-in `fetch`).
package/index.mjs CHANGED
@@ -1,7 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * plm-upload-mcp — read the LionsBot PLM and bulk-upload local files
4
- * (SolidWorks STEP/PDF exports) into it, matched to a component by SKU.
3
+ * plm-upload-mcp — read the LionsBot PLM, bulk-upload local files
4
+ * (SolidWorks STEP/PDF exports) into it matched to a component by SKU, make
5
+ * components' Drive folders and uprev staging prototypes.
5
6
  *
6
7
  * Runs locally on each engineer's machine (stdio), so it reads their exported
7
8
  * files straight off disk. It authenticates as the engineer with their own PLM
@@ -17,7 +18,7 @@
17
18
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
18
19
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
19
20
  import { z } from 'zod'
20
- import { readFile } from 'node:fs/promises'
21
+ import { readFile, stat } from 'node:fs/promises'
21
22
  import { basename, extname } from 'node:path'
22
23
 
23
24
  // Prod defaults — same values the PLM web app ships with. Overridable via env.
@@ -82,6 +83,25 @@ async function edgeJson(body) {
82
83
  return data
83
84
  }
84
85
 
86
+ // The engineer's PLM user id: PLM users.id is the auth uid, the token's `sub`.
87
+ const userId = async () => JSON.parse(Buffer.from((await getToken()).split('.')[1], 'base64url').toString()).sub
88
+
89
+ /** A part-history row, the same shape the PLM web app writes. Best effort:
90
+ * a failed history write never undoes or blocks the work it records. */
91
+ async function audit(entity_id, action, after_value) {
92
+ try {
93
+ const token = await getToken()
94
+ const resp = await fetch(`${GATEWAY}/rest/v1/audit_log`, {
95
+ method: 'POST',
96
+ headers: { apikey: ANON_KEY, authorization: `Bearer ${token}`, 'content-type': 'application/json', prefer: 'return=minimal' },
97
+ body: JSON.stringify({ entity_type: 'component', entity_id, action, actor_user_id: await userId(), actor_type: 'user', after_value }),
98
+ })
99
+ if (!resp.ok) console.error(`[audit] ${action}: http ${resp.status}`)
100
+ } catch (e) {
101
+ console.error(`[audit] ${action}:`, e instanceof Error ? e.message : e)
102
+ }
103
+ }
104
+
85
105
  // --- Read path: PostgREST GET with the engineer's token (RLS-enforced). -------
86
106
  // Same data path the PLM web app uses (supabase-js -> /rest/v1). The anon key is
87
107
  // the gateway apikey; the bearer token is the signed-in engineer, so row-level
@@ -103,10 +123,91 @@ async function restGet(table, params = {}, { count = false } = {}) {
103
123
  const stagingFilter = (bucket) =>
104
124
  bucket === 'staging' ? { staging: 'eq.true' } : bucket === 'main' ? { staging: 'eq.false' } : {}
105
125
 
126
+ /** The component with this SKU, or null. Writes only go to SKUs the PLM has:
127
+ * a stray `[SKU]` Drive folder would be read as a new part by the reconcile. */
128
+ async function findComponent(sku) {
129
+ const { rows } = await restGet('components', {
130
+ select: 'id,sku,name,staging,cad_revision,drive_folder_id,drive_folder_url',
131
+ sku: `eq.${sku.trim().toUpperCase()}`,
132
+ })
133
+ return rows[0] ?? null
134
+ }
135
+ const driveOf = (c) => (c.staging ? 'staging' : 'main')
136
+
137
+ // --- Injection Mold rules: a port of the PLM's src/lib/injectionMould.ts and
138
+ // planUprev (src/lib/promotion.ts). Change both together. ---------------------
139
+ const IM_METHOD = /\binjection\b|\bmou?ld(ed|ing)?\s+plastic/i
140
+ const isXRev = (sku) => /-X\d+$/.test(sku)
141
+ const familyOf = (sku) => sku.replace(/-(X\d+|[A-Z]\d|\d\d)$/, '')
142
+
143
+ /** Next prototype revision, same rule as the edge `uprev` (X0–X8 only). */
144
+ function nextRev(sku) {
145
+ const m = /^([A-Z]{3})-(\d{4})-X(\d)$/.exec(sku)
146
+ if (!m) return { error: `${sku}: only staging prototype revisions (X0–X8) can be uprevved` }
147
+ if (Number(m[3]) >= 9) return { error: 'X9 is the last prototype revision — release to A0 instead' }
148
+ return { newSku: `${m[1]}-${m[2]}-X${Number(m[3]) + 1}` }
149
+ }
150
+
151
+ /** The file name carrying `sku`: an older revision's SKU in it is swapped,
152
+ * else the SKU is put in front, so a STEP sent to a supplier names its part. */
153
+ function nameWithSku(name, sku) {
154
+ if (name.toUpperCase().includes(sku.toUpperCase())) return name
155
+ const older = new RegExp(`${familyOf(sku).replace(/-/g, '\\-')}-(X\\d+|[A-Z]\\d)`, 'i')
156
+ return older.test(name) ? name.replace(older, sku) : `[${sku}] ${name}`
157
+ }
158
+
159
+ /** Why a drawing PDF or STEP named `name` breaks the naming rule
160
+ * `[SKU] Part Name REV0X` for `sku`; null when it follows it or is another
161
+ * file type. A prompt only: the upload still goes ahead. */
162
+ function fileNameIssue(name, sku) {
163
+ const stem = /^(.*)\.(pdf|step|stp)$/i.exec(name)?.[1]
164
+ if (stem === undefined) return null
165
+ const head = `[${sku}] `.toUpperCase()
166
+ const ok = stem.toUpperCase().startsWith(head) && /^\S.* REV\d{2}$/i.test(stem.slice(head.length))
167
+ return ok ? null : `${name} is not named "[${sku}] Part Name REV0X".`
168
+ }
169
+
170
+ /** Warnings for a drawing about to be uploaded as `newSku`, compared with the
171
+ * revision it replaces. They are prompts: the uploader may still go ahead. Only
172
+ * the SKU has to move on: the title-block REV resets to 00 on a new SKU. */
173
+ function drawingWarnings(read, newSku, prev) {
174
+ if (!read) return ['The PDF could not be read, so its SKU and REV were not checked.']
175
+ if (!read.is_lionsbot) return ['This is not a LionsBot drawing title block, so nothing can be checked or extracted.']
176
+ const out = []
177
+ const sameSku = !!read.sku && read.sku === prev.sku
178
+ const sameRev = !!read.rev && read.rev === prev.drawing_rev
179
+ if (sameSku && (sameRev || !read.rev)) {
180
+ out.push(`No difference found: the drawing still reads ${prev.sku}${read.rev ? ` REV ${read.rev}` : ''}, the same as the current revision.`)
181
+ } else if (!read.sku) {
182
+ out.push('No SKU was found on the drawing.')
183
+ } else if (familyOf(read.sku) !== familyOf(newSku)) {
184
+ out.push(`The drawing is for ${read.sku}, a different part.`)
185
+ } else if (read.sku !== newSku) {
186
+ out.push(`The drawing reads ${read.sku}; this revision will be ${newSku}.`)
187
+ }
188
+ if (!read.rev) out.push('No REV was found on the drawing.')
189
+ return out
190
+ }
191
+
192
+ /** What reading an uploaded drawing did; `listed` = it is now in Injection Mold Staging. */
193
+ function readOutcome(res, sku) {
194
+ if (res.error) return { ok: false, text: res.error, listed: false }
195
+ if (!res.written) {
196
+ const text = res.extracted?.is_lionsbot === false
197
+ ? 'Not a LionsBot drawing, nothing read'
198
+ : `Drawing says ${res.sku_check?.drawing_sku ?? 'no SKU'}, not ${sku}: nothing read`
199
+ return { ok: false, text, listed: false }
200
+ }
201
+ return {
202
+ ok: true,
203
+ text: `Drawing read${res.extracted?.rev ? ` · REV ${res.extracted.rev}` : ''}`,
204
+ listed: IM_METHOD.test(res.extracted?.manufacturing_method ?? '') && isXRev(sku),
205
+ }
206
+ }
207
+
106
208
  /** store bytes → storagePath, then upload → mirror into the SKU's Drive folder. */
107
- async function uploadOne({ path, sku, skuName, category, bucket }) {
209
+ async function uploadOne({ path, sku, skuName, category, bucket, filename = basename(path) }) {
108
210
  const bytes = await readFile(path) // throws ENOENT with the path — surfaced per-file below
109
- const filename = basename(path)
110
211
  const mimeType = mimeFor(filename)
111
212
  const token = await getToken()
112
213
 
@@ -140,6 +241,7 @@ async function uploadOne({ path, sku, skuName, category, bucket }) {
140
241
  return {
141
242
  file: filename,
142
243
  sku,
244
+ bucket,
143
245
  driveFileId: synced.driveFileId,
144
246
  driveWebViewLink: synced.driveWebViewLink,
145
247
  replaced: !!synced.replaced,
@@ -147,8 +249,42 @@ async function uploadOne({ path, sku, skuName, category, bucket }) {
147
249
  }
148
250
  }
149
251
 
252
+ /** Reads an uploaded drawing PDF into the component (title-block fields), the
253
+ * same step the PLM runs after a Files-tab upload. The edge writes only a
254
+ * LionsBot drawing of this SKU. */
255
+ async function readDrawing(componentId, sku, fileId, filename) {
256
+ let res
257
+ try {
258
+ res = await edgeJson({ action: 'extract', componentId, fileId, filename })
259
+ } catch (e) {
260
+ res = { error: e instanceof Error ? e.message : String(e) }
261
+ }
262
+ if (res.written) await audit(componentId, 'component.drawing_extracted', { file: filename, extracted: res.extracted ?? null })
263
+ return readOutcome(res, sku)
264
+ }
265
+
266
+ /** The drawing's title block, read without storing or writing anything. */
267
+ async function previewDrawing(bytes, filename) {
268
+ try {
269
+ const token = await getToken()
270
+ const resp = await fetch(`${EDGE}/drive-library?${new URLSearchParams({ action: 'extract-preview', filename })}`, {
271
+ method: 'POST',
272
+ headers: { 'content-type': 'application/pdf', authorization: `Bearer ${token}` },
273
+ body: bytes,
274
+ })
275
+ const data = await resp.json().catch(() => null)
276
+ return resp.ok ? data?.extracted ?? null : null
277
+ } catch {
278
+ return null
279
+ }
280
+ }
281
+
282
+ const isPdf = (name) => /\.pdf$/i.test(name)
283
+ const readLine = (read) => (read ? ` · ${read.text}${read.listed ? ' · now in Injection Mold Staging' : ''}` : '')
284
+ const issueLine = (issue) => (issue ? `\n ⚠ ${issue} Tell the user.` : '')
285
+
150
286
  // --- Server ------------------------------------------------------------------
151
- const server = new McpServer({ name: 'plm-upload', version: '1.1.0' })
287
+ const server = new McpServer({ name: 'plm-upload', version: '1.3.0' })
152
288
 
153
289
  server.registerTool(
154
290
  'upload_files',
@@ -156,20 +292,22 @@ server.registerTool(
156
292
  title: 'Upload files to PLM by SKU',
157
293
  description:
158
294
  "Bulk-upload local files (e.g. SolidWorks STEP/PDF exports) into the LionsBot PLM. " +
159
- "Each file is attached to a component by its SKU: it lands in PLM storage and is mirrored " +
160
- "into that SKU's Google Drive folder (folder auto-created if missing). Re-uploading a file " +
161
- "with the same name replaces it in place rather than duplicating. You must supply the SKU " +
162
- "for each file — the caller's own tooling (e.g. a SolidWorks MCP) already knows each part's SKU.",
295
+ "Each file is attached to an existing component by its SKU: it lands in PLM storage and is " +
296
+ "mirrored into that SKU's Google Drive folder on the part's own drive (staging or main; folder " +
297
+ "auto-created if missing). A SKU that is not in the PLM is refused. Re-uploading a file with " +
298
+ "the same name replaces it in place rather than duplicating. A PDF is then read like a PLM " +
299
+ "upload: a LionsBot drawing of that SKU fills the part's title-block fields (material, colour, " +
300
+ "drawing REV, method), which lists an injection moulded X revision in Injection Mold Staging. " +
301
+ "PDF and STEP names should read `[SKU] Part Name REV0X` (e.g. `[SKN-0176-X1] DEPTH CAMERA COVER " +
302
+ "LEFT REV00.pdf`); one that doesn't is still uploaded but comes back with a name_issue: tell the user. " +
303
+ "You must supply the SKU for each file — the caller's own tooling (e.g. a SolidWorks MCP) " +
304
+ "already knows each part's SKU.",
163
305
  inputSchema: {
164
306
  files: z
165
307
  .array(
166
308
  z.object({
167
309
  path: z.string().describe('Absolute local path to the file to upload.'),
168
310
  sku: z.string().describe('Component SKU this file belongs to, e.g. MNT-1234-A0.'),
169
- skuName: z
170
- .string()
171
- .optional()
172
- .describe("Component display name — used only if the SKU's Drive folder must be created."),
173
311
  category: z
174
312
  .enum(['Default', 'Archive', 'Compliance', 'Ops'])
175
313
  .optional()
@@ -178,31 +316,34 @@ server.registerTool(
178
316
  )
179
317
  .min(1)
180
318
  .describe('The files to upload, each paired with its target SKU.'),
181
- bucket: z
182
- .enum(['main', 'staging'])
183
- .optional()
184
- .describe("Which shared drive: 'main' (confirmed components, default) or 'staging' (unconfirmed)."),
185
319
  },
186
320
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true },
187
321
  },
188
- async ({ files, bucket = 'main' }) => {
322
+ async ({ files }) => {
323
+ const parts = new Map()
189
324
  const results = []
190
325
  for (const f of files) {
326
+ const sku = f.sku.trim().toUpperCase()
191
327
  try {
192
- results.push({ ok: true, ...(await uploadOne({ ...f, bucket })) })
328
+ if (!parts.has(sku)) parts.set(sku, await findComponent(sku))
329
+ const c = parts.get(sku)
330
+ if (!c) throw new Error('not in the PLM, nothing uploaded (create the component first)')
331
+ const up = await uploadOne({ path: f.path, sku: c.sku, skuName: c.name, category: f.category, bucket: driveOf(c) })
332
+ const read = isPdf(up.file) && up.driveFileId ? await readDrawing(c.id, c.sku, up.driveFileId, up.file) : undefined
333
+ results.push({ ok: true, ...up, read, name_issue: fileNameIssue(up.file, c.sku) })
193
334
  } catch (e) {
194
- results.push({ ok: false, file: basename(f.path), sku: f.sku, error: e instanceof Error ? e.message : String(e) })
335
+ results.push({ ok: false, file: basename(f.path), sku, error: e instanceof Error ? e.message : String(e) })
195
336
  }
196
337
  }
197
338
  const ok = results.filter((r) => r.ok).length
198
339
  const lines = results.map((r) =>
199
340
  r.ok
200
- ? `✓ ${r.file} → ${r.sku}${r.replaced ? ' (replaced)' : ''}${r.category ? ` [${r.category}]` : ''}`
341
+ ? `✓ ${r.file} → ${r.sku} (${r.bucket})${r.replaced ? ' (replaced)' : ''}${r.category ? ` [${r.category}]` : ''}${readLine(r.read)}${issueLine(r.name_issue)}`
201
342
  : `✗ ${r.file} → ${r.sku}: ${r.error}`,
202
343
  )
203
344
  return {
204
- content: [{ type: 'text', text: `Uploaded ${ok}/${results.length} to ${bucket}.\n${lines.join('\n')}` }],
205
- structuredContent: { uploaded: ok, total: results.length, bucket, results },
345
+ content: [{ type: 'text', text: `Uploaded ${ok}/${results.length}.\n${lines.join('\n')}` }],
346
+ structuredContent: { uploaded: ok, total: results.length, results },
206
347
  }
207
348
  },
208
349
  )
@@ -232,6 +373,141 @@ server.registerTool(
232
373
  },
233
374
  )
234
375
 
376
+ server.registerTool(
377
+ 'create_folder',
378
+ {
379
+ title: "Create components' Drive folders",
380
+ description:
381
+ "Finds or creates the `[SKU] Name` Google Drive folder of components that already exist in the " +
382
+ "PLM, on each part's own drive (staging or main), and links the folder to the component. SKUs " +
383
+ "not in the PLM are refused: a stray folder would later be read as a new part. Uploading a file " +
384
+ "also creates the folder, so this is only needed for an empty one.",
385
+ inputSchema: {
386
+ skus: z.array(z.string()).min(1).describe('Component SKUs, e.g. MNT-1234-X0.'),
387
+ },
388
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true },
389
+ },
390
+ async ({ skus }) => {
391
+ const results = []
392
+ for (const s of skus) {
393
+ const sku = s.trim().toUpperCase()
394
+ try {
395
+ const c = await findComponent(sku)
396
+ if (!c) throw new Error('not in the PLM, no folder made')
397
+ const bucket = driveOf(c)
398
+ const r = await edgeJson({ action: 'ensure', sku: c.sku, skuName: c.name, componentId: c.id, bucket })
399
+ if (!r?.connected) throw new Error('Drive is not connected')
400
+ if (r.error || !r.folderId) throw new Error(r.error || 'no folder returned')
401
+ results.push({ ok: true, sku: c.sku, bucket, created: !!r.created, folderId: r.folderId, folderUrl: r.folderUrl ?? null })
402
+ } catch (e) {
403
+ results.push({ ok: false, sku, error: e instanceof Error ? e.message : String(e) })
404
+ }
405
+ }
406
+ const lines = results.map((r) =>
407
+ r.ok ? `✓ ${r.sku} (${r.bucket}): ${r.created ? 'folder created' : 'folder already there'} ${r.folderUrl ?? ''}`.trim() : `✗ ${r.sku}: ${r.error}`,
408
+ )
409
+ return {
410
+ content: [{ type: 'text', text: lines.join('\n') }],
411
+ structuredContent: { results },
412
+ }
413
+ },
414
+ )
415
+
416
+ server.registerTool(
417
+ 'uprev_component',
418
+ {
419
+ title: 'Uprev a staging prototype',
420
+ description:
421
+ "Uprevs a staging prototype part to its next X revision (MNT-1234-X1 -> MNT-1234-X2), the same as " +
422
+ "Uprev in the PLM: a new component with the old one's details and its own staging Drive folder; " +
423
+ "the old revision stays as history. Optionally uploads the new revision's drawing PDF and STEP in " +
424
+ "the same step (renamed to carry the new SKU) and reads the drawing into the PLM, which lists an " +
425
+ "injection moulded part in Injection Mold Staging. The PDF is checked BEFORE anything is created: " +
426
+ "if its title block still shows the old SKU, no SKU/REV, or another part, NOTHING is uprevved and " +
427
+ "the warnings come back. Show them to the user and only call again with " +
428
+ "proceed_despite_warnings: true if they say to go ahead. A saved name that is not " +
429
+ "`[new SKU] Part Name REV0X` is uploaded but flagged (name_issue): tell the user. Only staging X0-X8 parts can be uprevved; " +
430
+ "releasing to A0 is a promotion request in the PLM.",
431
+ inputSchema: {
432
+ sku: z.string().describe('Current SKU of the staging part, e.g. MNT-1234-X1.'),
433
+ drawing_pdf: z.string().optional().describe("Absolute local path to the new revision's drawing PDF."),
434
+ step: z.string().optional().describe("Absolute local path to the new revision's STEP model."),
435
+ proceed_despite_warnings: z
436
+ .boolean()
437
+ .optional()
438
+ .describe('Uprev even though the drawing check warned. Only after the user has seen the warnings and said yes.'),
439
+ },
440
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
441
+ },
442
+ async ({ sku, drawing_pdf, step, proceed_despite_warnings = false }) => {
443
+ const reply = (text, data, isError = false) => ({ content: [{ type: 'text', text }], structuredContent: data, isError })
444
+ const stop = (text) => reply(text, { uprevved: false, error: text }, true)
445
+
446
+ const c = await findComponent(sku)
447
+ if (!c) return stop(`${sku.trim().toUpperCase()} is not in the PLM.`)
448
+ if (!c.staging) return stop(`${c.sku} is not a staging part; only staging prototypes can be uprevved.`)
449
+ const plan = nextRev(c.sku)
450
+ if (plan.error) return stop(plan.error)
451
+
452
+ // Both files must be readable before anything is created.
453
+ let pdfBytes = null
454
+ try {
455
+ if (drawing_pdf) pdfBytes = await readFile(drawing_pdf)
456
+ if (step) await stat(step)
457
+ } catch (e) {
458
+ return stop(`Nothing uprevved: ${e instanceof Error ? e.message : e}`)
459
+ }
460
+
461
+ let drawing = null
462
+ let warnings = []
463
+ if (pdfBytes) {
464
+ drawing = await previewDrawing(pdfBytes, basename(drawing_pdf))
465
+ warnings = drawingWarnings(drawing, plan.newSku, { sku: c.sku, drawing_rev: c.cad_revision })
466
+ if (warnings.length && !proceed_despite_warnings) {
467
+ return reply(
468
+ `Not uprevved yet. Checking the drawing against ${plan.newSku} found:\n- ${warnings.join('\n- ')}\n` +
469
+ 'Show this to the user. Only if they say to go ahead, call again with proceed_despite_warnings: true.',
470
+ { uprevved: false, new_sku: plan.newSku, warnings, drawing },
471
+ )
472
+ }
473
+ }
474
+
475
+ let created
476
+ try {
477
+ created = await edgeJson({ action: 'uprev', componentId: c.id })
478
+ } catch (e) {
479
+ return stop(`Uprev failed: ${e instanceof Error ? e.message : e}`)
480
+ }
481
+ if (!created?.new_id) return stop(`Uprev failed: ${created?.error ?? 'no new component returned'}`)
482
+ await audit(created.new_id, 'component_uprevved', { old_sku: c.sku, new_sku: created.new_sku })
483
+
484
+ const lines = [`Uprevved ${c.sku} -> ${created.new_sku}, with its own staging Drive folder; ${c.sku} stays as history.`]
485
+ const files = []
486
+ let read
487
+ try {
488
+ for (const [path, kind] of [[drawing_pdf, 'DRAWING'], [step, 'STEP']]) {
489
+ if (!path) continue
490
+ const original = basename(path)
491
+ const name = nameWithSku(original, created.new_sku)
492
+ const up = await uploadOne({ path, sku: created.new_sku, skuName: c.name, bucket: 'staging', filename: name })
493
+ files.push({ ...up, name_issue: fileNameIssue(name, created.new_sku) })
494
+ await audit(created.new_id, 'component.file_uploaded', {
495
+ file: name,
496
+ original_name: name !== original ? original : undefined,
497
+ ...(kind === 'DRAWING' ? { drawing_sku: drawing?.sku ?? null, drawing_rev: drawing?.rev ?? null, warnings } : {}),
498
+ })
499
+ if (kind === 'DRAWING' && up.driveFileId) read = await readDrawing(created.new_id, created.new_sku, up.driveFileId, name)
500
+ lines.push(`✓ ${name}${kind === 'DRAWING' ? readLine(read) : ''}${issueLine(files.at(-1).name_issue)}`)
501
+ }
502
+ } catch (e) {
503
+ lines.push(`✗ Upload failed: ${e instanceof Error ? e.message : e}. ${created.new_sku} was created; finish with upload_files.`)
504
+ return reply(lines.join('\n'), { uprevved: true, ...created, files, read, warnings }, true)
505
+ }
506
+ if (warnings.length) lines.push(`Uploaded despite the drawing check (kept in the part's history): ${warnings.join(' ')}`)
507
+ return reply(lines.join('\n'), { uprevved: true, ...created, files, read, warnings })
508
+ },
509
+ )
510
+
235
511
  // === Read-only tools (RLS-enforced via the engineer's token) =================
236
512
 
237
513
  server.registerTool(
@@ -488,6 +764,26 @@ if (process.argv.includes('--selftest')) {
488
764
  assert(JSON.stringify(stagingFilter('main')) === '{"staging":"eq.false"}', 'main -> staging=false')
489
765
  assert(JSON.stringify(stagingFilter('staging')) === '{"staging":"eq.true"}', 'staging -> staging=true')
490
766
  assert(JSON.stringify(stagingFilter('all')) === '{}', 'all -> no filter')
767
+ // ported rules (same cases as the PLM's injectionMould.test.ts)
768
+ assert(nameWithSku('Bracket.STEP', 'MNT-1234-X2') === '[MNT-1234-X2] Bracket.STEP', 'sku put in front')
769
+ assert(nameWithSku('MNT-1234-X1 Bracket.pdf', 'MNT-1234-X2') === 'MNT-1234-X2 Bracket.pdf', 'older rev swapped')
770
+ assert(nameWithSku('[MNT-1234-X2] Bracket.pdf', 'MNT-1234-X2') === '[MNT-1234-X2] Bracket.pdf', 'already named')
771
+ assert(fileNameIssue('[SKN-0176-X1] DEPTH CAMERA COVER LEFT REV00.STEP', 'SKN-0176-X1') === null, 'named right')
772
+ assert(fileNameIssue('notes.xlsx', 'SKN-0176-X1') === null, 'other file type not checked')
773
+ assert(fileNameIssue('[SKN-0176-X1] DEPTH CAMERA COVER LEFT.pdf', 'SKN-0176-X1'), 'no REV flagged')
774
+ assert(fileNameIssue('[SKN-0176-X0] DEPTH CAMERA COVER LEFT REV00.pdf', 'SKN-0176-X1'), 'other rev flagged')
775
+ assert(nextRev('MNT-1234-X1').newSku === 'MNT-1234-X2', 'X1 -> X2')
776
+ assert(nextRev('MNT-1234-X9').error && nextRev('MNT-1234-A0').error, 'X9 and A0 refused')
777
+ const prev = { sku: 'MNT-1234-X1', drawing_rev: '01' }
778
+ assert(drawingWarnings({ is_lionsbot: true, sku: 'MNT-1234-X2', rev: '02' }, 'MNT-1234-X2', prev).length === 0, 'clean drawing')
779
+ assert(/No difference/.test(drawingWarnings({ is_lionsbot: true, sku: 'MNT-1234-X1', rev: '01' }, 'MNT-1234-X2', prev)[0]), 'same sku + rev')
780
+ assert(drawingWarnings({ is_lionsbot: true, sku: 'MNT-1234-X2', rev: '01' }, 'MNT-1234-X2', prev).length === 0, 'new sku, rev unchanged')
781
+ assert(/reads MNT-1234-X1;/.test(drawingWarnings({ is_lionsbot: true, sku: 'MNT-1234-X1', rev: '02' }, 'MNT-1234-X2', prev)[0]), 'rev up, sku not')
782
+ assert(/different part/.test(drawingWarnings({ is_lionsbot: true, sku: 'BOX-0001-X0', rev: '02' }, 'MNT-1234-X2', prev)[0]), 'other part')
783
+ assert(/could not be read/.test(drawingWarnings(null, 'MNT-1234-X2', prev)[0]), 'unreadable')
784
+ assert(readOutcome({ written: true, extracted: { rev: '02', manufacturing_method: 'MOULD PLASTIC AND RUBBER' } }, 'MNT-1234-X2').listed, 'IM X rev listed')
785
+ assert(!readOutcome({ written: true, extracted: { manufacturing_method: 'MOULD PLASTIC AND RUBBER' } }, 'MNT-1234-A0').listed, 'released not listed')
786
+ assert(readOutcome({ written: false, extracted: { is_lionsbot: false } }, 'X').text === 'Not a LionsBot drawing, nothing read', 'not LB')
491
787
  console.log('selftest ok')
492
788
  process.exit(0)
493
789
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "plm-upload-mcp",
3
- "version": "1.1.0",
4
- "description": "MCP server to read the LionsBot PLM (SKU folders, component metadata, extracted drawing metadata, product & staging BOMs) and bulk-upload SolidWorks exports (STEP/PDF) into it by SKU.",
3
+ "version": "1.3.0",
4
+ "description": "MCP server to read the LionsBot PLM (SKU folders, component metadata, extracted drawing metadata, product & staging BOMs) bulk-upload SolidWorks exports (STEP/PDF) into it by SKU, create components' Drive folders and uprev staging prototypes.",
5
5
  "license": "UNLICENSED",
6
6
  "keywords": ["mcp", "modelcontextprotocol", "lionsbot", "plm", "solidworks"],
7
7
  "type": "module",