forked from ultraworkers/claw-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmcpbHandler.ts
More file actions
968 lines (869 loc) · 30.6 KB
/
Copy pathmcpbHandler.ts
File metadata and controls
968 lines (869 loc) · 30.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
import type {
McpbManifest,
McpbUserConfigurationOption,
} from '@anthropic-ai/mcpb'
import axios from 'axios'
import { createHash } from 'crypto'
import { chmod, writeFile } from 'fs/promises'
import { dirname, join } from 'path'
import type { McpServerConfig } from '../../services/mcp/types.js'
import { logForDebugging } from '../debug.js'
import { parseAndValidateManifestFromBytes } from '../dxt/helpers.js'
import { parseZipModes, unzipFile } from '../dxt/zip.js'
import { errorMessage, getErrnoCode, isENOENT, toError } from '../errors.js'
import { getFsImplementation } from '../fsOperations.js'
import { logError } from '../log.js'
import { getSecureStorage } from '../secureStorage/index.js'
import {
getSettings_DEPRECATED,
updateSettingsForSource,
} from '../settings/settings.js'
import { jsonParse, jsonStringify } from '../slowOperations.js'
import { getSystemDirectories } from '../systemDirectories.js'
import { classifyFetchError, logPluginFetch } from './fetchTelemetry.js'
/**
* User configuration values for MCPB
*/
export type UserConfigValues = Record<
string,
string | number | boolean | string[]
>
/**
* User configuration schema from DXT manifest
*/
export type UserConfigSchema = Record<string, McpbUserConfigurationOption>
/**
* Result of loading an MCPB file (success case)
*/
export type McpbLoadResult = {
manifest: McpbManifest
mcpConfig: McpServerConfig
extractedPath: string
contentHash: string
}
/**
* Result when MCPB needs user configuration
*/
export type McpbNeedsConfigResult = {
status: 'needs-config'
manifest: McpbManifest
extractedPath: string
contentHash: string
configSchema: UserConfigSchema
existingConfig: UserConfigValues
validationErrors: string[]
}
/**
* Metadata stored for each cached MCPB
*/
export type McpbCacheMetadata = {
source: string
contentHash: string
extractedPath: string
cachedAt: string
lastChecked: string
}
/**
* Progress callback for download and extraction operations
*/
export type ProgressCallback = (status: string) => void
/**
* Check if a source string is an MCPB file reference
*/
export function isMcpbSource(source: string): boolean {
return source.endsWith('.mcpb') || source.endsWith('.dxt')
}
/**
* Check if a source is a URL
*/
function isUrl(source: string): boolean {
return source.startsWith('http://') || source.startsWith('https://')
}
/**
* Generate content hash for an MCPB file
*/
function generateContentHash(data: Uint8Array): string {
return createHash('sha256').update(data).digest('hex').substring(0, 16)
}
/**
* Get cache directory for MCPB files
*/
function getMcpbCacheDir(pluginPath: string): string {
return join(pluginPath, '.mcpb-cache')
}
/**
* Get metadata file path for cached MCPB
*/
function getMetadataPath(cacheDir: string, source: string): string {
const sourceHash = createHash('md5')
.update(source)
.digest('hex')
.substring(0, 8)
return join(cacheDir, `${sourceHash}.metadata.json`)
}
/**
* Compose the secureStorage key for a per-server secret bucket.
* `pluginSecrets` is a flat map — per-server secrets share it with top-level
* plugin options (pluginOptionsStorage.ts) using a `${pluginId}/${server}`
* composite key. `/` can't appear in plugin IDs (`name@marketplace`) or
* server names (MCP identifier constraints), so it's unambiguous. Keeps the
* SecureStorageData schema unchanged and the single-keychain-entry size
* budget (~2KB stdin-safe, see INC-3028) shared across all plugin secrets.
*/
function serverSecretsKey(pluginId: string, serverName: string): string {
return `${pluginId}/${serverName}`
}
/**
* Load user configuration for an MCP server, merging non-sensitive values
* (from settings.json) with sensitive values (from secureStorage keychain).
* secureStorage wins on collision — schema determines destination so
* collision shouldn't happen, but if a user hand-edits settings.json we
* trust the more secure source.
*
* Returns null only if NEITHER source has anything — callers skip
* ${user_config.X} substitution in that case.
*
* @param pluginId - Plugin identifier in "plugin@marketplace" format
* @param serverName - MCP server name from DXT manifest
*/
export function loadMcpServerUserConfig(
pluginId: string,
serverName: string,
): UserConfigValues | null {
try {
const settings = getSettings_DEPRECATED()
const nonSensitive =
settings.pluginConfigs?.[pluginId]?.mcpServers?.[serverName]
const sensitive =
getSecureStorage().read()?.pluginSecrets?.[
serverSecretsKey(pluginId, serverName)
]
if (!nonSensitive && !sensitive) {
return null
}
logForDebugging(
`Loaded user config for ${pluginId}/${serverName} (settings + secureStorage)`,
)
return { ...nonSensitive, ...sensitive }
} catch (error) {
const errorObj = toError(error)
logError(errorObj)
logForDebugging(
`Failed to load user config for ${pluginId}/${serverName}: ${error}`,
{ level: 'error' },
)
return null
}
}
/**
* Save user configuration for an MCP server, splitting by `schema[key].sensitive`.
* Mirrors savePluginOptions (pluginOptionsStorage.ts:90) for top-level options:
* - `sensitive: true` → secureStorage (keychain on macOS, .credentials.json 0600 elsewhere)
* - everything else → settings.json pluginConfigs[pluginId].mcpServers[serverName]
*
* Without this split, per-channel `sensitive: true` was a false sense of
* security — the dialog masked the input but the save went to plaintext
* settings.json anyway. H1 #3617646 (Telegram/Discord bot tokens in
* world-readable .env) surfaced this as the gap to close.
*
* Writes are skipped if nothing in that category is present.
*
* @param pluginId - Plugin identifier in "plugin@marketplace" format
* @param serverName - MCP server name from DXT manifest
* @param config - User configuration values
* @param schema - The userConfig schema for this server (manifest.user_config
* or channels[].userConfig) — drives the sensitive/non-sensitive split
*/
export function saveMcpServerUserConfig(
pluginId: string,
serverName: string,
config: UserConfigValues,
schema: UserConfigSchema,
): void {
try {
const nonSensitive: UserConfigValues = {}
const sensitive: Record<string, string> = {}
for (const [key, value] of Object.entries(config)) {
if (schema[key]?.sensitive === true) {
sensitive[key] = String(value)
} else {
nonSensitive[key] = value
}
}
// Scrub ONLY keys we're writing in this call. Covers both directions
// across schema-version flips:
// - sensitive→secureStorage ⇒ remove stale plaintext from settings.json
// - nonSensitive→settings.json ⇒ remove stale entry from secureStorage
// (otherwise loadMcpServerUserConfig's {...nonSensitive, ...sensitive}
// would let the stale secureStorage value win on next read)
// Partial `config` (user only re-enters one field) leaves other fields
// untouched in BOTH stores — defense-in-depth against future callers.
const sensitiveKeysInThisSave = new Set(Object.keys(sensitive))
const nonSensitiveKeysInThisSave = new Set(Object.keys(nonSensitive))
// Sensitive → secureStorage FIRST. If this fails (keychain locked,
// .credentials.json perms), throw before touching settings.json — the
// old plaintext stays as a fallback instead of losing BOTH copies.
//
// Also scrub non-sensitive keys from secureStorage — schema flipped
// sensitive→false and they're being written to settings.json now. Without
// this, loadMcpServerUserConfig's merge would let the stale secureStorage
// value win on next read.
const storage = getSecureStorage()
const k = serverSecretsKey(pluginId, serverName)
const existingInSecureStorage =
storage.read()?.pluginSecrets?.[k] ?? undefined
const secureScrubbed = existingInSecureStorage
? Object.fromEntries(
Object.entries(existingInSecureStorage).filter(
([key]) => !nonSensitiveKeysInThisSave.has(key),
),
)
: undefined
const needSecureScrub =
secureScrubbed &&
existingInSecureStorage &&
Object.keys(secureScrubbed).length !==
Object.keys(existingInSecureStorage).length
if (Object.keys(sensitive).length > 0 || needSecureScrub) {
const existing = storage.read() ?? {}
if (!existing.pluginSecrets) {
existing.pluginSecrets = {}
}
// secureStorage keyvault is a flat object — direct replace, no merge
// semantics to worry about (unlike settings.json's mergeWith).
existing.pluginSecrets[k] = {
...secureScrubbed,
...sensitive,
}
const result = storage.update(existing)
if (!result.success) {
throw new Error(
`Failed to save sensitive config to secure storage for ${k}`,
)
}
if (result.warning) {
logForDebugging(`Server secrets save warning: ${result.warning}`, {
level: 'warn',
})
}
if (needSecureScrub) {
logForDebugging(
`saveMcpServerUserConfig: scrubbed ${
Object.keys(existingInSecureStorage!).length -
Object.keys(secureScrubbed!).length
} stale non-sensitive key(s) from secureStorage for ${k}`,
)
}
}
// Non-sensitive → settings.json. Write whenever there are new non-sensitive
// values OR existing plaintext sensitive values to scrub — so reconfiguring
// a sensitive-only schema still cleans up the old settings.json. Runs
// AFTER the secureStorage write succeeded, so the scrub can't leave you
// with zero copies of the secret.
//
// updateSettingsForSource does mergeWith(diskSettings, ourSettings, ...)
// which PRESERVES destination keys absent from source — so simply omitting
// sensitive keys doesn't scrub them, the disk copy merges back in. Instead:
// set each sensitive key to explicit `undefined` — mergeWith (with the
// customizer at settings.ts:349) treats explicit undefined as a delete.
const settings = getSettings_DEPRECATED()
const existingInSettings =
settings.pluginConfigs?.[pluginId]?.mcpServers?.[serverName] ?? {}
const keysToScrubFromSettings = Object.keys(existingInSettings).filter(k =>
sensitiveKeysInThisSave.has(k),
)
if (
Object.keys(nonSensitive).length > 0 ||
keysToScrubFromSettings.length > 0
) {
if (!settings.pluginConfigs) {
settings.pluginConfigs = {}
}
if (!settings.pluginConfigs[pluginId]) {
settings.pluginConfigs[pluginId] = {}
}
if (!settings.pluginConfigs[pluginId].mcpServers) {
settings.pluginConfigs[pluginId].mcpServers = {}
}
// Build the scrub-via-undefined map. The UserConfigValues type doesn't
// include undefined, but updateSettingsForSource's mergeWith customizer
// needs explicit undefined to delete — cast is deliberate internal
// plumbing (same rationale as deletePluginOptions in
// pluginOptionsStorage.ts:184, see CLAUDE.md's 10% case).
const scrubbed = Object.fromEntries(
keysToScrubFromSettings.map(k => [k, undefined]),
) as Record<string, undefined>
settings.pluginConfigs[pluginId].mcpServers![serverName] = {
...nonSensitive,
...scrubbed,
} as UserConfigValues
const result = updateSettingsForSource('userSettings', settings)
if (result.error) {
throw result.error
}
if (keysToScrubFromSettings.length > 0) {
logForDebugging(
`saveMcpServerUserConfig: scrubbed ${keysToScrubFromSettings.length} plaintext sensitive key(s) from settings.json for ${pluginId}/${serverName}`,
)
}
}
logForDebugging(
`Saved user config for ${pluginId}/${serverName} (${Object.keys(nonSensitive).length} non-sensitive, ${Object.keys(sensitive).length} sensitive)`,
)
} catch (error) {
const errorObj = toError(error)
logError(errorObj)
throw new Error(
`Failed to save user configuration for ${pluginId}/${serverName}: ${errorObj.message}`,
)
}
}
/**
* Validate user configuration values against DXT user_config schema
*/
export function validateUserConfig(
values: UserConfigValues,
schema: UserConfigSchema,
): { valid: boolean; errors: string[] } {
const errors: string[] = []
// Check each field in the schema
for (const [key, fieldSchema] of Object.entries(schema)) {
const value = values[key]
// Check required fields
if (fieldSchema.required && (value === undefined || value === '')) {
errors.push(`${fieldSchema.title || key} is required but not provided`)
continue
}
// Skip validation for optional fields that aren't provided
if (value === undefined || value === '') {
continue
}
// Type validation
if (fieldSchema.type === 'string') {
if (Array.isArray(value)) {
// String arrays are allowed if multiple: true
if (!fieldSchema.multiple) {
errors.push(
`${fieldSchema.title || key} must be a string, not an array`,
)
} else if (!value.every(v => typeof v === 'string')) {
errors.push(`${fieldSchema.title || key} must be an array of strings`)
}
} else if (typeof value !== 'string') {
errors.push(`${fieldSchema.title || key} must be a string`)
}
} else if (fieldSchema.type === 'number' && typeof value !== 'number') {
errors.push(`${fieldSchema.title || key} must be a number`)
} else if (fieldSchema.type === 'boolean' && typeof value !== 'boolean') {
errors.push(`${fieldSchema.title || key} must be a boolean`)
} else if (
(fieldSchema.type === 'file' || fieldSchema.type === 'directory') &&
typeof value !== 'string'
) {
errors.push(`${fieldSchema.title || key} must be a path string`)
}
// Number range validation
if (fieldSchema.type === 'number' && typeof value === 'number') {
if (fieldSchema.min !== undefined && value < fieldSchema.min) {
errors.push(
`${fieldSchema.title || key} must be at least ${fieldSchema.min}`,
)
}
if (fieldSchema.max !== undefined && value > fieldSchema.max) {
errors.push(
`${fieldSchema.title || key} must be at most ${fieldSchema.max}`,
)
}
}
}
return { valid: errors.length === 0, errors }
}
/**
* Generate MCP server configuration from DXT manifest
*/
async function generateMcpConfig(
manifest: McpbManifest,
extractedPath: string,
userConfig: UserConfigValues = {},
): Promise<McpServerConfig> {
// Lazy import: @anthropic-ai/mcpb barrel pulls in zod v3 schemas (~700KB of
// bound closures). See dxt/helpers.ts for details.
const { getMcpConfigForManifest } = await import('@anthropic-ai/mcpb')
const mcpConfig = await getMcpConfigForManifest({
manifest,
extensionPath: extractedPath,
systemDirs: getSystemDirectories(),
userConfig,
pathSeparator: '/',
})
if (!mcpConfig) {
const error = new Error(
`Failed to generate MCP server configuration from manifest "${manifest.name}"`,
)
logError(error)
throw error
}
return mcpConfig as McpServerConfig
}
/**
* Load cache metadata for an MCPB source
*/
async function loadCacheMetadata(
cacheDir: string,
source: string,
): Promise<McpbCacheMetadata | null> {
const fs = getFsImplementation()
const metadataPath = getMetadataPath(cacheDir, source)
try {
const content = await fs.readFile(metadataPath, { encoding: 'utf-8' })
return jsonParse(content) as McpbCacheMetadata
} catch (error) {
const code = getErrnoCode(error)
if (code === 'ENOENT') return null
const errorObj = toError(error)
logError(errorObj)
logForDebugging(`Failed to load MCPB cache metadata: ${error}`, {
level: 'error',
})
return null
}
}
/**
* Save cache metadata for an MCPB source
*/
async function saveCacheMetadata(
cacheDir: string,
source: string,
metadata: McpbCacheMetadata,
): Promise<void> {
const metadataPath = getMetadataPath(cacheDir, source)
await getFsImplementation().mkdir(cacheDir)
await writeFile(metadataPath, jsonStringify(metadata, null, 2), 'utf-8')
}
/**
* Download MCPB file from URL
*/
async function downloadMcpb(
url: string,
destPath: string,
onProgress?: ProgressCallback,
): Promise<Uint8Array> {
logForDebugging(`Downloading MCPB from ${url}`)
if (onProgress) {
onProgress(`Downloading ${url}...`)
}
const started = performance.now()
let fetchTelemetryFired = false
try {
const response = await axios.get(url, {
timeout: 120000, // 2 minute timeout
responseType: 'arraybuffer',
maxRedirects: 5, // Follow redirects (like curl -L)
onDownloadProgress: progressEvent => {
if (progressEvent.total && onProgress) {
const percent = Math.round(
(progressEvent.loaded / progressEvent.total) * 100,
)
onProgress(`Downloading... ${percent}%`)
}
},
})
const data = new Uint8Array(response.data)
// Fire telemetry before writeFile — the event measures the network
// fetch, not disk I/O. A writeFile EACCES would otherwise match
// classifyFetchError's /permission denied/ → misreport as auth.
logPluginFetch('mcpb', url, 'success', performance.now() - started)
fetchTelemetryFired = true
// Save to disk (binary data)
await writeFile(destPath, Buffer.from(data))
logForDebugging(`Downloaded ${data.length} bytes to ${destPath}`)
if (onProgress) {
onProgress('Download complete')
}
return data
} catch (error) {
if (!fetchTelemetryFired) {
logPluginFetch(
'mcpb',
url,
'failure',
performance.now() - started,
classifyFetchError(error),
)
}
const errorMsg = errorMessage(error)
const fullError = new Error(
`Failed to download MCPB file from ${url}: ${errorMsg}`,
)
logError(fullError)
throw fullError
}
}
/**
* Extract MCPB file and write contents to extraction directory.
*
* @param modes - name→mode map from `parseZipModes`. MCPB bundles can ship
* native MCP server binaries, so preserving the exec bit matters here.
*/
async function extractMcpbContents(
unzipped: Record<string, Uint8Array>,
extractPath: string,
modes: Record<string, number>,
onProgress?: ProgressCallback,
): Promise<void> {
if (onProgress) {
onProgress('Extracting files...')
}
// Create extraction directory
await getFsImplementation().mkdir(extractPath)
// Write all files. Filter directory entries from the count so progress
// messages use the same denominator as filesWritten (which skips them).
let filesWritten = 0
const entries = Object.entries(unzipped).filter(([k]) => !k.endsWith('/'))
const totalFiles = entries.length
for (const [filePath, fileData] of entries) {
// Directory entries (common in zip -r, Python zipfile, Java ZipOutputStream)
// are filtered above — writeFile would create `bin/` as an empty regular
// file, then mkdir for `bin/server` would fail with ENOTDIR. The
// mkdir(dirname(fullPath)) below creates parent dirs implicitly.
const fullPath = join(extractPath, filePath)
const dir = dirname(fullPath)
// Ensure directory exists (recursive handles already-existing)
if (dir !== extractPath) {
await getFsImplementation().mkdir(dir)
}
// Determine if text or binary
const isTextFile =
filePath.endsWith('.json') ||
filePath.endsWith('.js') ||
filePath.endsWith('.ts') ||
filePath.endsWith('.txt') ||
filePath.endsWith('.md') ||
filePath.endsWith('.yml') ||
filePath.endsWith('.yaml')
if (isTextFile) {
const content = new TextDecoder().decode(fileData)
await writeFile(fullPath, content, 'utf-8')
} else {
await writeFile(fullPath, Buffer.from(fileData))
}
const mode = modes[filePath]
if (mode && mode & 0o111) {
// Swallow EPERM/ENOTSUP (NFS root_squash, some FUSE mounts) — losing +x
// is the pre-PR behavior and better than aborting mid-extraction.
await chmod(fullPath, mode & 0o777).catch(() => {})
}
filesWritten++
if (onProgress && filesWritten % 10 === 0) {
onProgress(`Extracted ${filesWritten}/${totalFiles} files`)
}
}
logForDebugging(`Extracted ${filesWritten} files to ${extractPath}`)
if (onProgress) {
onProgress(`Extraction complete (${filesWritten} files)`)
}
}
/**
* Check if an MCPB source has changed and needs re-extraction
*/
export async function checkMcpbChanged(
source: string,
pluginPath: string,
): Promise<boolean> {
const fs = getFsImplementation()
const cacheDir = getMcpbCacheDir(pluginPath)
const metadata = await loadCacheMetadata(cacheDir, source)
if (!metadata) {
// No cache metadata, needs loading
return true
}
// Check if extraction directory still exists
try {
await fs.stat(metadata.extractedPath)
} catch (error) {
const code = getErrnoCode(error)
if (code === 'ENOENT') {
logForDebugging(`MCPB extraction path missing: ${metadata.extractedPath}`)
} else {
logForDebugging(
`MCPB extraction path inaccessible: ${metadata.extractedPath}: ${error}`,
{ level: 'error' },
)
}
return true
}
// For local files, check mtime
if (!isUrl(source)) {
const localPath = join(pluginPath, source)
let stats
try {
stats = await fs.stat(localPath)
} catch (error) {
const code = getErrnoCode(error)
if (code === 'ENOENT') {
logForDebugging(`MCPB source file missing: ${localPath}`)
} else {
logForDebugging(
`MCPB source file inaccessible: ${localPath}: ${error}`,
{ level: 'error' },
)
}
return true
}
const cachedTime = new Date(metadata.cachedAt).getTime()
// Floor to match the ms precision of cachedAt (ISO string). Sub-ms
// precision on mtimeMs would make a freshly-cached file appear "newer"
// than its own cache timestamp when both happen in the same millisecond.
const fileTime = Math.floor(stats.mtimeMs)
if (fileTime > cachedTime) {
logForDebugging(
`MCPB file modified: ${new Date(fileTime)} > ${new Date(cachedTime)}`,
)
return true
}
}
// For URLs, we'll re-check on explicit update (handled elsewhere)
return false
}
/**
* Load and extract an MCPB file, with caching and user configuration support
*
* @param source - MCPB file path or URL
* @param pluginPath - Plugin directory path
* @param pluginId - Plugin identifier in "plugin@marketplace" format (for config storage)
* @param onProgress - Progress callback
* @param providedUserConfig - User configuration values (for initial setup or reconfiguration)
* @returns Success with MCP config, or needs-config status with schema
*/
export async function loadMcpbFile(
source: string,
pluginPath: string,
pluginId: string,
onProgress?: ProgressCallback,
providedUserConfig?: UserConfigValues,
forceConfigDialog?: boolean,
): Promise<McpbLoadResult | McpbNeedsConfigResult> {
const fs = getFsImplementation()
const cacheDir = getMcpbCacheDir(pluginPath)
await fs.mkdir(cacheDir)
logForDebugging(`Loading MCPB from source: ${source}`)
// Check cache first
const metadata = await loadCacheMetadata(cacheDir, source)
if (metadata && !(await checkMcpbChanged(source, pluginPath))) {
logForDebugging(
`Using cached MCPB from ${metadata.extractedPath} (hash: ${metadata.contentHash})`,
)
// Load manifest from cache
const manifestPath = join(metadata.extractedPath, 'manifest.json')
let manifestContent: string
try {
manifestContent = await fs.readFile(manifestPath, { encoding: 'utf-8' })
} catch (error) {
if (isENOENT(error)) {
const err = new Error(`Cached manifest not found: ${manifestPath}`)
logError(err)
throw err
}
throw error
}
const manifestData = new TextEncoder().encode(manifestContent)
const manifest = await parseAndValidateManifestFromBytes(manifestData)
// Check for user_config requirement
if (manifest.user_config && Object.keys(manifest.user_config).length > 0) {
// Server name from DXT manifest
const serverName = manifest.name
// Try to load existing config from settings.json or use provided config
const savedConfig = loadMcpServerUserConfig(pluginId, serverName)
const userConfig = providedUserConfig || savedConfig || {}
// Validate we have all required fields
const validation = validateUserConfig(userConfig, manifest.user_config)
// Return needs-config if: forced (reconfiguration) OR validation failed
if (forceConfigDialog || !validation.valid) {
return {
status: 'needs-config',
manifest,
extractedPath: metadata.extractedPath,
contentHash: metadata.contentHash,
configSchema: manifest.user_config,
existingConfig: savedConfig || {},
validationErrors: validation.valid ? [] : validation.errors,
}
}
// Save config if it was provided (first time or reconfiguration)
if (providedUserConfig) {
saveMcpServerUserConfig(
pluginId,
serverName,
providedUserConfig,
manifest.user_config ?? {},
)
}
// Generate MCP config WITH user config
const mcpConfig = await generateMcpConfig(
manifest,
metadata.extractedPath,
userConfig,
)
return {
manifest,
mcpConfig,
extractedPath: metadata.extractedPath,
contentHash: metadata.contentHash,
}
}
// No user_config required - generate config without it
const mcpConfig = await generateMcpConfig(manifest, metadata.extractedPath)
return {
manifest,
mcpConfig,
extractedPath: metadata.extractedPath,
contentHash: metadata.contentHash,
}
}
// Not cached or changed - need to download/load and extract
let mcpbData: Uint8Array
let mcpbFilePath: string
if (isUrl(source)) {
// Download from URL
const sourceHash = createHash('md5')
.update(source)
.digest('hex')
.substring(0, 8)
mcpbFilePath = join(cacheDir, `${sourceHash}.mcpb`)
mcpbData = await downloadMcpb(source, mcpbFilePath, onProgress)
} else {
// Load from local path
const localPath = join(pluginPath, source)
if (onProgress) {
onProgress(`Loading ${source}...`)
}
try {
mcpbData = await fs.readFileBytes(localPath)
mcpbFilePath = localPath
} catch (error) {
if (isENOENT(error)) {
const err = new Error(`MCPB file not found: ${localPath}`)
logError(err)
throw err
}
throw error
}
}
// Generate content hash
const contentHash = generateContentHash(mcpbData)
logForDebugging(`MCPB content hash: ${contentHash}`)
// Extract ZIP
if (onProgress) {
onProgress('Extracting MCPB archive...')
}
const unzipped = await unzipFile(Buffer.from(mcpbData))
// fflate doesn't surface external_attr — parse the central directory so
// native MCP server binaries keep their exec bit after extraction.
const modes = parseZipModes(mcpbData)
// Check for manifest.json
const manifestData = unzipped['manifest.json']
if (!manifestData) {
const error = new Error('No manifest.json found in MCPB file')
logError(error)
throw error
}
// Parse and validate manifest
const manifest = await parseAndValidateManifestFromBytes(manifestData)
logForDebugging(
`MCPB manifest: ${manifest.name} v${manifest.version} by ${manifest.author.name}`,
)
// Check if manifest has server config
if (!manifest.server) {
const error = new Error(
`MCPB manifest for "${manifest.name}" does not define a server configuration`,
)
logError(error)
throw error
}
// Extract to cache directory
const extractPath = join(cacheDir, contentHash)
await extractMcpbContents(unzipped, extractPath, modes, onProgress)
// Check for user_config requirement
if (manifest.user_config && Object.keys(manifest.user_config).length > 0) {
// Server name from DXT manifest
const serverName = manifest.name
// Try to load existing config from settings.json or use provided config
const savedConfig = loadMcpServerUserConfig(pluginId, serverName)
const userConfig = providedUserConfig || savedConfig || {}
// Validate we have all required fields
const validation = validateUserConfig(userConfig, manifest.user_config)
if (!validation.valid) {
// Save cache metadata even though config is incomplete
const newMetadata: McpbCacheMetadata = {
source,
contentHash,
extractedPath: extractPath,
cachedAt: new Date().toISOString(),
lastChecked: new Date().toISOString(),
}
await saveCacheMetadata(cacheDir, source, newMetadata)
// Return "needs configuration" status
return {
status: 'needs-config',
manifest,
extractedPath: extractPath,
contentHash,
configSchema: manifest.user_config,
existingConfig: savedConfig || {},
validationErrors: validation.errors,
}
}
// Save config if it was provided (first time or reconfiguration)
if (providedUserConfig) {
saveMcpServerUserConfig(
pluginId,
serverName,
providedUserConfig,
manifest.user_config ?? {},
)
}
// Generate MCP config WITH user config
if (onProgress) {
onProgress('Generating MCP server configuration...')
}
const mcpConfig = await generateMcpConfig(manifest, extractPath, userConfig)
// Save cache metadata
const newMetadata: McpbCacheMetadata = {
source,
contentHash,
extractedPath: extractPath,
cachedAt: new Date().toISOString(),
lastChecked: new Date().toISOString(),
}
await saveCacheMetadata(cacheDir, source, newMetadata)
return {
manifest,
mcpConfig,
extractedPath: extractPath,
contentHash,
}
}
// No user_config required - generate config without it
if (onProgress) {
onProgress('Generating MCP server configuration...')
}
const mcpConfig = await generateMcpConfig(manifest, extractPath)
// Save cache metadata
const newMetadata: McpbCacheMetadata = {
source,
contentHash,
extractedPath: extractPath,
cachedAt: new Date().toISOString(),
lastChecked: new Date().toISOString(),
}
await saveCacheMetadata(cacheDir, source, newMetadata)
logForDebugging(
`Successfully loaded MCPB: ${manifest.name} (extracted to ${extractPath})`,
)
return {
manifest,
mcpConfig: mcpConfig as McpServerConfig,
extractedPath: extractPath,
contentHash,
}
}