forked from dipseth/dataproc-mcp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcluster-handlers.ts
More file actions
941 lines (816 loc) · 31.3 KB
/
cluster-handlers.ts
File metadata and controls
941 lines (816 loc) · 31.3 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
/**
* Cluster operation handlers
* Extracted from main server file for better organization
*/
import { McpError, ErrorCode } from '@modelcontextprotocol/sdk/types.js';
import { logger } from '../utils/logger.js';
import { deepMerge } from '../utils/object-utils.js';
import SecurityMiddleware from '../security/middleware.js';
import {
StartDataprocClusterSchema,
ListClustersSchema,
GetClusterSchema,
DeleteClusterSchema,
} from '../validation/schemas.js';
import { createCluster, deleteCluster, listClusters, getCluster } from '../services/cluster.js';
import { DefaultParameterManager } from '../services/default-params.js';
import { ResponseFilter } from '../services/response-filter.js';
import { KnowledgeIndexer } from '../services/knowledge-indexer.js';
import { ProfileManager } from '../services/profile.js';
import { ClusterTracker } from '../services/tracker.js';
import { TemplatingIntegration } from '../services/templating-integration.js';
export interface HandlerDependencies {
defaultParamManager?: DefaultParameterManager;
responseFilter?: ResponseFilter;
knowledgeIndexer?: KnowledgeIndexer;
profileManager?: ProfileManager;
clusterTracker?: ClusterTracker;
templatingIntegration?: TemplatingIntegration;
}
export async function handleStartDataprocCluster(args: any, deps: HandlerDependencies) {
// Apply security middleware
SecurityMiddleware.checkRateLimit(`start_dataproc_cluster:${JSON.stringify(args)}`);
// Sanitize input
const sanitizedArgs = SecurityMiddleware.sanitizeObject(args);
// Validate input with Zod schema
let validatedArgs;
try {
validatedArgs = SecurityMiddleware.validateInput(StartDataprocClusterSchema, sanitizedArgs);
} catch (error) {
SecurityMiddleware.auditLog(
'Input validation failed',
{
tool: 'start_dataproc_cluster',
error: error instanceof Error ? error.message : 'Unknown error',
args: SecurityMiddleware.sanitizeForLogging(args),
},
'warn'
);
throw new McpError(
ErrorCode.InvalidParams,
error instanceof Error ? error.message : 'Invalid input'
);
}
// Get default parameters if not provided
const { clusterName, clusterConfig } = validatedArgs;
let { projectId, region } = validatedArgs;
if (!projectId && deps.defaultParamManager) {
try {
projectId = deps.defaultParamManager.getParameterValue('projectId');
} catch (error) {
// Ignore error, will be caught by validation below
}
}
if (!region && deps.defaultParamManager) {
try {
region = deps.defaultParamManager.getParameterValue('region');
} catch (error) {
// Ignore error, will be caught by validation below
}
}
// Validate required parameters after defaults
if (!projectId || !region) {
throw new McpError(ErrorCode.InvalidParams, 'Missing required parameters: projectId, region');
}
// Additional GCP constraint validation
SecurityMiddleware.validateGCPConstraints({ projectId, region, clusterName });
// Audit log the operation
SecurityMiddleware.auditLog('Cluster creation initiated', {
tool: 'start_dataproc_cluster',
projectId,
region,
clusterName,
hasConfig: !!clusterConfig,
});
logger.debug(
'MCP start_dataproc_cluster: Called with validated params:',
SecurityMiddleware.sanitizeForLogging({ projectId, region, clusterName, clusterConfig })
);
let response;
try {
response = await createCluster(projectId, region, clusterName, clusterConfig);
// Track the cluster if clusterTracker is available
// The clusterUuid is in response.metadata.clusterUuid for operation responses
const clusterUuid = response?.metadata?.clusterUuid || response?.clusterUuid;
if (response && clusterUuid && deps.clusterTracker) {
logger.debug('MCP start_dataproc_cluster: Tracking cluster:', {
clusterUuid,
clusterName,
projectId,
region,
responseType: response.metadata ? 'operation' : 'cluster',
});
deps.clusterTracker.trackCluster(
clusterUuid,
clusterName,
undefined, // No profile ID for direct cluster creation
undefined, // No profile path
{
projectId,
region,
createdAt: new Date().toISOString(),
tool: 'start_dataproc_cluster',
}
);
logger.debug('MCP start_dataproc_cluster: Cluster tracked successfully');
} else {
logger.debug('MCP start_dataproc_cluster: Cluster tracking skipped:', {
hasResponse: !!response,
hasClusterUuid: !!(response && clusterUuid),
hasClusterTracker: !!deps.clusterTracker,
responseStructure: response ? Object.keys(response) : 'no response',
});
}
SecurityMiddleware.auditLog('Cluster creation completed', {
tool: 'start_dataproc_cluster',
projectId,
region,
clusterName,
success: true,
});
logger.debug(
'MCP start_dataproc_cluster: createCluster response:',
SecurityMiddleware.sanitizeForLogging(response)
);
} catch (error) {
SecurityMiddleware.auditLog(
'Cluster creation failed',
{
tool: 'start_dataproc_cluster',
projectId,
region,
clusterName,
error: error instanceof Error ? error.message : 'Unknown error',
},
'error'
);
logger.error('MCP start_dataproc_cluster: Error from createCluster:', error);
throw error;
}
return {
content: [
{
type: 'text',
text: `Cluster ${clusterName} started successfully in region ${region}.\nCluster details:\n${JSON.stringify(SecurityMiddleware.sanitizeForLogging(response), null, 2)}`,
},
],
};
}
export async function handleListClusters(args: any, deps: HandlerDependencies) {
// Apply security middleware
SecurityMiddleware.checkRateLimit(`list_clusters:${JSON.stringify(args)}`);
// Sanitize input
const sanitizedArgs = SecurityMiddleware.sanitizeObject(args);
// Validate input with Zod schema
let validatedArgs;
try {
validatedArgs = SecurityMiddleware.validateInput(ListClustersSchema, sanitizedArgs);
} catch (error) {
SecurityMiddleware.auditLog(
'Input validation failed',
{
tool: 'list_clusters',
error: error instanceof Error ? error.message : 'Unknown error',
args: SecurityMiddleware.sanitizeForLogging(args),
},
'warn'
);
throw new McpError(
ErrorCode.InvalidParams,
error instanceof Error ? error.message : 'Invalid input'
);
}
// Get default parameters if not provided
const { filter, pageSize, pageToken } = validatedArgs;
let { projectId, region } = validatedArgs;
if (!projectId && deps.defaultParamManager) {
try {
projectId = deps.defaultParamManager.getParameterValue('projectId');
} catch (error) {
// Ignore error, will be caught by validation below
}
}
if (!region && deps.defaultParamManager) {
try {
region = deps.defaultParamManager.getParameterValue('region');
} catch (error) {
// Ignore error, will be caught by validation below
}
}
// Validate required parameters after defaults
if (!projectId || !region) {
throw new McpError(ErrorCode.InvalidParams, 'Missing required parameters: projectId, region');
}
// Additional GCP constraint validation
SecurityMiddleware.validateGCPConstraints({ projectId, region });
// Audit log the operation
SecurityMiddleware.auditLog('Cluster list requested', {
tool: 'list_clusters',
projectId,
region,
hasFilter: !!filter,
pageSize,
});
const response = await listClusters(projectId, region, filter, pageSize, pageToken);
SecurityMiddleware.auditLog('Cluster list completed', {
tool: 'list_clusters',
projectId,
region,
clusterCount: Array.isArray(response?.clusters) ? response.clusters.length : 0,
});
// Index cluster knowledge if available
if (deps.knowledgeIndexer && response?.clusters) {
try {
for (const cluster of response.clusters) {
await deps.knowledgeIndexer.indexClusterConfiguration(cluster as any);
}
logger.info(`Indexed ${response.clusters.length} clusters for knowledge base`);
} catch (indexError) {
logger.warn('Failed to index cluster knowledge:', indexError);
}
}
// Handle semantic query using KnowledgeIndexer if available
if (args.semanticQuery && deps.knowledgeIndexer) {
try {
const queryResults = await deps.knowledgeIndexer.queryKnowledge(String(args.semanticQuery), {
type: 'cluster',
projectId: projectId ? String(projectId) : undefined,
region: region ? String(region) : undefined,
limit: 5,
});
if (queryResults.length === 0) {
// Fall back to regular formatted response with semantic query note
let fallbackText = `🔍 **Semantic Query**: "${args.semanticQuery}"\n❌ **No semantic results found**\n\n`;
// Use the same response filtering logic as regular queries
if (deps.responseFilter && !args.verbose) {
try {
const filteredResponse = await deps.responseFilter.filterResponse(
'list_clusters',
response,
{
toolName: 'list_clusters',
timestamp: new Date().toISOString(),
projectId,
region,
responseType: 'cluster_list',
originalTokenCount: JSON.stringify(response).length,
filteredTokenCount: 0,
compressionRatio: 1.0,
}
);
const formattedContent =
filteredResponse.type === 'summary'
? filteredResponse.summary || filteredResponse.content
: filteredResponse.content;
fallbackText += formattedContent;
fallbackText += `\n\n💡 **Note**: Semantic search requires Qdrant vector database. To enable:\n`;
fallbackText += `- Start Qdrant: \`docker run -p 6334:6333 qdrant/qdrant\`\n`;
fallbackText += `- Or use regular cluster operations without semantic queries`;
} catch (filterError) {
logger.warn('Response filtering failed in semantic fallback:', filterError);
fallbackText += `📋 **Regular cluster list**:\n${JSON.stringify(SecurityMiddleware.sanitizeForLogging(response), null, 2)}`;
}
} else {
fallbackText += `📋 **Regular cluster list**:\n${JSON.stringify(SecurityMiddleware.sanitizeForLogging(response), null, 2)}`;
}
return {
content: [
{
type: 'text',
text: fallbackText,
},
],
};
}
// Format semantic results
let semanticResponse = `🔍 **Semantic Query**: "${args.semanticQuery}"\n`;
semanticResponse += `📊 **Found**: ${queryResults.length} matching clusters\n\n`;
queryResults.forEach((result, index) => {
const data = result.data as any;
semanticResponse += `**${index + 1}. ${data.clusterName}** (${data.projectId}/${data.region})\n`;
semanticResponse += ` 🎯 Confidence: ${(result.confidence * 100).toFixed(1)}%\n`;
semanticResponse += ` 📅 Last seen: ${data.lastSeen}\n`;
// Show machine types if available
if (data.configurations?.machineTypes?.length > 0) {
semanticResponse += ` 🖥️ Machine types: ${data.configurations.machineTypes.join(', ')}\n`;
}
// Show components if available
if (data.configurations?.components?.length > 0) {
semanticResponse += ` 🔧 Components: ${data.configurations.components.join(', ')}\n`;
}
// Show pip packages if available
if (data.configurations?.pipPackages?.length > 0) {
const packages = data.configurations.pipPackages.slice(0, 5);
semanticResponse += ` 📦 Pip packages: ${packages.join(', ')}${data.configurations.pipPackages.length > 5 ? '...' : ''}\n`;
}
semanticResponse += '\n';
});
return {
content: [
{
type: 'text',
text: semanticResponse,
},
],
};
} catch (semanticError) {
logger.warn('Semantic query failed, falling back to regular response:', semanticError);
// Continue with regular response below
}
}
// Regular response handling
if (deps.responseFilter && !args.verbose) {
try {
logger.debug('🔍 [DEBUG] Starting response filtering for list_clusters', {
verbose: args.verbose,
responseSize: JSON.stringify(response).length,
hasResponseFilter: !!deps.responseFilter,
});
const filteredResponse = await deps.responseFilter.filterResponse('list_clusters', response, {
toolName: 'list_clusters',
timestamp: new Date().toISOString(),
projectId,
region,
responseType: 'cluster_list',
originalTokenCount: JSON.stringify(response).length,
filteredTokenCount: 0,
compressionRatio: 1.0,
});
logger.debug('🔍 [DEBUG] Response filtering completed', {
filterType: filteredResponse.type,
tokensSaved: filteredResponse.tokensSaved,
contentLength: filteredResponse.content.length,
hasContent: !!filteredResponse.content,
hasSummary: !!filteredResponse.summary,
});
const formattedContent =
filteredResponse.type === 'summary'
? filteredResponse.summary || filteredResponse.content
: filteredResponse.content;
logger.debug('🔍 [DEBUG] Using formatted content', {
contentType: filteredResponse.type === 'summary' ? 'summary' : 'content',
finalContentLength: formattedContent.length,
contentPreview: formattedContent.substring(0, 200),
});
return {
content: [
{
type: 'text',
text: formattedContent,
},
],
};
} catch (filterError) {
logger.warn('Response filtering failed, returning raw response:', filterError);
logger.debug('🔍 [DEBUG] Filter error details', {
errorMessage: filterError instanceof Error ? filterError.message : String(filterError),
errorStack: filterError instanceof Error ? filterError.stack : undefined,
});
}
}
return {
content: [
{
type: 'text',
text: `Clusters in project ${projectId}, region ${region}:\n${JSON.stringify(SecurityMiddleware.sanitizeForLogging(response), null, 2)}`,
},
],
};
}
export async function handleGetCluster(args: any, deps: HandlerDependencies) {
// Apply security middleware
SecurityMiddleware.checkRateLimit(`get_cluster:${JSON.stringify(args)}`);
// Sanitize input
const sanitizedArgs = SecurityMiddleware.sanitizeObject(args);
// Validate input with Zod schema
let validatedArgs;
try {
validatedArgs = SecurityMiddleware.validateInput(GetClusterSchema, sanitizedArgs);
} catch (error) {
SecurityMiddleware.auditLog(
'Input validation failed',
{
tool: 'get_cluster',
error: error instanceof Error ? error.message : 'Unknown error',
args: SecurityMiddleware.sanitizeForLogging(args),
},
'warn'
);
throw new McpError(
ErrorCode.InvalidParams,
error instanceof Error ? error.message : 'Invalid input'
);
}
// Get default parameters if not provided
const { clusterName } = validatedArgs;
let { projectId, region } = validatedArgs;
if (!projectId && deps.defaultParamManager) {
try {
projectId = deps.defaultParamManager.getParameterValue('projectId');
} catch (error) {
// Ignore error, will be caught by validation below
}
}
if (!region && deps.defaultParamManager) {
try {
region = deps.defaultParamManager.getParameterValue('region');
} catch (error) {
// Ignore error, will be caught by validation below
}
}
// Validate required parameters after defaults
if (!projectId || !region || !clusterName) {
throw new McpError(
ErrorCode.InvalidParams,
'Missing required parameters: projectId, region, clusterName'
);
}
// Additional GCP constraint validation
SecurityMiddleware.validateGCPConstraints({ projectId, region, clusterName });
// Audit log the operation
SecurityMiddleware.auditLog('Cluster details requested', {
tool: 'get_cluster',
projectId,
region,
clusterName,
});
const response = await getCluster(String(projectId), String(region), String(clusterName));
// Index cluster configuration for knowledge base
if (deps.knowledgeIndexer && response) {
try {
await deps.knowledgeIndexer.indexClusterConfiguration(response as any);
} catch (indexError) {
logger.warn('Failed to index cluster configuration:', indexError);
}
}
// Handle semantic query using KnowledgeIndexer if available
if (args.semanticQuery && deps.knowledgeIndexer) {
try {
const queryResults = await deps.knowledgeIndexer.queryKnowledge(String(args.semanticQuery), {
type: 'cluster',
projectId: String(projectId),
region: String(region),
limit: 5,
});
if (queryResults.length === 0) {
// Fall back to regular formatted response with semantic query note
let fallbackText = `🔍 **Semantic Query**: "${args.semanticQuery}"\n❌ **No semantic results found for cluster ${clusterName}**\n\n`;
// Use the same response filtering logic as regular queries
if (deps.responseFilter && !args.verbose) {
try {
const filteredResponse = await deps.responseFilter.filterResponse(
'get_cluster',
response,
{
toolName: 'get_cluster',
timestamp: new Date().toISOString(),
projectId: String(projectId),
region: String(region),
clusterName: String(clusterName),
responseType: 'cluster_details',
originalTokenCount: JSON.stringify(response).length,
filteredTokenCount: 0,
compressionRatio: 1.0,
}
);
const formattedContent =
filteredResponse.type === 'summary'
? filteredResponse.summary || filteredResponse.content
: filteredResponse.content;
fallbackText += `📋 **Regular cluster details**:\n${formattedContent}`;
fallbackText += `\n\n💡 **Note**: Semantic search requires Qdrant vector database. To enable:\n`;
fallbackText += `- Start Qdrant: \`docker run -p 6334:6333 qdrant/qdrant\`\n`;
fallbackText += `- Or use regular cluster operations without semantic queries`;
} catch (filterError) {
logger.warn('Response filtering failed in semantic fallback:', filterError);
fallbackText += `📋 **Regular cluster details**:\n${JSON.stringify(response, null, 2)}`;
}
} else {
fallbackText += `📋 **Regular cluster details**:\n${JSON.stringify(response, null, 2)}`;
}
return {
content: [
{
type: 'text',
text: fallbackText,
},
],
};
}
// Format semantic results
let semanticResponse = `🔍 **Semantic Query**: "${args.semanticQuery}"\n`;
semanticResponse += `🎯 **Target Cluster**: ${clusterName} (${projectId}/${region})\n`;
semanticResponse += `📊 **Found**: ${queryResults.length} matching results\n\n`;
queryResults.forEach((result, index) => {
const data = result.data as any;
semanticResponse += `**${index + 1}. ${data.clusterName}** (${data.projectId}/${data.region})\n`;
semanticResponse += ` 🎯 Confidence: ${(result.confidence * 100).toFixed(1)}%\n`;
semanticResponse += ` 📅 Last seen: ${data.lastSeen}\n`;
// Show machine types if available
if (data.configurations?.machineTypes?.length > 0) {
semanticResponse += ` 🖥️ Machine types: ${data.configurations.machineTypes.join(', ')}\n`;
}
// Show components if available
if (data.configurations?.components?.length > 0) {
semanticResponse += ` 🔧 Components: ${data.configurations.components.join(', ')}\n`;
}
// Show pip packages if available
if (data.configurations?.pipPackages?.length > 0) {
const packages = data.configurations.pipPackages.slice(0, 5);
semanticResponse += ` 📦 Pip packages: ${packages.join(', ')}${data.configurations.pipPackages.length > 5 ? '...' : ''}\n`;
}
semanticResponse += '\n';
});
return {
content: [
{
type: 'text',
text: semanticResponse,
},
],
};
} catch (semanticError) {
logger.warn('Semantic query failed, falling back to regular response:', semanticError);
// Continue with regular response below
}
}
// Regular response handling
if (deps.responseFilter && !args.verbose) {
try {
const filteredResponse = await deps.responseFilter.filterResponse('get_cluster', response, {
toolName: 'get_cluster',
timestamp: new Date().toISOString(),
projectId: String(projectId),
region: String(region),
clusterName: String(clusterName),
responseType: 'cluster_details',
originalTokenCount: JSON.stringify(response).length,
filteredTokenCount: 0,
compressionRatio: 1.0,
});
const formattedContent =
filteredResponse.type === 'summary'
? filteredResponse.summary || filteredResponse.content
: filteredResponse.content;
return {
content: [
{
type: 'text',
text: formattedContent,
},
],
};
} catch (filterError) {
logger.warn('Response filtering failed, returning raw response:', filterError);
}
}
return {
content: [
{
type: 'text',
text: `Cluster ${clusterName} details:\n${JSON.stringify(response, null, 2)}`,
},
],
};
}
export async function handleDeleteCluster(args: any, deps: HandlerDependencies) {
// Apply security middleware
SecurityMiddleware.checkRateLimit(`delete_cluster:${JSON.stringify(args)}`);
// Sanitize input
const sanitizedArgs = SecurityMiddleware.sanitizeObject(args);
// Validate input with Zod schema
let validatedArgs;
try {
validatedArgs = SecurityMiddleware.validateInput(DeleteClusterSchema, sanitizedArgs);
} catch (error) {
SecurityMiddleware.auditLog(
'Input validation failed',
{
tool: 'delete_cluster',
error: error instanceof Error ? error.message : 'Unknown error',
args: SecurityMiddleware.sanitizeForLogging(args),
},
'warn'
);
throw new McpError(
ErrorCode.InvalidParams,
error instanceof Error ? error.message : 'Invalid input'
);
}
// Get default parameters if not provided
const { clusterName } = validatedArgs;
let { projectId, region } = validatedArgs;
if (!projectId && deps.defaultParamManager) {
try {
projectId = deps.defaultParamManager.getParameterValue('projectId');
} catch (error) {
// Ignore error, will be caught by validation below
}
}
if (!region && deps.defaultParamManager) {
try {
region = deps.defaultParamManager.getParameterValue('region');
} catch (error) {
// Ignore error, will be caught by validation below
}
}
// Validate required parameters after defaults
if (!projectId || !region) {
throw new McpError(ErrorCode.InvalidParams, 'Missing required parameters: projectId, region');
}
// Additional GCP constraint validation
SecurityMiddleware.validateGCPConstraints({ projectId, region, clusterName });
// Audit log the operation
SecurityMiddleware.auditLog('Cluster deletion initiated', {
tool: 'delete_cluster',
projectId,
region,
clusterName,
});
const response = await deleteCluster(projectId, region, clusterName);
SecurityMiddleware.auditLog('Cluster deletion completed', {
tool: 'delete_cluster',
projectId,
region,
clusterName,
success: true,
});
return {
content: [
{
type: 'text',
text: `Cluster ${clusterName} deletion initiated in region ${region}.\nDeletion details:\n${JSON.stringify(SecurityMiddleware.sanitizeForLogging(response), null, 2)}`,
},
],
};
}
/**
* Create cluster from YAML configuration file
*/
export async function handleCreateClusterFromYaml(args: any, deps: HandlerDependencies) {
// Apply security middleware
SecurityMiddleware.checkRateLimit(`create_cluster_from_yaml:${JSON.stringify(args)}`);
// Basic validation (sanitize only the input parameters, not the YAML data)
const typedArgs = args as any;
// Sanitize only the user-provided parameters
if (typedArgs.yamlPath && typeof typedArgs.yamlPath === 'string') {
typedArgs.yamlPath = SecurityMiddleware.sanitizeString(typedArgs.yamlPath);
}
if (!typedArgs.yamlPath || typeof typedArgs.yamlPath !== 'string') {
throw new McpError(ErrorCode.InvalidParams, 'yamlPath is required and must be a string');
}
const { yamlPath, overrides } = typedArgs;
try {
// Use the proper YAML processing function that handles both formats
const { getDataprocConfigFromYaml } = await import('../config/yaml.js');
const yamlResult = await getDataprocConfigFromYaml(yamlPath);
// Extract the properly processed configuration
const { clusterName } = yamlResult;
let clusterConfig = yamlResult.config;
// Apply overrides if provided
if (overrides && typeof overrides === 'object') {
clusterConfig = deepMerge(clusterConfig, overrides);
}
// Use existing cluster creation logic with properly extracted config
// This will now include tracking since we updated handleStartDataprocCluster
return handleStartDataprocCluster({ clusterName, clusterConfig }, deps);
} catch (error) {
logger.error('Failed to create cluster from YAML:', error);
throw new McpError(
ErrorCode.InternalError,
`Failed to create cluster from YAML: ${error instanceof Error ? error.message : 'Unknown error'}`
);
}
}
/**
* Create cluster from profile
*/
export async function handleCreateClusterFromProfile(args: any, deps: HandlerDependencies) {
// Apply security middleware
SecurityMiddleware.checkRateLimit(`create_cluster_from_profile:${JSON.stringify(args)}`);
// Basic validation (sanitize only the input parameters, not the profile data)
const typedArgs = args as any;
// Sanitize only the user-provided parameters
if (typedArgs.profileName && typeof typedArgs.profileName === 'string') {
typedArgs.profileName = SecurityMiddleware.sanitizeString(typedArgs.profileName);
}
if (typedArgs.clusterName && typeof typedArgs.clusterName === 'string') {
typedArgs.clusterName = SecurityMiddleware.sanitizeString(typedArgs.clusterName);
}
if (!typedArgs.profileName || typeof typedArgs.profileName !== 'string') {
throw new McpError(ErrorCode.InvalidParams, 'profileName is required and must be a string');
}
if (!typedArgs.clusterName || typeof typedArgs.clusterName !== 'string') {
throw new McpError(ErrorCode.InvalidParams, 'clusterName is required and must be a string');
}
const { profileName, clusterName, overrides } = typedArgs;
try {
// Load profile configuration
if (!deps.profileManager) {
throw new McpError(ErrorCode.InternalError, 'Profile manager not available');
}
const profile = await deps.profileManager.getProfile(profileName);
if (!profile) {
throw new McpError(ErrorCode.InvalidParams, `Profile not found: ${profileName}`);
}
// Get cluster config from profile
let clusterConfig = profile.clusterConfig || {};
// Apply overrides if provided
if (overrides && typeof overrides === 'object') {
clusterConfig = deepMerge(clusterConfig, overrides);
}
// Use existing cluster creation logic
return handleStartDataprocCluster({ clusterName, clusterConfig }, deps);
} catch (error) {
logger.error('Failed to create cluster from profile:', error);
throw new McpError(
ErrorCode.InternalError,
`Failed to create cluster from profile: ${error instanceof Error ? error.message : 'Unknown error'}`
);
}
}
/**
* Get all available HTTP endpoints for a cluster
*/
export async function handleGetClusterEndpoints(args: any, deps: HandlerDependencies) {
// Apply security middleware
SecurityMiddleware.checkRateLimit(`get_cluster_endpoints:${JSON.stringify(args)}`);
// Sanitize input
const sanitizedArgs = SecurityMiddleware.sanitizeObject(args);
// Basic validation
const typedArgs = sanitizedArgs as any;
if (!typedArgs.clusterName || typeof typedArgs.clusterName !== 'string') {
throw new McpError(ErrorCode.InvalidParams, 'clusterName is required and must be a string');
}
const { clusterName } = typedArgs;
try {
// Get default parameters if not provided
let projectId: string | undefined;
let region: string | undefined;
if (deps.defaultParamManager) {
try {
projectId = deps.defaultParamManager.getParameterValue('projectId') as string;
} catch (error) {
// Ignore error, will be caught by validation below
}
try {
region = deps.defaultParamManager.getParameterValue('region') as string;
} catch (error) {
// Ignore error, will be caught by validation below
}
}
// Validate required parameters after defaults
if (!projectId || !region) {
throw new McpError(ErrorCode.InvalidParams, 'Missing required parameters: projectId, region');
}
// Get cluster details to check if Zeppelin is enabled
const cluster = await getCluster(projectId, region, clusterName);
if (!cluster) {
throw new McpError(ErrorCode.InvalidParams, `Cluster not found: ${clusterName}`);
}
// Check if Zeppelin is enabled in the cluster configuration
const zeppelinEnabled = (cluster as any).config?.softwareConfig?.optionalComponents?.includes(
'ZEPPELIN'
);
if (!zeppelinEnabled) {
return {
content: [
{
type: 'text',
text: `Zeppelin is not enabled on cluster ${clusterName}. To enable Zeppelin, recreate the cluster with ZEPPELIN in the optional components.`,
},
],
};
}
// Extract all HTTP endpoints from cluster endpoint configuration
const httpPorts = (cluster as any).config?.endpointConfig?.httpPorts;
if (!httpPorts || Object.keys(httpPorts).length === 0) {
return {
content: [
{
type: 'text',
text: `No HTTP endpoints are available for cluster ${clusterName}. The cluster may still be starting up or endpoint access may not be enabled.`,
},
],
};
}
// Format all available endpoints nicely
const endpointsList = Object.entries(httpPorts)
.map(([service, url]) => `• ${service}: ${url}`)
.join('\n');
return {
content: [
{
type: 'text',
text: `Available HTTP endpoints for cluster ${clusterName}:\n\n${endpointsList}\n\nNote: These URLs are accessible from within the VPC or through appropriate firewall rules.`,
},
],
};
} catch (error) {
logger.error('Failed to get Zeppelin URL:', error);
throw new McpError(
ErrorCode.InternalError,
`Failed to get Zeppelin URL: ${error instanceof Error ? error.message : 'Unknown error'}`
);
}
}