forked from dipseth/dataproc-mcp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjob-handlers.ts
More file actions
983 lines (874 loc) Β· 29.3 KB
/
job-handlers.ts
File metadata and controls
983 lines (874 loc) Β· 29.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
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
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
/**
* Job 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 SecurityMiddleware from '../security/middleware.js';
import {
SubmitHiveQuerySchema,
GetJobStatusSchema,
GetQueryResultsSchema,
CancelDataprocJobSchema,
// SubmitDataprocJobSchema,
// GetJobResultsSchema,
CheckActiveJobsSchema,
} from '../validation/schemas.js';
import { submitHiveQuery, getJobStatus, getQueryResults } from '../services/query.js';
import { submitDataprocJob, cancelDataprocJob } from '../services/job.js';
import { DefaultParameterManager } from '../services/default-params.js';
import { ResponseFilter } from '../services/response-filter.js';
import { KnowledgeIndexer } from '../services/knowledge-indexer.js';
import { JobTracker } from '../services/job-tracker.js';
import { AsyncQueryPoller } from '../services/async-query-poller.js';
import { TemplatingIntegration } from '../services/templating-integration.js';
import { LocalFileStagingService } from '../services/local-file-staging.js';
export interface JobHandlerDependencies {
defaultParamManager?: DefaultParameterManager;
responseFilter?: ResponseFilter;
knowledgeIndexer?: KnowledgeIndexer;
jobTracker?: JobTracker;
asyncQueryPoller?: AsyncQueryPoller;
templatingIntegration?: TemplatingIntegration;
}
export async function handleSubmitHiveQuery(args: any, deps: JobHandlerDependencies) {
// Apply security middleware
SecurityMiddleware.checkRateLimit(`submit_hive_query:${JSON.stringify(args)}`);
// Sanitize input
const sanitizedArgs = SecurityMiddleware.sanitizeObject(args);
// Validate input with Zod schema
let validatedArgs;
try {
validatedArgs = SecurityMiddleware.validateInput(SubmitHiveQuerySchema, sanitizedArgs);
} catch (error) {
SecurityMiddleware.auditLog(
'Input validation failed',
{
tool: 'submit_hive_query',
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
let { projectId, region } = validatedArgs;
const { clusterName, query, async, queryOptions } = 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 || !query) {
throw new McpError(
ErrorCode.InvalidParams,
'Missing required parameters: projectId, region, clusterName, query'
);
}
// Additional GCP constraint validation
SecurityMiddleware.validateGCPConstraints({ projectId, region, clusterName });
// Audit log the operation
SecurityMiddleware.auditLog('Hive query submission initiated', {
tool: 'submit_hive_query',
projectId,
region,
clusterName,
queryLength: query.length,
async: !!async,
});
logger.debug(
'MCP submit_hive_query: Called with validated params:',
SecurityMiddleware.sanitizeForLogging({
projectId,
region,
clusterName,
query: query.substring(0, 100) + '...',
async,
queryOptions,
})
);
let response;
try {
response = await submitHiveQuery(projectId, region, clusterName, query, async, queryOptions);
SecurityMiddleware.auditLog('Hive query submission completed', {
tool: 'submit_hive_query',
projectId,
region,
clusterName,
jobId: response?.reference?.jobId,
success: true,
});
logger.debug(
'MCP submit_hive_query: submitHiveQuery response:',
SecurityMiddleware.sanitizeForLogging(response)
);
} catch (error) {
SecurityMiddleware.auditLog(
'Hive query submission failed',
{
tool: 'submit_hive_query',
projectId,
region,
clusterName,
error: error instanceof Error ? error.message : 'Unknown error',
},
'error'
);
logger.error('MCP submit_hive_query: Error from submitHiveQuery:', error);
throw error;
}
// Index query for knowledge base
if (deps.knowledgeIndexer && response?.reference?.jobId) {
try {
await deps.knowledgeIndexer.indexJobSubmission({
jobId: response.reference.jobId,
jobType: 'hive',
projectId,
region,
clusterName,
query,
status: 'SUBMITTED',
submissionTime: new Date().toISOString(),
});
} catch (indexError) {
logger.warn('Failed to index query submission:', indexError);
}
}
// Track job if async and tracker available
if (async && deps.jobTracker && response?.reference?.jobId) {
try {
deps.jobTracker.addOrUpdateJob({
jobId: response.reference.jobId,
projectId,
region,
clusterName,
toolName: 'submit_hive_query',
status: 'SUBMITTED',
submissionTime: new Date().toISOString(),
});
} catch (trackError) {
logger.warn('Failed to track async job:', trackError);
}
}
const jobId = response?.reference?.jobId;
let responseText: string;
if (async) {
responseText =
`Hive query submitted asynchronously. Job ID: ${jobId}\n\n` +
`π **NEXT STEPS:**\n` +
`1. Check status: get_job_status("${jobId}")\n` +
`2. When DONE, get results: query_knowledge("jobId:${jobId} contentType:query_results")\n\n` +
`π‘ **PRO TIP:** The query_knowledge approach gets actual data, not just metadata!`;
} else {
responseText =
`Hive query completed successfully.\n\n` +
`π― **GET ACTUAL RESULTS:**\n` +
`query_knowledge("jobId:${jobId} contentType:query_results")\n\n` +
`π **Raw Response:**\n${JSON.stringify(SecurityMiddleware.sanitizeForLogging(response), null, 2)}`;
}
return {
content: [
{
type: 'text',
text: responseText,
},
],
};
}
export async function handleGetQueryStatus(args: any, deps: JobHandlerDependencies) {
// Apply security middleware
SecurityMiddleware.checkRateLimit(`get_query_status:${JSON.stringify(args)}`);
// Sanitize input
const sanitizedArgs = SecurityMiddleware.sanitizeObject(args);
// Validate input with Zod schema
let validatedArgs;
try {
validatedArgs = SecurityMiddleware.validateInput(GetJobStatusSchema, sanitizedArgs);
} catch (error) {
SecurityMiddleware.auditLog(
'Input validation failed',
{
tool: 'get_query_status',
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
let { projectId, region } = validatedArgs;
const { jobId } = 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 || !jobId) {
throw new McpError(
ErrorCode.InvalidParams,
'Missing required parameters: projectId, region, jobId'
);
}
// Additional GCP constraint validation
SecurityMiddleware.validateGCPConstraints({ projectId, region });
// Audit log the operation
SecurityMiddleware.auditLog('Query status check initiated', {
tool: 'get_query_status',
projectId,
region,
jobId,
});
const response = await getJobStatus(projectId, region, jobId);
SecurityMiddleware.auditLog('Query status check completed', {
tool: 'get_query_status',
projectId,
region,
jobId,
status: response?.status?.state,
});
// Add result discovery hints when job is complete
let statusText = `Job ${jobId} status:\n${JSON.stringify(SecurityMiddleware.sanitizeForLogging(response), null, 2)}`;
if (response?.status?.state === 'DONE') {
statusText +=
`\n\nπ― **GET ACTUAL RESULTS:**\n` +
`Use: query_knowledge("jobId:${jobId} contentType:query_results")\n` +
`π‘ This will return the actual query output data (not just metadata)\n\n` +
`**Alternative patterns:**\n` +
`β’ jobId:${jobId} type:query_result - Alternative format\n` +
`β’ jobId:${jobId} includeRawDocument:true - Complete data access`;
}
return {
content: [
{
type: 'text',
text: statusText,
},
],
};
}
export async function handleGetQueryResults(args: any, deps: JobHandlerDependencies) {
// Apply security middleware
SecurityMiddleware.checkRateLimit(`get_query_results:${JSON.stringify(args)}`);
// Sanitize input
const sanitizedArgs = SecurityMiddleware.sanitizeObject(args);
// Validate input with Zod schema
let validatedArgs;
try {
validatedArgs = SecurityMiddleware.validateInput(GetQueryResultsSchema, sanitizedArgs);
} catch (error) {
SecurityMiddleware.auditLog(
'Input validation failed',
{
tool: 'get_query_results',
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
let { projectId, region } = validatedArgs;
const { jobId, maxResults, pageToken } = 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 || !jobId) {
throw new McpError(
ErrorCode.InvalidParams,
'Missing required parameters: projectId, region, jobId'
);
}
// Additional GCP constraint validation
SecurityMiddleware.validateGCPConstraints({ projectId, region });
// Audit log the operation
SecurityMiddleware.auditLog('Query results retrieval initiated', {
tool: 'get_query_results',
projectId,
region,
jobId,
maxResults,
});
const response = await getQueryResults(projectId, region, jobId, maxResults, pageToken);
SecurityMiddleware.auditLog('Query results retrieval completed', {
tool: 'get_query_results',
projectId,
region,
jobId,
resultCount: response?.rows?.length || 0,
});
// Index query results for knowledge base
if (deps.knowledgeIndexer && response) {
try {
await deps.knowledgeIndexer.indexJobSubmission({
jobId,
jobType: 'hive',
projectId,
region,
clusterName: 'unknown',
status: 'COMPLETED',
results: response,
});
} catch (indexError) {
logger.warn('Failed to index query results:', indexError);
}
}
// Handle response filtering
if (deps.responseFilter && !args.verbose) {
try {
const filteredResponse = await deps.responseFilter.filterResponse(
'get_query_results',
response,
{
toolName: 'get_query_results',
timestamp: new Date().toISOString(),
projectId,
region,
responseType: 'query_results',
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: `Query results for job ${jobId}:\n${JSON.stringify(SecurityMiddleware.sanitizeForLogging(response), null, 2)}`,
},
],
};
}
export async function handleCheckActiveJobs(args: any, deps: JobHandlerDependencies) {
// Apply security middleware
SecurityMiddleware.checkRateLimit(`check_active_jobs:${JSON.stringify(args)}`);
// Sanitize input
const sanitizedArgs = SecurityMiddleware.sanitizeObject(args);
// Validate input with Zod schema
let validatedArgs;
try {
validatedArgs = SecurityMiddleware.validateInput(CheckActiveJobsSchema, sanitizedArgs);
} catch (error) {
SecurityMiddleware.auditLog(
'Input validation failed',
{
tool: 'check_active_jobs',
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'
);
}
const { projectId, region, includeCompleted } = validatedArgs;
// Audit log the operation
SecurityMiddleware.auditLog('Active jobs check initiated', {
tool: 'check_active_jobs',
projectId,
region,
includeCompleted,
});
// Use job tracker if available
if (deps.jobTracker) {
try {
let activeJobs = deps.jobTracker.listJobs();
// Filter by project and region if specified
if (projectId || region) {
activeJobs = activeJobs.filter(
(job) => (!projectId || job.projectId === projectId) && (!region || job.region === region)
);
}
// Filter by status
if (!includeCompleted) {
activeJobs = activeJobs.filter(
(job) => !['COMPLETED', 'DONE', 'FAILED', 'CANCELLED', 'ERROR'].includes(job.status)
);
}
SecurityMiddleware.auditLog('Active jobs check completed', {
tool: 'check_active_jobs',
projectId,
region,
jobCount: activeJobs.length,
});
return {
content: [
{
type: 'text',
text: `π **Active Jobs Summary**\n\n${activeJobs.length === 0 ? 'β
No active jobs found' : activeJobs.map((job, index) => `**${index + 1}. Job ${job.jobId}**\n Status: ${job.status}\n Cluster: ${job.clusterName || 'unknown'}\n Started: ${job.submissionTime}`).join('\n\n')}`,
},
],
};
} catch (error) {
logger.warn('Job tracker failed, falling back to basic response:', error);
}
}
return {
content: [
{
type: 'text',
text: 'π **Active Jobs Check**\n\nβ οΈ Job tracking service not available. Use individual job status tools to check specific jobs.',
},
],
};
}
// Additional job handlers would go here (submitDataprocJob, getJobResults, etc.)
// For brevity, I'm showing the main patterns. The remaining handlers follow similar patterns.
/**
* Submit a generic Dataproc job
*/
export async function handleSubmitDataprocJob(args: any, deps: JobHandlerDependencies) {
// Apply security middleware
SecurityMiddleware.checkRateLimit(`submit_dataproc_job:${JSON.stringify(args)}`);
// Sanitize input
const sanitizedArgs = SecurityMiddleware.sanitizeObject(args);
const typedArgs = sanitizedArgs as any;
// Basic validation
if (!typedArgs.clusterName || typeof typedArgs.clusterName !== 'string') {
throw new McpError(ErrorCode.InvalidParams, 'clusterName is required and must be a string');
}
if (!typedArgs.jobType || typeof typedArgs.jobType !== 'string') {
throw new McpError(ErrorCode.InvalidParams, 'jobType is required and must be a string');
}
if (!typedArgs.jobConfig || typeof typedArgs.jobConfig !== 'object') {
throw new McpError(ErrorCode.InvalidParams, 'jobConfig is required and must be an object');
}
const { clusterName, jobType, jobConfig, async } = typedArgs;
// Get default parameters if not provided
let { projectId, region } = typedArgs;
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('Dataproc job submission initiated', {
tool: 'submit_dataproc_job',
projectId,
region,
clusterName,
jobType,
async: !!async,
});
try {
// For Hive jobs, delegate to the specialized Hive handler
if (jobType.toLowerCase() === 'hive') {
const hiveQuery = jobConfig.query || jobConfig.queryList?.queries?.[0];
if (hiveQuery) {
return handleSubmitHiveQuery({ clusterName, query: hiveQuery, async }, deps);
}
}
// Check for local files and stage if needed
const stagingService = new LocalFileStagingService(deps.defaultParamManager);
const localFiles = stagingService.detectLocalFiles(jobConfig);
let processedJobConfig = jobConfig;
if (localFiles.length > 0) {
logger.debug(
`handleSubmitDataprocJob: Found ${localFiles.length} local files to stage: ${localFiles.join(', ')}`
);
try {
const fileMapping = await stagingService.stageFiles(localFiles, clusterName);
processedJobConfig = stagingService.transformJobConfig(jobConfig, fileMapping);
logger.debug(
`handleSubmitDataprocJob: Successfully staged files and transformed job config`
);
// Log the transformation for debugging
SecurityMiddleware.auditLog('Local files staged for job', {
tool: 'submit_dataproc_job',
projectId,
region,
clusterName,
jobType,
localFiles: localFiles.length,
stagedFiles: Array.from(fileMapping.values()),
});
} catch (stagingError) {
logger.error(`handleSubmitDataprocJob: Failed to stage local files:`, stagingError);
throw new McpError(
ErrorCode.InternalError,
`Failed to stage local files: ${stagingError instanceof Error ? stagingError.message : 'Unknown error'}`
);
}
}
// For all other job types (including PySpark), use the generic job service
const response = await submitDataprocJob({
projectId,
region,
clusterName,
jobType,
jobConfig: processedJobConfig,
async,
});
SecurityMiddleware.auditLog('Dataproc job submission completed', {
tool: 'submit_dataproc_job',
projectId,
region,
clusterName,
jobType,
jobId: response?.jobId,
success: true,
});
// Index job for knowledge base
if (deps.knowledgeIndexer && response?.jobId) {
try {
await deps.knowledgeIndexer.indexJobSubmission({
jobId: response.jobId,
jobType: jobType as any,
projectId,
region,
clusterName,
status: 'SUBMITTED',
submissionTime: new Date().toISOString(),
});
} catch (indexError) {
logger.warn('Failed to index job submission:', indexError);
}
}
// Track job if async and tracker available
if (async && deps.jobTracker && response?.jobId) {
try {
deps.jobTracker.addOrUpdateJob({
jobId: response.jobId,
projectId,
region,
clusterName,
toolName: 'submit_dataproc_job',
status: 'SUBMITTED',
submissionTime: new Date().toISOString(),
});
} catch (trackError) {
logger.warn('Failed to track async job:', trackError);
}
}
const jobId = response?.jobId;
let responseText: string;
if (async) {
responseText =
`${jobType} job submitted asynchronously. Job ID: ${jobId}\n\n` +
`π **MONITORING & RESULTS:**\n` +
`1. Check status: get_job_status("${jobId}")\n` +
`2. When DONE, get results: query_knowledge("jobId:${jobId} contentType:query_results")\n\n` +
`π **SEARCH PATTERNS:**\n` +
`β’ jobId:${jobId} type:job - Job metadata\n` +
`β’ jobId:${jobId} contentType:query_results - Actual output data\n` +
`β’ clusterName:${clusterName} ${jobType} - Related jobs on cluster`;
} else {
responseText =
`${jobType} job completed successfully.\n\n` +
`π― **GET ACTUAL RESULTS:**\n` +
`query_knowledge("jobId:${jobId} contentType:query_results")\n\n` +
`π **Job Details:**\n` +
`Job ID: ${jobId}\n` +
`Status: ${response?.status}\n` +
`Type: ${jobType}\n` +
`Cluster: ${clusterName}`;
}
return {
content: [
{
type: 'text',
text: responseText,
},
],
};
} catch (error) {
SecurityMiddleware.auditLog(
'Dataproc job submission failed',
{
tool: 'submit_dataproc_job',
projectId,
region,
clusterName,
jobType,
error: error instanceof Error ? error.message : 'Unknown error',
},
'error'
);
logger.error('Failed to submit Dataproc job:', error);
throw new McpError(
ErrorCode.InternalError,
`Failed to submit Dataproc job: ${error instanceof Error ? error.message : 'Unknown error'}`
);
}
}
/**
* Get job status (enhanced version of get_query_status)
*/
export async function handleGetJobStatus(args: any, deps: JobHandlerDependencies) {
// For now, delegate to the existing query status handler
return handleGetQueryStatus(args, deps);
}
/**
* Get job results (enhanced version of get_query_results)
*/
export async function handleGetJobResults(args: any, deps: JobHandlerDependencies) {
// For now, delegate to the existing query results handler
return handleGetQueryResults(args, deps);
}
/**
* Cancel a Dataproc job
*/
export async function handleCancelDataprocJob(args: any, deps: JobHandlerDependencies) {
// Apply security middleware
SecurityMiddleware.checkRateLimit(`cancel_dataproc_job:${JSON.stringify(args)}`);
// Sanitize input
const sanitizedArgs = SecurityMiddleware.sanitizeObject(args);
// Validate input with Zod schema
let validatedArgs;
try {
validatedArgs = SecurityMiddleware.validateInput(CancelDataprocJobSchema, sanitizedArgs);
} catch (error) {
SecurityMiddleware.auditLog(
'Input validation failed',
{
tool: 'cancel_dataproc_job',
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
let { projectId, region } = validatedArgs;
const { jobId, verbose } = 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 || !jobId) {
throw new McpError(
ErrorCode.InvalidParams,
'Missing required parameters: projectId, region, jobId'
);
}
// Additional GCP constraint validation
SecurityMiddleware.validateGCPConstraints({ projectId, region });
// Audit log the operation
SecurityMiddleware.auditLog('Dataproc job cancellation initiated', {
tool: 'cancel_dataproc_job',
projectId,
region,
jobId,
});
try {
const cancellationResult = await cancelDataprocJob({ projectId, region, jobId });
if (cancellationResult.success) {
// Update JobTracker if available
if (
deps.jobTracker &&
(cancellationResult.status === 'PENDING' || cancellationResult.status === 'RUNNING')
) {
try {
deps.jobTracker.addOrUpdateJob({
jobId,
projectId,
region,
status: 'CANCELLING',
toolName: 'cancel_dataproc_job',
submissionTime: new Date().toISOString(),
});
} catch (trackError) {
logger.warn('Failed to update job tracker:', trackError);
}
}
// Index in Knowledge Base if available
if (deps.knowledgeIndexer) {
try {
await deps.knowledgeIndexer.indexJobSubmission({
jobId,
jobType: 'cancel',
projectId,
region,
clusterName: 'unknown',
status: 'CANCELLATION_REQUESTED',
submissionTime: new Date().toISOString(),
results: cancellationResult.jobDetails,
});
} catch (indexError) {
logger.warn('Failed to index cancellation event:', indexError);
}
}
SecurityMiddleware.auditLog('Dataproc job cancellation completed', {
tool: 'cancel_dataproc_job',
projectId,
region,
jobId,
status: cancellationResult.status,
success: true,
});
let responseText = '';
// Handle different status scenarios
if (cancellationResult.status === 'PENDING' || cancellationResult.status === 'RUNNING') {
responseText =
`π **Job Cancellation Initiated**\n\n` +
`Job ID: ${jobId}\n` +
`Status: Cancellation requested\n` +
`Message: ${cancellationResult.message}\n\n` +
`π **NEXT STEPS:**\n` +
`1. Monitor status: get_job_status("${jobId}")\n` +
`2. Expected final status: CANCELLED\n\n` +
`π‘ **TIP:** Cancellation may take a few moments to complete.`;
} else if (
cancellationResult.status === 'DONE' ||
cancellationResult.status === 'ERROR' ||
cancellationResult.status === 'CANCELLED'
) {
responseText =
`βΉοΈ **Job Already Completed**\n\n` +
`Job ID: ${jobId}\n` +
`Current Status: ${cancellationResult.status}\n` +
`Message: ${cancellationResult.message}\n\n` +
`π― **GET RESULTS:**\n` +
`query_knowledge("jobId:${jobId} contentType:query_results")`;
} else {
responseText =
`π **Job Cancellation Status**\n\n` +
`Job ID: ${jobId}\n` +
`Status: ${cancellationResult.status}\n` +
`Message: ${cancellationResult.message}`;
}
if (verbose && cancellationResult.jobDetails) {
responseText += `\n\nπ **Raw Response:**\n${JSON.stringify(SecurityMiddleware.sanitizeForLogging(cancellationResult.jobDetails), null, 2)}`;
}
return {
content: [{ type: 'text', text: responseText }],
};
} else {
// Handle failure cases (e.g., job not found)
SecurityMiddleware.auditLog(
'Dataproc job cancellation failed',
{
tool: 'cancel_dataproc_job',
projectId,
region,
jobId,
error: cancellationResult.message,
},
'error'
);
const errorText =
`β **Job Not Found**\n\n` +
`Job ID: ${jobId}\n` +
`Status: ${cancellationResult.status}\n` +
`Message: ${cancellationResult.message}\n\n` +
`π‘ **TROUBLESHOOTING:**\n` +
`β’ Verify the job ID is correct\n` +
`β’ Check that you're using the right project and region\n` +
`β’ Ensure you have Dataproc Job Admin permissions`;
return {
content: [{ type: 'text', text: errorText }],
};
}
} catch (error) {
SecurityMiddleware.auditLog(
'Dataproc job cancellation failed',
{
tool: 'cancel_dataproc_job',
projectId,
region,
jobId,
error: error instanceof Error ? error.message : 'Unknown error',
},
'error'
);
logger.error('Failed to cancel Dataproc job:', error);
throw new McpError(
ErrorCode.InternalError,
`Failed to cancel Dataproc job: ${error instanceof Error ? error.message : 'Unknown error'}`
);
}
}