-
Notifications
You must be signed in to change notification settings - Fork 1.7k
3683 lines (3620 loc) · 173 KB
/
Copy pathpr-fix.lock.yml
File metadata and controls
3683 lines (3620 loc) · 173 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
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# This file was automatically generated by gh-aw. DO NOT EDIT.
# To update this file, edit the corresponding .md file and run:
# gh aw compile
#
# Effective stop-time: 2025-09-21 02:31:54
name: "PR Fix"
on:
issues:
types: [opened, edited, reopened]
issue_comment:
types: [created, edited]
pull_request:
types: [opened, edited, reopened]
pull_request_review_comment:
types: [created, edited]
permissions: {}
concurrency:
group: "gh-aw-${{ github.workflow }}-${{ github.event.issue.number || github.event.pull_request.number }}"
run-name: "PR Fix"
jobs:
task:
if: >
((contains(github.event.issue.body, '/pr-fix')) || (contains(github.event.comment.body, '/pr-fix'))) ||
(contains(github.event.pull_request.body, '/pr-fix'))
runs-on: ubuntu-latest
permissions:
actions: write # Required for github.rest.actions.cancelWorkflowRun()
outputs:
text: ${{ steps.compute-text.outputs.text }}
steps:
- name: Check team membership for command workflow
id: check-team-member
uses: actions/github-script@v8
env:
GITHUB_AW_REQUIRED_ROLES: admin,maintainer,write
with:
script: |
async function setCancelled(message) {
try {
await github.rest.actions.cancelWorkflowRun({
owner: context.repo.owner,
repo: context.repo.repo,
run_id: context.runId,
});
core.info(`Cancellation requested for this workflow run: ${message}`);
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
core.warning(`Failed to cancel workflow run: ${errorMessage}`);
core.setFailed(message); // Fallback if API call fails
}
}
async function main() {
const { eventName } = context;
// skip check for safe events
const safeEvents = ["workflow_dispatch", "workflow_run", "schedule"];
if (safeEvents.includes(eventName)) {
core.info(`✅ Event ${eventName} does not require validation`);
return;
}
const actor = context.actor;
const { owner, repo } = context.repo;
const requiredPermissionsEnv = process.env.GITHUB_AW_REQUIRED_ROLES;
const requiredPermissions = requiredPermissionsEnv
? requiredPermissionsEnv.split(",").filter(p => p.trim() !== "")
: [];
if (!requiredPermissions || requiredPermissions.length === 0) {
core.error(
"❌ Configuration error: Required permissions not specified. Contact repository administrator."
);
await setCancelled(
"Configuration error: Required permissions not specified"
);
return;
}
// Check if the actor has the required repository permissions
try {
core.debug(
`Checking if user '${actor}' has required permissions for ${owner}/${repo}`
);
core.debug(`Required permissions: ${requiredPermissions.join(", ")}`);
const repoPermission =
await github.rest.repos.getCollaboratorPermissionLevel({
owner: owner,
repo: repo,
username: actor,
});
const permission = repoPermission.data.permission;
core.debug(`Repository permission level: ${permission}`);
// Check if user has one of the required permission levels
for (const requiredPerm of requiredPermissions) {
if (
permission === requiredPerm ||
(requiredPerm === "maintainer" && permission === "maintain")
) {
core.info(`✅ User has ${permission} access to repository`);
return;
}
}
core.warning(
`User permission '${permission}' does not meet requirements: ${requiredPermissions.join(", ")}`
);
} catch (repoError) {
const errorMessage =
repoError instanceof Error ? repoError.message : String(repoError);
core.error(`Repository permission check failed: ${errorMessage}`);
await setCancelled(`Repository permission check failed: ${errorMessage}`);
return;
}
// Cancel the workflow when permission check fails
core.warning(
`❌ Access denied: Only authorized users can trigger this workflow. User '${actor}' is not authorized. Required permissions: ${requiredPermissions.join(", ")}`
);
await setCancelled(
`Access denied: User '${actor}' is not authorized. Required permissions: ${requiredPermissions.join(", ")}`
);
}
await main();
- name: Compute current body text
id: compute-text
uses: actions/github-script@v8
with:
script: |
/**
* Sanitizes content for safe output in GitHub Actions
* @param {string} content - The content to sanitize
* @returns {string} The sanitized content
*/
function sanitizeContent(content) {
if (!content || typeof content !== "string") {
return "";
}
// Read allowed domains from environment variable
const allowedDomainsEnv = process.env.GITHUB_AW_ALLOWED_DOMAINS;
const defaultAllowedDomains = [
"github.com",
"github.io",
"githubusercontent.com",
"githubassets.com",
"github.dev",
"codespaces.new",
];
const allowedDomains = allowedDomainsEnv
? allowedDomainsEnv
.split(",")
.map(d => d.trim())
.filter(d => d)
: defaultAllowedDomains;
let sanitized = content;
// Neutralize @mentions to prevent unintended notifications
sanitized = neutralizeMentions(sanitized);
// Remove control characters (except newlines and tabs)
sanitized = sanitized.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, "");
// XML tag neutralization - convert XML tags to parentheses format
sanitized = convertXmlTagsToParentheses(sanitized);
// URI filtering - replace non-https protocols with "(redacted)"
// Step 1: Temporarily mark HTTPS URLs to protect them
sanitized = sanitizeUrlProtocols(sanitized);
// Domain filtering for HTTPS URIs
// Match https:// URIs and check if domain is in allowlist
sanitized = sanitizeUrlDomains(sanitized);
// Limit total length to prevent DoS (0.5MB max)
const maxLength = 524288;
if (sanitized.length > maxLength) {
sanitized =
sanitized.substring(0, maxLength) + "\n[Content truncated due to length]";
}
// Limit number of lines to prevent log flooding (65k max)
const lines = sanitized.split("\n");
const maxLines = 65000;
if (lines.length > maxLines) {
sanitized =
lines.slice(0, maxLines).join("\n") +
"\n[Content truncated due to line count]";
}
// Remove ANSI escape sequences
sanitized = sanitized.replace(/\x1b\[[0-9;]*[mGKH]/g, "");
// Neutralize common bot trigger phrases
sanitized = neutralizeBotTriggers(sanitized);
// Trim excessive whitespace
return sanitized.trim();
/**
* Convert XML tags to parentheses format while preserving non-XML uses of < and >
* @param {string} s - The string to process
* @returns {string} The string with XML tags converted to parentheses
*/
function convertXmlTagsToParentheses(s) {
if (!s || typeof s !== "string") {
return s;
}
// XML tag patterns that should be converted to parentheses
return (
s
// Standard XML tags: <tag>, <tag attr="value">, <tag/>, </tag>
.replace(/<\/?[a-zA-Z][a-zA-Z0-9\-_:]*(?:\s[^>]*|\/)?>/g, match => {
// Extract the tag name and content without < >
const innerContent = match.slice(1, -1);
return `(${innerContent})`;
})
// XML comments: <!-- comment -->
.replace(/<!--[\s\S]*?-->/g, match => {
const innerContent = match.slice(4, -3); // Remove <!-- and -->
return `(!--${innerContent}--)`;
})
// CDATA sections: <![CDATA[content]]>
.replace(/<!\[CDATA\[[\s\S]*?\]\]>/g, match => {
const innerContent = match.slice(9, -3); // Remove <![CDATA[ and ]]>
return `(![CDATA[${innerContent}]])`;
})
// XML processing instructions: <?xml ... ?>
.replace(/<\?[\s\S]*?\?>/g, match => {
const innerContent = match.slice(2, -2); // Remove <? and ?>
return `(?${innerContent}?)`;
})
// DOCTYPE declarations: <!DOCTYPE ...>
.replace(/<!DOCTYPE[^>]*>/gi, match => {
const innerContent = match.slice(9, -1); // Remove <!DOCTYPE and >
return `(!DOCTYPE${innerContent})`;
})
);
}
/**
* Remove unknown domains
* @param {string} s - The string to process
* @returns {string} The string with unknown domains redacted
*/
function sanitizeUrlDomains(s) {
s = s.replace(
/\bhttps:\/\/([^\/\s\])}'"<>&\x00-\x1f]+)/gi,
(match, domain) => {
// Extract the hostname part (before first slash, colon, or other delimiter)
const hostname = domain.split(/[\/:\?#]/)[0].toLowerCase();
// Check if this domain or any parent domain is in the allowlist
const isAllowed = allowedDomains.some(allowedDomain => {
const normalizedAllowed = allowedDomain.toLowerCase();
return (
hostname === normalizedAllowed ||
hostname.endsWith("." + normalizedAllowed)
);
});
return isAllowed ? match : "(redacted)";
}
);
return s;
}
/**
* Remove unknown protocols except https
* @param {string} s - The string to process
* @returns {string} The string with non-https protocols redacted
*/
function sanitizeUrlProtocols(s) {
// Match both protocol:// and protocol: patterns
// This covers URLs like https://example.com, javascript:alert(), mailto:user@domain.com, etc.
return s.replace(
/\b(\w+):(?:\/\/)?[^\s\])}'"<>&\x00-\x1f]+/gi,
(match, protocol) => {
// Allow https (case insensitive), redact everything else
return protocol.toLowerCase() === "https" ? match : "(redacted)";
}
);
}
/**
* Neutralizes @mentions by wrapping them in backticks
* @param {string} s - The string to process
* @returns {string} The string with neutralized mentions
*/
function neutralizeMentions(s) {
// Replace @name or @org/team outside code with `@name`
return s.replace(
/(^|[^\w`])@([A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?(?:\/[A-Za-z0-9._-]+)?)/g,
(_m, p1, p2) => `${p1}\`@${p2}\``
);
}
/**
* Neutralizes bot trigger phrases by wrapping them in backticks
* @param {string} s - The string to process
* @returns {string} The string with neutralized bot triggers
*/
function neutralizeBotTriggers(s) {
// Neutralize common bot trigger phrases like "fixes #123", "closes #asdfs", etc.
return s.replace(
/\b(fixes?|closes?|resolves?|fix|close|resolve)\s+#(\w+)/gi,
(match, action, ref) => `\`${action} #${ref}\``
);
}
}
async function main() {
let text = "";
const actor = context.actor;
const { owner, repo } = context.repo;
// Check if the actor has repository access (admin, maintain permissions)
const repoPermission = await github.rest.repos.getCollaboratorPermissionLevel(
{
owner: owner,
repo: repo,
username: actor,
}
);
const permission = repoPermission.data.permission;
core.debug(`Repository permission level: ${permission}`);
if (permission !== "admin" && permission !== "maintain") {
core.setOutput("text", "");
return;
}
// Determine current body text based on event context
switch (context.eventName) {
case "issues":
// For issues: title + body
if (context.payload.issue) {
const title = context.payload.issue.title || "";
const body = context.payload.issue.body || "";
text = `${title}\n\n${body}`;
}
break;
case "pull_request":
// For pull requests: title + body
if (context.payload.pull_request) {
const title = context.payload.pull_request.title || "";
const body = context.payload.pull_request.body || "";
text = `${title}\n\n${body}`;
}
break;
case "pull_request_target":
// For pull request target events: title + body
if (context.payload.pull_request) {
const title = context.payload.pull_request.title || "";
const body = context.payload.pull_request.body || "";
text = `${title}\n\n${body}`;
}
break;
case "issue_comment":
// For issue comments: comment body
if (context.payload.comment) {
text = context.payload.comment.body || "";
}
break;
case "pull_request_review_comment":
// For PR review comments: comment body
if (context.payload.comment) {
text = context.payload.comment.body || "";
}
break;
case "pull_request_review":
// For PR reviews: review body
if (context.payload.review) {
text = context.payload.review.body || "";
}
break;
default:
// Default: empty text
text = "";
break;
}
// Sanitize the text before output
const sanitizedText = sanitizeContent(text);
// Display sanitized text in logs
core.debug(`text: ${sanitizedText}`);
// Set the sanitized text as output
core.setOutput("text", sanitizedText);
}
await main();
add_reaction:
needs: task
if: >
github.event_name == 'issues' || github.event_name == 'issue_comment' || github.event_name == 'pull_request_comment' ||
github.event_name == 'pull_request_review_comment' || (github.event_name == 'pull_request') &&
(github.event.pull_request.head.repo.full_name == github.repository)
runs-on: ubuntu-latest
permissions:
actions: write # Required for github.rest.actions.cancelWorkflowRun()
issues: write
pull-requests: write
contents: read
outputs:
reaction_id: ${{ steps.react.outputs.reaction-id }}
steps:
- name: Add eyes reaction to the triggering item
id: react
uses: actions/github-script@v8
env:
GITHUB_AW_REACTION: eyes
GITHUB_AW_COMMAND: pr-fix
with:
script: |
async function main() {
// Read inputs from environment variables
const reaction = process.env.GITHUB_AW_REACTION || "eyes";
const command = process.env.GITHUB_AW_COMMAND; // Only present for command workflows
const runId = context.runId;
const runUrl = context.payload.repository
? `${context.payload.repository.html_url}/actions/runs/${runId}`
: `https://github.com/${context.repo.owner}/${context.repo.repo}/actions/runs/${runId}`;
core.info(`Reaction type: ${reaction}`);
core.info(`Command name: ${command || "none"}`);
core.info(`Run ID: ${runId}`);
core.info(`Run URL: ${runUrl}`);
// Validate reaction type
const validReactions = [
"+1",
"-1",
"laugh",
"confused",
"heart",
"hooray",
"rocket",
"eyes",
];
if (!validReactions.includes(reaction)) {
core.setFailed(
`Invalid reaction type: ${reaction}. Valid reactions are: ${validReactions.join(", ")}`
);
return;
}
// Determine the API endpoint based on the event type
let reactionEndpoint;
let commentUpdateEndpoint;
let shouldEditComment = false;
const eventName = context.eventName;
const owner = context.repo.owner;
const repo = context.repo.repo;
try {
switch (eventName) {
case "issues":
const issueNumber = context.payload?.issue?.number;
if (!issueNumber) {
core.setFailed("Issue number not found in event payload");
return;
}
reactionEndpoint = `/repos/${owner}/${repo}/issues/${issueNumber}/reactions`;
// Don't edit issue bodies for now - this might be more complex
shouldEditComment = false;
break;
case "issue_comment":
const commentId = context.payload?.comment?.id;
if (!commentId) {
core.setFailed("Comment ID not found in event payload");
return;
}
reactionEndpoint = `/repos/${owner}/${repo}/issues/comments/${commentId}/reactions`;
commentUpdateEndpoint = `/repos/${owner}/${repo}/issues/comments/${commentId}`;
// Only edit comments for command workflows
shouldEditComment = command ? true : false;
break;
case "pull_request":
const prNumber = context.payload?.pull_request?.number;
if (!prNumber) {
core.setFailed("Pull request number not found in event payload");
return;
}
// PRs are "issues" for the reactions endpoint
reactionEndpoint = `/repos/${owner}/${repo}/issues/${prNumber}/reactions`;
// Don't edit PR bodies for now - this might be more complex
shouldEditComment = false;
break;
case "pull_request_review_comment":
const reviewCommentId = context.payload?.comment?.id;
if (!reviewCommentId) {
core.setFailed("Review comment ID not found in event payload");
return;
}
reactionEndpoint = `/repos/${owner}/${repo}/pulls/comments/${reviewCommentId}/reactions`;
commentUpdateEndpoint = `/repos/${owner}/${repo}/pulls/comments/${reviewCommentId}`;
// Only edit comments for command workflows
shouldEditComment = command ? true : false;
break;
default:
core.setFailed(`Unsupported event type: ${eventName}`);
return;
}
core.info(`Reaction API endpoint: ${reactionEndpoint}`);
// Add reaction first
await addReaction(reactionEndpoint, reaction);
// Then edit comment if applicable and if it's a comment event
if (shouldEditComment && commentUpdateEndpoint) {
core.info(`Comment update endpoint: ${commentUpdateEndpoint}`);
await editCommentWithWorkflowLink(commentUpdateEndpoint, runUrl);
} else {
if (!command && commentUpdateEndpoint) {
core.info(
"Skipping comment edit - only available for command workflows"
);
} else {
core.info(`Skipping comment edit for event type: ${eventName}`);
}
}
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
core.error(`Failed to process reaction and comment edit: ${errorMessage}`);
core.setFailed(
`Failed to process reaction and comment edit: ${errorMessage}`
);
}
}
/**
* Add a reaction to a GitHub issue, PR, or comment
* @param {string} endpoint - The GitHub API endpoint to add the reaction to
* @param {string} reaction - The reaction type to add
*/
async function addReaction(endpoint, reaction) {
const response = await github.request("POST " + endpoint, {
content: reaction,
headers: {
Accept: "application/vnd.github+json",
},
});
const reactionId = response.data?.id;
if (reactionId) {
core.info(`Successfully added reaction: ${reaction} (id: ${reactionId})`);
core.setOutput("reaction-id", reactionId.toString());
} else {
core.info(`Successfully added reaction: ${reaction}`);
core.setOutput("reaction-id", "");
}
}
/**
* Edit a comment to add a workflow run link
* @param {string} endpoint - The GitHub API endpoint to update the comment
* @param {string} runUrl - The URL of the workflow run
*/
async function editCommentWithWorkflowLink(endpoint, runUrl) {
try {
// First, get the current comment content
const getResponse = await github.request("GET " + endpoint, {
headers: {
Accept: "application/vnd.github+json",
},
});
const originalBody = getResponse.data.body || "";
const workflowLinkText = `\n\n---\n*🤖 [Workflow run](${runUrl}) triggered by this comment*`;
// Check if we've already added a workflow link to avoid duplicates
if (originalBody.includes("*🤖 [Workflow run](")) {
core.info("Comment already contains a workflow run link, skipping edit");
return;
}
const updatedBody = originalBody + workflowLinkText;
// Update the comment
const updateResponse = await github.request("PATCH " + endpoint, {
body: updatedBody,
headers: {
Accept: "application/vnd.github+json",
},
});
core.info(`Successfully updated comment with workflow link`);
core.info(`Comment ID: ${updateResponse.data.id}`);
} catch (error) {
// Don't fail the entire job if comment editing fails - just log it
const errorMessage = error instanceof Error ? error.message : String(error);
core.warning(
"Failed to edit comment with workflow link (This is not critical - the reaction was still added successfully): " +
errorMessage
);
}
}
await main();
pr-fix:
needs: task
if: >
contains(github.event.issue.body, '/pr-fix') || contains(github.event.comment.body, '/pr-fix') ||
contains(github.event.pull_request.body, '/pr-fix')
runs-on: ubuntu-latest
permissions: read-all
outputs:
output: ${{ steps.collect_output.outputs.output }}
steps:
- name: Checkout repository
uses: actions/checkout@v6
- name: Configure Git credentials
run: |
git config --global user.email "github-actions[bot]@users.noreply.github.com"
git config --global user.name "${{ github.workflow }}"
echo "Git configured with standard GitHub Actions identity"
- name: Setup agent output
id: setup_agent_output
uses: actions/github-script@v8
with:
script: |
function main() {
const fs = require("fs");
const crypto = require("crypto");
// Generate a random filename for the output file
const randomId = crypto.randomBytes(8).toString("hex");
const outputFile = `/tmp/aw_output_${randomId}.txt`;
// Ensure the /tmp directory exists
fs.mkdirSync("/tmp", { recursive: true });
// We don't create the file, as the name is sufficiently random
// and some engines (Claude) fails first Write to the file
// if it exists and has not been read.
// Set the environment variable for subsequent steps
core.exportVariable("GITHUB_AW_SAFE_OUTPUTS", outputFile);
// Also set as step output for reference
core.setOutput("output_file", outputFile);
}
main();
- name: Setup Safe Outputs Collector MCP
env:
GITHUB_AW_SAFE_OUTPUTS_CONFIG: "{\"add-comment\":{},\"create-issue\":{},\"push-to-pr-branch\":{}}"
run: |
mkdir -p /tmp/safe-outputs
cat > /tmp/safe-outputs/mcp-server.cjs << 'EOF'
const fs = require("fs");
const encoder = new TextEncoder();
const configEnv = process.env.GITHUB_AW_SAFE_OUTPUTS_CONFIG;
if (!configEnv) throw new Error("GITHUB_AW_SAFE_OUTPUTS_CONFIG not set");
const safeOutputsConfig = JSON.parse(configEnv);
const outputFile = process.env.GITHUB_AW_SAFE_OUTPUTS;
if (!outputFile)
throw new Error("GITHUB_AW_SAFE_OUTPUTS not set, no output file");
const SERVER_INFO = { name: "safe-outputs-mcp-server", version: "1.0.0" };
const debug = msg => process.stderr.write(`[${SERVER_INFO.name}] ${msg}\n`);
function writeMessage(obj) {
const json = JSON.stringify(obj);
debug(`send: ${json}`);
const message = json + "\n";
const bytes = encoder.encode(message);
fs.writeSync(1, bytes);
}
class ReadBuffer {
append(chunk) {
this._buffer = this._buffer ? Buffer.concat([this._buffer, chunk]) : chunk;
}
readMessage() {
if (!this._buffer) {
return null;
}
const index = this._buffer.indexOf("\n");
if (index === -1) {
return null;
}
const line = this._buffer.toString("utf8", 0, index).replace(/\r$/, "");
this._buffer = this._buffer.subarray(index + 1);
if (line.trim() === "") {
return this.readMessage(); // Skip empty lines recursively
}
try {
return JSON.parse(line);
} catch (error) {
throw new Error(
`Parse error: ${error instanceof Error ? error.message : String(error)}`
);
}
}
}
const readBuffer = new ReadBuffer();
function onData(chunk) {
readBuffer.append(chunk);
processReadBuffer();
}
function processReadBuffer() {
while (true) {
try {
const message = readBuffer.readMessage();
if (!message) {
break;
}
debug(`recv: ${JSON.stringify(message)}`);
handleMessage(message);
} catch (error) {
// For parse errors, we can't know the request id, so we shouldn't send a response
// according to JSON-RPC spec. Just log the error.
debug(
`Parse error: ${error instanceof Error ? error.message : String(error)}`
);
}
}
}
function replyResult(id, result) {
if (id === undefined || id === null) return; // notification
const res = { jsonrpc: "2.0", id, result };
writeMessage(res);
}
function replyError(id, code, message, data) {
// Don't send error responses for notifications (id is null/undefined)
if (id === undefined || id === null) {
debug(`Error for notification: ${message}`);
return;
}
const error = { code, message };
if (data !== undefined) {
error.data = data;
}
const res = {
jsonrpc: "2.0",
id,
error,
};
writeMessage(res);
}
function isToolEnabled(name) {
return safeOutputsConfig[name];
}
function appendSafeOutput(entry) {
if (!outputFile) throw new Error("No output file configured");
const jsonLine = JSON.stringify(entry) + "\n";
try {
fs.appendFileSync(outputFile, jsonLine);
} catch (error) {
throw new Error(
`Failed to write to output file: ${error instanceof Error ? error.message : String(error)}`
);
}
}
const defaultHandler = type => args => {
const entry = { ...(args || {}), type };
appendSafeOutput(entry);
return {
content: [
{
type: "text",
text: `success`,
},
],
};
};
const TOOLS = Object.fromEntries(
[
{
name: "create-issue",
description: "Create a new GitHub issue",
inputSchema: {
type: "object",
required: ["title", "body"],
properties: {
title: { type: "string", description: "Issue title" },
body: { type: "string", description: "Issue body/description" },
labels: {
type: "array",
items: { type: "string" },
description: "Issue labels",
},
},
additionalProperties: false,
},
},
{
name: "create-discussion",
description: "Create a new GitHub discussion",
inputSchema: {
type: "object",
required: ["title", "body"],
properties: {
title: { type: "string", description: "Discussion title" },
body: { type: "string", description: "Discussion body/content" },
category: { type: "string", description: "Discussion category" },
},
additionalProperties: false,
},
},
{
name: "add-comment",
description: "Add a comment to a GitHub issue or pull request",
inputSchema: {
type: "object",
required: ["body"],
properties: {
body: { type: "string", description: "Comment body/content" },
issue_number: {
type: "number",
description: "Issue or PR number (optional for current context)",
},
},
additionalProperties: false,
},
},
{
name: "create-pull-request",
description: "Create a new GitHub pull request",
inputSchema: {
type: "object",
required: ["title", "body", "branch"],
properties: {
title: { type: "string", description: "Pull request title" },
body: {
type: "string",
description: "Pull request body/description",
},
branch: {
type: "string",
description: "Required branch name",
},
labels: {
type: "array",
items: { type: "string" },
description: "Optional labels to add to the PR",
},
},
additionalProperties: false,
},
},
{
name: "create-pull-request-review-comment",
description: "Create a review comment on a GitHub pull request",
inputSchema: {
type: "object",
required: ["path", "line", "body"],
properties: {
path: {
type: "string",
description: "File path for the review comment",
},
line: {
type: ["number", "string"],
description: "Line number for the comment",
},
body: { type: "string", description: "Comment body content" },
start_line: {
type: ["number", "string"],
description: "Optional start line for multi-line comments",
},
side: {
type: "string",
enum: ["LEFT", "RIGHT"],
description: "Optional side of the diff: LEFT or RIGHT",
},
},
additionalProperties: false,
},
},
{
name: "create-code-scanning-alert",
description: "Create a code scanning alert",
inputSchema: {
type: "object",
required: ["file", "line", "severity", "message"],
properties: {
file: {
type: "string",
description: "File path where the issue was found",
},
line: {
type: ["number", "string"],
description: "Line number where the issue was found",
},
severity: {
type: "string",
enum: ["error", "warning", "info", "note"],
description: "Severity level",
},
message: {
type: "string",
description: "Alert message describing the issue",
},
column: {
type: ["number", "string"],
description: "Optional column number",
},
ruleIdSuffix: {
type: "string",
description: "Optional rule ID suffix for uniqueness",
},
},
additionalProperties: false,
},
},
{
name: "add-labels",
description: "Add labels to a GitHub issue or pull request",
inputSchema: {
type: "object",
required: ["labels"],
properties: {
labels: {
type: "array",
items: { type: "string" },
description: "Labels to add",
},
issue_number: {
type: "number",
description: "Issue or PR number (optional for current context)",
},
},
additionalProperties: false,
},
},
{
name: "update-issue",
description: "Update a GitHub issue",
inputSchema: {
type: "object",
properties: {
status: {
type: "string",
enum: ["open", "closed"],
description: "Optional new issue status",
},
title: { type: "string", description: "Optional new issue title" },
body: { type: "string", description: "Optional new issue body" },
issue_number: {
type: ["number", "string"],
description: "Optional issue number for target '*'",
},
},
additionalProperties: false,
},
},
{
name: "push-to-pr-branch",
description: "Push changes to a pull request branch",
inputSchema: {
type: "object",
required: ["branch", "message"],
properties: {
branch: {
type: "string",
description:
"The name of the branch to push to, should be the branch name associated with the pull request",
},
message: { type: "string", description: "Commit message" },
pull_request_number: {
type: ["number", "string"],
description: "Optional pull request number for target '*'",
},
},
additionalProperties: false,
},
},
{
name: "missing-tool",
description:
"Report a missing tool or functionality needed to complete tasks",
inputSchema: {
type: "object",
required: ["tool", "reason"],
properties: {
tool: { type: "string", description: "Name of the missing tool" },
reason: { type: "string", description: "Why this tool is needed" },
alternatives: {
type: "string",
description: "Possible alternatives or workarounds",
},
},
additionalProperties: false,
},
},
]
.filter(({ name }) => isToolEnabled(name))
.map(tool => [tool.name, tool])
);
debug(`v${SERVER_INFO.version} ready on stdio`);
debug(` output file: ${outputFile}`);
debug(` config: ${JSON.stringify(safeOutputsConfig)}`);
debug(` tools: ${Object.keys(TOOLS).join(", ")}`);
if (!Object.keys(TOOLS).length)
throw new Error("No tools enabled in configuration");
function handleMessage(req) {
// Validate basic JSON-RPC structure
if (!req || typeof req !== "object") {
debug(`Invalid message: not an object`);
return;
}
if (req.jsonrpc !== "2.0") {
debug(`Invalid message: missing or invalid jsonrpc field`);
return;
}
const { id, method, params } = req;
// Validate method field
if (!method || typeof method !== "string") {
replyError(id, -32600, "Invalid Request: method must be a string");
return;
}
try {
if (method === "initialize") {
const clientInfo = params?.clientInfo ?? {};
console.error(`client initialized:`, clientInfo);
const protocolVersion = params?.protocolVersion ?? undefined;
const result = {
serverInfo: SERVER_INFO,
...(protocolVersion ? { protocolVersion } : {}),
capabilities: {
tools: {},
},
};
replyResult(id, result);
} else if (method === "tools/list") {
const list = [];
Object.values(TOOLS).forEach(tool => {
list.push({
name: tool.name,
description: tool.description,
inputSchema: tool.inputSchema,
});
});
replyResult(id, { tools: list });
} else if (method === "tools/call") {
const name = params?.name;
const args = params?.arguments ?? {};
if (!name || typeof name !== "string") {
replyError(id, -32602, "Invalid params: 'name' must be a string");
return;
}
const tool = TOOLS[name];
if (!tool) {
replyError(id, -32601, `Tool not found: ${name}`);
return;
}