-
Notifications
You must be signed in to change notification settings - Fork 429
Expand file tree
/
Copy pathgithub-mcp-structural-analysis.lock.yml
More file actions
8298 lines (8054 loc) · 385 KB
/
Copy pathgithub-mcp-structural-analysis.lock.yml
File metadata and controls
8298 lines (8054 loc) · 385 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
#
# ___ _ _
# / _ \ | | (_)
# | |_| | __ _ ___ _ __ | |_ _ ___
# | _ |/ _` |/ _ \ '_ \| __| |/ __|
# | | | | (_| | __/ | | | |_| | (__
# \_| |_/\__, |\___|_| |_|\__|_|\___|
# __/ |
# _ _ |___/
# | | | | / _| |
# | | | | ___ _ __ _ __| |_| | _____ ____
# | |/\| |/ _ \ '__| |/ /| _| |/ _ \ \ /\ / / ___|
# \ /\ / (_) | | | | ( | | | | (_) \ V V /\__ \
# \/ \/ \___/|_| |_|\_\|_| |_|\___/ \_/\_/ |___/
#
# 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
# For more information: https://github.com/githubnext/gh-aw/blob/main/.github/aw/github-agentic-workflows.md
#
# Structural analysis of GitHub MCP tool responses with schema evaluation and usefulness ratings for agentic work
#
# Original Frontmatter:
# ```yaml
# description: Structural analysis of GitHub MCP tool responses with schema evaluation and usefulness ratings for agentic work
# timeout-minutes: 15
# on:
# schedule:
# - cron: "0 11 * * 1-5" # 11 AM UTC, weekdays only
# workflow_dispatch:
# permissions:
# contents: read
# actions: read
# issues: read
# pull-requests: read
# discussions: read
# repository-projects: read
# security-events: read
# engine: claude
# strict: false # Required: imports python-dataviz.md which needs network access, and claude doesn't support firewall
# tools:
# github:
# mode: local
# read-only: true
# toolsets: [all]
# cache-memory:
# key: mcp-response-analysis-${{ github.workflow }}
# safe-outputs:
# create-discussion:
# category: "audits"
# title-prefix: "[mcp-analysis] "
# max: 1
# close-older-discussions: true
# imports:
# - shared/python-dataviz.md
# - shared/reporting.md
# ```
#
# Resolved workflow manifest:
# Imports:
# - shared/python-dataviz.md
# - shared/reporting.md
#
# Job Dependency Graph:
# ```mermaid
# graph LR
# activation["activation"]
# agent["agent"]
# conclusion["conclusion"]
# create_discussion["create_discussion"]
# detection["detection"]
# update_cache_memory["update_cache_memory"]
# upload_assets["upload_assets"]
# activation --> agent
# activation --> conclusion
# agent --> conclusion
# agent --> create_discussion
# agent --> detection
# agent --> update_cache_memory
# agent --> upload_assets
# create_discussion --> conclusion
# detection --> conclusion
# detection --> create_discussion
# detection --> update_cache_memory
# detection --> upload_assets
# update_cache_memory --> conclusion
# upload_assets --> conclusion
# ```
#
# Original Prompt:
# ```markdown
# # Python Data Visualization Guide
#
# Python scientific libraries have been installed and are ready for use. A temporary folder structure has been created at `/tmp/gh-aw/python/` for organizing scripts, data, and outputs.
#
# ## Installed Libraries
#
# - **NumPy**: Array processing and numerical operations
# - **Pandas**: Data manipulation and analysis
# - **Matplotlib**: Chart generation and plotting
# - **Seaborn**: Statistical data visualization
# - **SciPy**: Scientific computing utilities
#
# ## Directory Structure
#
# ```
# /tmp/gh-aw/python/
# ├── data/ # Store all data files here (CSV, JSON, etc.)
# ├── charts/ # Generated chart images (PNG)
# ├── artifacts/ # Additional output files
# └── *.py # Python scripts
# ```
#
# ## Data Separation Requirement
#
# **CRITICAL**: Data must NEVER be inlined in Python code. Always store data in external files and load using pandas.
#
# ### ❌ PROHIBITED - Inline Data
# ```python
# # DO NOT do this
# data = [10, 20, 30, 40, 50]
# labels = ['A', 'B', 'C', 'D', 'E']
# ```
#
# ### ✅ REQUIRED - External Data Files
# ```python
# # Always load data from external files
# import pandas as pd
#
# # Load data from CSV
# data = pd.read_csv('/tmp/gh-aw/python/data/data.csv')
#
# # Or from JSON
# data = pd.read_json('/tmp/gh-aw/python/data/data.json')
# ```
#
# ## Chart Generation Best Practices
#
# ### High-Quality Chart Settings
#
# ```python
# import matplotlib.pyplot as plt
# import seaborn as sns
#
# # Set style for better aesthetics
# sns.set_style("whitegrid")
# sns.set_palette("husl")
#
# # Create figure with high DPI
# fig, ax = plt.subplots(figsize=(10, 6), dpi=300)
#
# # Your plotting code here
# # ...
#
# # Save with high quality
# plt.savefig('/tmp/gh-aw/python/charts/chart.png',
# dpi=300,
# bbox_inches='tight',
# facecolor='white',
# edgecolor='none')
# ```
#
# ### Chart Quality Guidelines
#
# - **DPI**: Use 300 or higher for publication quality
# - **Figure Size**: Standard is 10x6 inches (adjustable based on needs)
# - **Labels**: Always include clear axis labels and titles
# - **Legend**: Add legends when plotting multiple series
# - **Grid**: Enable grid lines for easier reading
# - **Colors**: Use colorblind-friendly palettes (seaborn defaults are good)
#
# ## Including Images in Reports
#
# When creating reports (issues, discussions, etc.), use the `upload asset` tool to make images URL-addressable and include them in markdown:
#
# ### Step 1: Generate and Upload Chart
# ```python
# # Generate your chart
# plt.savefig('/tmp/gh-aw/python/charts/my_chart.png', dpi=300, bbox_inches='tight')
# ```
#
# ### Step 2: Upload as Asset
# Use the `upload asset` tool to upload the chart file. The tool will return a GitHub raw content URL.
#
# ### Step 3: Include in Markdown Report
# When creating your discussion or issue, include the image using markdown:
#
# ```markdown
# ## Visualization Results
#
# 
#
# The chart above shows...
# ```
#
# **Important**: Assets are published to an orphaned git branch and become URL-addressable after workflow completion.
#
# ## Cache Memory Integration
#
# The cache memory at `/tmp/gh-aw/cache-memory/` is available for storing reusable code:
#
# **Helper Functions to Cache:**
# - Data loading utilities: `data_loader.py`
# - Chart styling functions: `chart_utils.py`
# - Common data transformations: `transforms.py`
#
# **Check Cache Before Creating:**
# ```bash
# # Check if helper exists in cache
# if [ -f /tmp/gh-aw/cache-memory/data_loader.py ]; then
# cp /tmp/gh-aw/cache-memory/data_loader.py /tmp/gh-aw/python/
# echo "Using cached data_loader.py"
# fi
# ```
#
# **Save to Cache for Future Runs:**
# ```bash
# # Save useful helpers to cache
# cp /tmp/gh-aw/python/data_loader.py /tmp/gh-aw/cache-memory/
# echo "Saved data_loader.py to cache for future runs"
# ```
#
# ## Complete Example Workflow
#
# ```python
# #!/usr/bin/env python3
# """
# Example data visualization script
# Generates a bar chart from external data
# """
# import pandas as pd
# import matplotlib.pyplot as plt
# import seaborn as sns
#
# # Set style
# sns.set_style("whitegrid")
# sns.set_palette("husl")
#
# # Load data from external file (NEVER inline)
# data = pd.read_csv('/tmp/gh-aw/python/data/data.csv')
#
# # Process data
# summary = data.groupby('category')['value'].sum()
#
# # Create chart
# fig, ax = plt.subplots(figsize=(10, 6), dpi=300)
# summary.plot(kind='bar', ax=ax)
#
# # Customize
# ax.set_title('Data Summary by Category', fontsize=16, fontweight='bold')
# ax.set_xlabel('Category', fontsize=12)
# ax.set_ylabel('Value', fontsize=12)
# ax.grid(True, alpha=0.3)
#
# # Save chart
# plt.savefig('/tmp/gh-aw/python/charts/chart.png',
# dpi=300,
# bbox_inches='tight',
# facecolor='white')
#
# print("Chart saved to /tmp/gh-aw/python/charts/chart.png")
# ```
#
# ## Error Handling
#
# **Check File Existence:**
# ```python
# import os
#
# data_file = '/tmp/gh-aw/python/data/data.csv'
# if not os.path.exists(data_file):
# raise FileNotFoundError(f"Data file not found: {data_file}")
# ```
#
# **Validate Data:**
# ```python
# # Check for required columns
# required_cols = ['category', 'value']
# missing = set(required_cols) - set(data.columns)
# if missing:
# raise ValueError(f"Missing columns: {missing}")
# ```
#
# ## Artifact Upload
#
# Charts and source files are automatically uploaded as artifacts:
#
# **Charts Artifact:**
# - Name: `data-charts`
# - Contents: PNG files from `/tmp/gh-aw/python/charts/`
# - Retention: 30 days
#
# **Source and Data Artifact:**
# - Name: `python-source-and-data`
# - Contents: Python scripts and data files
# - Retention: 30 days
#
# Both artifacts are uploaded with `if: always()` condition, ensuring they're available even if the workflow fails.
#
# ## Tips for Success
#
# 1. **Always Separate Data**: Store data in files, never inline in code
# 2. **Use Cache Memory**: Store reusable helpers for faster execution
# 3. **High Quality Charts**: Use DPI 300+ and proper sizing
# 4. **Clear Documentation**: Add docstrings and comments
# 5. **Error Handling**: Validate data and check file existence
# 6. **Type Hints**: Use type annotations for better code quality
# 7. **Seaborn Defaults**: Leverage seaborn for better aesthetics
# 8. **Reproducibility**: Set random seeds when needed
#
# ## Common Data Sources
#
# Based on common use cases:
#
# **Repository Statistics:**
# ```python
# # Collect via GitHub API, save to data.csv
# # Then load and visualize
# data = pd.read_csv('/tmp/gh-aw/python/data/repo_stats.csv')
# ```
#
# **Workflow Metrics:**
# ```python
# # Collect via GitHub Actions API, save to data.json
# data = pd.read_json('/tmp/gh-aw/python/data/workflow_metrics.json')
# ```
#
# **Sample Data Generation:**
# ```python
# # Generate with NumPy, save to file first
# import numpy as np
# data = np.random.randn(100, 2)
# df = pd.DataFrame(data, columns=['x', 'y'])
# df.to_csv('/tmp/gh-aw/python/data/sample_data.csv', index=False)
#
# # Then load it back (demonstrating the pattern)
# data = pd.read_csv('/tmp/gh-aw/python/data/sample_data.csv')
# ```
#
# ## Report Formatting
#
# Structure your report with an overview followed by detailed content:
#
# 1. **Content Overview**: Start with 1-2 paragraphs that summarize the key findings, highlights, or main points of your report. This should give readers a quick understanding of what the report contains without needing to expand the details.
#
# 2. **Detailed Content**: Place the rest of your report inside HTML `<details>` and `<summary>` tags to allow readers to expand and view the full information. **IMPORTANT**: Always wrap the summary text in `<b>` tags to make it bold.
#
# **Example format:**
#
# `````markdown
# Brief overview paragraph 1 introducing the report and its main findings.
#
# Optional overview paragraph 2 with additional context or highlights.
#
# <details>
# <summary><b>Full Report Details</b></summary>
#
# ## Detailed Analysis
#
# Full report content with all sections, tables, and detailed information goes here.
#
# ### Section 1
# [Content]
#
# ### Section 2
# [Content]
#
# </details>
# `````
#
# ## Reporting Workflow Run Information
#
# When analyzing workflow run logs or reporting information from GitHub Actions runs:
#
# ### 1. Workflow Run ID Formatting
#
# **Always render workflow run IDs as clickable URLs** when mentioning them in your report. The workflow run data includes a `url` field that provides the full GitHub Actions run page URL.
#
# **Format:**
#
# `````markdown
# [§12345](https://github.com/owner/repo/actions/runs/12345)
# `````
#
# **Example:**
#
# `````markdown
# Analysis based on [§456789](https://github.com/githubnext/gh-aw/actions/runs/456789)
# `````
#
# ### 2. Document References for Workflow Runs
#
# When your analysis is based on information mined from one or more workflow runs, **include up to 3 workflow run URLs as document references** at the end of your report.
#
# **Format:**
#
# `````markdown
# ---
#
# **References:**
# - [§12345](https://github.com/owner/repo/actions/runs/12345)
# - [§12346](https://github.com/owner/repo/actions/runs/12346)
# - [§12347](https://github.com/owner/repo/actions/runs/12347)
# `````
#
# **Guidelines:**
#
# - Include **maximum 3 references** to keep reports concise
# - Choose the most relevant or representative runs (e.g., failed runs, high-cost runs, or runs with significant findings)
# - Always use the actual URL from the workflow run data (specifically, use the `url` field from `RunData` or the `RunURL` field from `ErrorSummary`)
# - If analyzing more than 3 runs, select the most important ones for references
#
# ## Footer Attribution
#
# **Do NOT add footer lines** like `> AI generated by...` to your comment. The system automatically appends attribution after your content to prevent duplicates.
#
# # GitHub MCP Structural Analysis
#
# You are the GitHub MCP Structural Analyzer - an agent that performs quantitative analysis of the response sizes AND qualitative analysis of the structure/schema of GitHub MCP tool responses to evaluate their usefulness for agentic work.
#
# ## Mission
#
# Analyze each GitHub MCP tool response for:
# 1. **Size**: Response size in tokens
# 2. **Structure**: Schema and data organization
# 3. **Usefulness**: Rating for agentic workflows (1-5 scale)
#
# Track trends over 30 days, generate visualizations, and create a daily discussion report.
#
# ## Context
#
# - **Repository**: ${{ github.repository }}
# - **Run ID**: ${{ github.run_id }}
# - **Analysis Date**: Current date
#
# ## Analysis Process
#
# ### Phase 1: Load Historical Data
#
# 1. Check for existing trending data at `/tmp/gh-aw/cache-memory/mcp_analysis.jsonl`
# 2. If exists, load the historical data (keep last 30 days)
# 3. If not exists, start fresh
#
# ### Phase 2: Tool Response Analysis
#
# **IMPORTANT**: Keep your context small. Call each tool with minimal parameters to analyze responses, not to gather extensive data.
#
# For each GitHub MCP toolset, systematically test representative tools:
#
# #### Toolsets to Test
#
# Test ONE representative tool from each toolset with minimal parameters:
#
# 1. **context**: `get_me` - Get current user info
# 2. **repos**: `get_file_contents` - Get a small file (README.md or similar)
# 3. **issues**: `list_issues` - List issues with perPage=1
# 4. **pull_requests**: `list_pull_requests` - List PRs with perPage=1
# 5. **actions**: `list_workflows` - List workflows with perPage=1
# 6. **code_security**: `list_code_scanning_alerts` - List alerts with minimal params
# 7. **discussions**: `list_discussions` (if available)
# 8. **labels**: `get_label` - Get a single label
# 9. **users**: `get_user` (if available)
# 10. **search**: Search with minimal query
#
# #### For Each Tool Call, Analyze:
#
# **A. Size Metrics**
# - Estimate response size in tokens (1 token ≈ 4 characters)
#
# **B. Structure Analysis**
# Identify the response schema:
# - **Data type**: object, array, primitive
# - **Nesting depth**: How deeply nested is the data?
# - **Key fields**: What are the main fields returned?
# - **Field types**: strings, numbers, booleans, arrays, objects
# - **Pagination**: Does it support pagination?
# - **Relationships**: Does it include related entities (e.g., user info embedded in issue)?
#
# **C. Usefulness Rating for Agentic Work (1-5 scale)**
#
# Rate each tool's response on how useful it is for autonomous agents:
#
# | Rating | Description |
# |--------|-------------|
# | **5** | Excellent - Complete, actionable data with clear structure |
# | **4** | Good - Most needed data present, minor gaps |
# | **3** | Adequate - Usable but requires additional calls |
# | **2** | Limited - Missing key data, hard to parse |
# | **1** | Poor - Minimal value for agentic tasks |
#
# **Rating Criteria:**
# - **Completeness**: Does response contain all needed info?
# - **Actionability**: Can agent act on this data directly?
# - **Clarity**: Is the structure intuitive and consistent?
# - **Efficiency**: Is context usage optimized (no bloat)?
# - **Relationships**: Are related entities included or linkable?
#
# Record: `{tool_name, toolset, tokens, schema_type, nesting_depth, key_fields, usefulness_rating, notes, timestamp}`
#
# ### Phase 3: Save Data
#
# Append today's measurements to `/tmp/gh-aw/cache-memory/mcp_analysis.jsonl`:
#
# ```json
# {"date": "2024-01-15", "tool": "get_me", "toolset": "context", "tokens": 150, "schema_type": "object", "nesting_depth": 2, "key_fields": ["login", "id", "name", "email"], "usefulness_rating": 5, "notes": "Complete user profile, immediately actionable"}
# {"date": "2024-01-15", "tool": "list_issues", "toolset": "issues", "tokens": 500, "schema_type": "array", "nesting_depth": 3, "key_fields": ["number", "title", "state", "labels", "assignees"], "usefulness_rating": 4, "notes": "Good issue data but user details minimal"}
# ```
#
# Prune data older than 30 days.
#
# ### Phase 4: Generate Visualization
#
# Create a Python script at `/tmp/gh-aw/python/analyze_mcp.py`:
#
# ```python
# #!/usr/bin/env python3
# """MCP Tool Structural Analysis"""
# import pandas as pd
# import matplotlib.pyplot as plt
# import seaborn as sns
# import json
# import os
# from datetime import datetime, timedelta
#
# # Configuration
# CACHE_FILE = '/tmp/gh-aw/cache-memory/mcp_analysis.jsonl'
# CHARTS_DIR = '/tmp/gh-aw/python/charts'
# DATA_DIR = '/tmp/gh-aw/python/data'
#
# os.makedirs(CHARTS_DIR, exist_ok=True)
# os.makedirs(DATA_DIR, exist_ok=True)
#
# # Load data
# if os.path.exists(CACHE_FILE):
# df = pd.read_json(CACHE_FILE, lines=True)
# df['date'] = pd.to_datetime(df['date'])
# else:
# print("No historical data found")
# exit(1)
#
# # Save data copy
# df.to_csv(f'{DATA_DIR}/mcp_analysis.csv', index=False)
#
# # Set style
# sns.set_style("whitegrid")
# custom_colors = ["#FF6B6B", "#4ECDC4", "#45B7D1", "#FFA07A", "#98D8C8", "#DDA0DD", "#F0E68C"]
# sns.set_palette(custom_colors)
#
# # Chart 1: Response Size by Toolset (Bar Chart)
# fig, ax = plt.subplots(figsize=(12, 6), dpi=300)
# toolset_avg = df.groupby('toolset')['tokens'].mean().sort_values(ascending=False)
# toolset_avg.plot(kind='bar', ax=ax, color=custom_colors)
# ax.set_title('Average Response Size by Toolset', fontsize=16, fontweight='bold')
# ax.set_xlabel('Toolset', fontsize=12)
# ax.set_ylabel('Tokens', fontsize=12)
# ax.grid(True, alpha=0.3)
# plt.xticks(rotation=45, ha='right')
# plt.tight_layout()
# plt.savefig(f'{CHARTS_DIR}/toolset_sizes.png', dpi=300, bbox_inches='tight', facecolor='white')
# plt.close()
#
# # Chart 2: Usefulness Rating by Toolset (Bar Chart)
# fig, ax = plt.subplots(figsize=(12, 6), dpi=300)
# latest_date = df['date'].max()
# latest_data = df[df['date'] == latest_date]
# usefulness_by_toolset = latest_data.groupby('toolset')['usefulness_rating'].mean().sort_values(ascending=False)
# colors = ['#2ECC71' if x >= 4 else '#F39C12' if x >= 3 else '#E74C3C' for x in usefulness_by_toolset.values]
# usefulness_by_toolset.plot(kind='bar', ax=ax, color=colors)
# ax.set_title('Usefulness Rating by Toolset (5=Excellent, 1=Poor)', fontsize=16, fontweight='bold')
# ax.set_xlabel('Toolset', fontsize=12)
# ax.set_ylabel('Rating', fontsize=12)
# ax.set_ylim(0, 5.5)
# ax.axhline(y=4, color='green', linestyle='--', alpha=0.5, label='Good threshold')
# ax.axhline(y=3, color='orange', linestyle='--', alpha=0.5, label='Adequate threshold')
# ax.grid(True, alpha=0.3)
# plt.xticks(rotation=45, ha='right')
# plt.legend()
# plt.tight_layout()
# plt.savefig(f'{CHARTS_DIR}/usefulness_ratings.png', dpi=300, bbox_inches='tight', facecolor='white')
# plt.close()
#
# # Chart 3: Daily Trends (Line Chart)
# fig, ax = plt.subplots(figsize=(14, 7), dpi=300)
# daily_total = df.groupby('date')['tokens'].sum()
# ax.plot(daily_total.index, daily_total.values, marker='o', linewidth=2, color='#4ECDC4')
# ax.fill_between(daily_total.index, daily_total.values, alpha=0.2, color='#4ECDC4')
# ax.set_title('Daily Total Token Usage Trend', fontsize=16, fontweight='bold')
# ax.set_xlabel('Date', fontsize=12)
# ax.set_ylabel('Total Tokens', fontsize=12)
# ax.grid(True, alpha=0.3)
# plt.xticks(rotation=45)
# plt.tight_layout()
# plt.savefig(f'{CHARTS_DIR}/daily_trend.png', dpi=300, bbox_inches='tight', facecolor='white')
# plt.close()
#
# # Chart 4: Size vs Usefulness Scatter
# fig, ax = plt.subplots(figsize=(12, 8), dpi=300)
# scatter = ax.scatter(latest_data['tokens'], latest_data['usefulness_rating'],
# c=range(len(latest_data)), cmap='viridis', s=150, alpha=0.7)
# for i, row in latest_data.iterrows():
# ax.annotate(row['tool'], (row['tokens'], row['usefulness_rating']),
# xytext=(5, 5), textcoords='offset points', fontsize=9)
# ax.set_title('Token Size vs Usefulness Rating', fontsize=16, fontweight='bold')
# ax.set_xlabel('Tokens', fontsize=12)
# ax.set_ylabel('Usefulness Rating', fontsize=12)
# ax.set_ylim(0, 5.5)
# ax.grid(True, alpha=0.3)
# plt.tight_layout()
# plt.savefig(f'{CHARTS_DIR}/size_vs_usefulness.png', dpi=300, bbox_inches='tight', facecolor='white')
# plt.close()
#
# print("✅ Charts generated successfully")
# print(f" - toolset_sizes.png")
# print(f" - usefulness_ratings.png")
# print(f" - daily_trend.png")
# print(f" - size_vs_usefulness.png")
# ```
#
# Run the script: `python3 /tmp/gh-aw/python/analyze_mcp.py`
#
# ### Phase 5: Generate Report
#
# Create a discussion with the following structure:
#
# **Title**: `MCP Structural Analysis - {date}`
#
# **Content**:
#
# Brief overview with key findings (tools analyzed, best/worst usefulness ratings, schema patterns).
#
# ```markdown
# <details>
# <summary><b>Full Structural Analysis Report</b></summary>
#
# ## Executive Summary
#
# | Metric | Value |
# |--------|-------|
# | Tools Analyzed | {count} |
# | Total Tokens (Today) | {sum} |
# | Average Usefulness Rating | {avg}/5 |
# | Best Rated Tool | {tool}: {rating}/5 |
# | Worst Rated Tool | {tool}: {rating}/5 |
#
# ## Usefulness Ratings for Agentic Work
#
# | Tool | Toolset | Rating | Assessment |
# |------|---------|--------|------------|
# | ... | ... | ⭐⭐⭐⭐⭐ | Excellent for autonomous agents |
# | ... | ... | ⭐⭐⭐⭐ | Good, minor improvements possible |
# | ... | ... | ⭐⭐⭐ | Adequate, requires supplementary calls |
# | ... | ... | ⭐⭐ | Limited usefulness |
# | ... | ... | ⭐ | Poor for agentic tasks |
#
# ## Schema Analysis
#
# | Tool | Type | Depth | Key Fields | Notes |
# |------|------|-------|------------|-------|
# | ... | object | 2 | login, id, name | Clean structure |
# | ... | array | 3 | number, title, labels | Nested user data |
#
# ## Response Size Analysis
#
# | Toolset | Avg Tokens | Tools Tested |
# |---------|------------|--------------|
# | ... | ... | ... |
#
# ## Tool-by-Tool Analysis
#
# | Tool | Toolset | Tokens | Schema | Rating | Notes |
# |------|---------|--------|--------|--------|-------|
# | ... | ... | ... | ... | ... | ... |
#
# ## 30-Day Trend Summary
#
# | Metric | Value |
# |--------|-------|
# | Data Points | {count} |
# | Average Daily Tokens | {avg} |
# | Average Rating Trend | {improving/declining/stable} |
#
# ## Recommendations
#
# Based on the analysis:
# - **High-value tools** (rating 4-5): {list}
# - **Tools needing improvement**: {list}
# - **Context-efficient tools** (low tokens, high rating): {list}
# - **Context-heavy tools** (high tokens): {list}
#
# ## Visualizations
#
# ### Response Size by Toolset
# 
#
# ### Usefulness Ratings
# 
#
# ### Daily Token Trend
# 
#
# ### Size vs Usefulness
# 
#
# </details>
# ```
#
# ## Guidelines
#
# ### Context Efficiency
# - **CRITICAL**: Keep your context small
# - Call each tool only ONCE with minimal parameters
# - Don't expand nested data structures unnecessarily
# - Focus on analyzing structure, not gathering extensive data
#
# ### Schema Analysis
# - Identify response data types accurately
# - Note nesting depth (shallow is better for agents)
# - List key fields that provide value
# - Note any redundant or bloated fields
#
# ### Usefulness Rating Criteria
# Apply consistent ratings:
# - **5**: All needed data, clear structure, immediately actionable
# - **4**: Good data, minor gaps, mostly actionable
# - **3**: Usable but needs supplementary calls
# - **2**: Missing key data or confusing structure
# - **1**: Minimal value, better alternatives exist
#
# ### Report Quality
# - Start with brief overview
# - Use collapsible details for full report
# - Include star ratings (⭐) for visual clarity
# - Provide actionable recommendations
#
# ## Success Criteria
#
# A successful analysis:
# - ✅ Tests representative tools from each available toolset
# - ✅ Records response sizes in tokens
# - ✅ Analyzes schema structure (type, depth, fields)
# - ✅ Rates usefulness for agentic work (1-5 scale)
# - ✅ Appends data to cache-memory for trending
# - ✅ Generates Python visualizations
# - ✅ Creates a discussion with statistics, ratings, and charts
# - ✅ Provides recommendations for tool selection
# - ✅ Maintains 30-day rolling window of data
# ```
#
# Pinned GitHub Actions:
# - actions/cache/restore@v4 (0057852bfaa89a56745cba8c7296529d2fc39830)
# https://github.com/actions/cache/commit/0057852bfaa89a56745cba8c7296529d2fc39830
# - actions/cache/save@v4 (0057852bfaa89a56745cba8c7296529d2fc39830)
# https://github.com/actions/cache/commit/0057852bfaa89a56745cba8c7296529d2fc39830
# - actions/checkout@v5 (93cb6efe18208431cddfb8368fd83d5badbf9bfd)
# https://github.com/actions/checkout/commit/93cb6efe18208431cddfb8368fd83d5badbf9bfd
# - actions/download-artifact@v6 (018cc2cf5baa6db3ef3c5f8a56943fffe632ef53)
# https://github.com/actions/download-artifact/commit/018cc2cf5baa6db3ef3c5f8a56943fffe632ef53
# - actions/github-script@v8 (ed597411d8f924073f98dfc5c65a23a2325f34cd)
# https://github.com/actions/github-script/commit/ed597411d8f924073f98dfc5c65a23a2325f34cd
# - actions/setup-node@v6 (395ad3262231945c25e8478fd5baf05154b1d79f)
# https://github.com/actions/setup-node/commit/395ad3262231945c25e8478fd5baf05154b1d79f
# - actions/upload-artifact@v5 (330a01c490aca151604b8cf639adc76d48f6c5d4)
# https://github.com/actions/upload-artifact/commit/330a01c490aca151604b8cf639adc76d48f6c5d4
name: "GitHub MCP Structural Analysis"
"on":
schedule:
- cron: "0 11 * * 1-5"
workflow_dispatch: null
permissions:
actions: read
contents: read
discussions: read
issues: read
pull-requests: read
repository-projects: read
security-events: read
concurrency:
group: "gh-aw-${{ github.workflow }}"
run-name: "GitHub MCP Structural Analysis"
jobs:
activation:
runs-on: ubuntu-slim
permissions:
contents: read
outputs:
comment_id: ""
comment_repo: ""
steps:
- name: Check workflow file timestamps
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8
env:
GH_AW_WORKFLOW_FILE: "github-mcp-structural-analysis.lock.yml"
with:
script: |
async function main() {
const workflowFile = process.env.GH_AW_WORKFLOW_FILE;
if (!workflowFile) {
core.setFailed("Configuration error: GH_AW_WORKFLOW_FILE not available.");
return;
}
const workflowBasename = workflowFile.replace(".lock.yml", "");
const workflowMdPath = `.github/workflows/${workflowBasename}.md`;
const lockFilePath = `.github/workflows/${workflowFile}`;
core.info(`Checking workflow timestamps using GitHub API:`);
core.info(` Source: ${workflowMdPath}`);
core.info(` Lock file: ${lockFilePath}`);
const { owner, repo } = context.repo;
const ref = context.sha;
async function getLastCommitForFile(path) {
try {
const response = await github.rest.repos.listCommits({
owner,
repo,
path,
per_page: 1,
sha: ref,
});
if (response.data && response.data.length > 0) {
const commit = response.data[0];
return {
sha: commit.sha,
date: commit.commit.committer.date,
message: commit.commit.message,
};
}
return null;
} catch (error) {
core.info(`Could not fetch commit for ${path}: ${error.message}`);
return null;
}
}
const workflowCommit = await getLastCommitForFile(workflowMdPath);
const lockCommit = await getLastCommitForFile(lockFilePath);
if (!workflowCommit) {
core.info(`Source file does not exist: ${workflowMdPath}`);
}
if (!lockCommit) {
core.info(`Lock file does not exist: ${lockFilePath}`);
}
if (!workflowCommit || !lockCommit) {
core.info("Skipping timestamp check - one or both files not found");
return;
}
const workflowDate = new Date(workflowCommit.date);
const lockDate = new Date(lockCommit.date);
core.info(` Source last commit: ${workflowDate.toISOString()} (${workflowCommit.sha.substring(0, 7)})`);
core.info(` Lock last commit: ${lockDate.toISOString()} (${lockCommit.sha.substring(0, 7)})`);
if (workflowDate > lockDate) {
const warningMessage = `WARNING: Lock file '${lockFilePath}' is outdated! The workflow file '${workflowMdPath}' has been modified more recently. Run 'gh aw compile' to regenerate the lock file.`;
core.error(warningMessage);
const workflowTimestamp = workflowDate.toISOString();
const lockTimestamp = lockDate.toISOString();
let summary = core.summary
.addRaw("### ⚠️ Workflow Lock File Warning\n\n")
.addRaw("**WARNING**: Lock file is outdated and needs to be regenerated.\n\n")
.addRaw("**Files:**\n")
.addRaw(`- Source: \`${workflowMdPath}\`\n`)
.addRaw(` - Last commit: ${workflowTimestamp}\n`)
.addRaw(
` - Commit SHA: [\`${workflowCommit.sha.substring(0, 7)}\`](https://github.com/${owner}/${repo}/commit/${workflowCommit.sha})\n`
)
.addRaw(`- Lock: \`${lockFilePath}\`\n`)
.addRaw(` - Last commit: ${lockTimestamp}\n`)
.addRaw(` - Commit SHA: [\`${lockCommit.sha.substring(0, 7)}\`](https://github.com/${owner}/${repo}/commit/${lockCommit.sha})\n\n`)
.addRaw("**Action Required:** Run `gh aw compile` to regenerate the lock file.\n\n");
await summary.write();
} else if (workflowCommit.sha === lockCommit.sha) {
core.info("✅ Lock file is up to date (same commit)");
} else {
core.info("✅ Lock file is up to date");
}
}
main().catch(error => {
core.setFailed(error instanceof Error ? error.message : String(error));
});
agent:
needs: activation
runs-on: ubuntu-latest
permissions:
actions: read
contents: read
discussions: read
issues: read
pull-requests: read
repository-projects: read
security-events: read
concurrency:
group: "gh-aw-claude-${{ github.workflow }}"
env:
GH_AW_ASSETS_ALLOWED_EXTS: ".png,.jpg,.jpeg"
GH_AW_ASSETS_BRANCH: "assets/${{ github.workflow }}"
GH_AW_ASSETS_MAX_SIZE_KB: 10240
GH_AW_MCP_LOG_DIR: /tmp/gh-aw/mcp-logs/safeoutputs
GH_AW_SAFE_OUTPUTS: /tmp/gh-aw/safeoutputs/outputs.jsonl
GH_AW_SAFE_OUTPUTS_CONFIG_PATH: /tmp/gh-aw/safeoutputs/config.json
GH_AW_SAFE_OUTPUTS_TOOLS_PATH: /tmp/gh-aw/safeoutputs/tools.json
outputs:
has_patch: ${{ steps.collect_output.outputs.has_patch }}
model: ${{ steps.generate_aw_info.outputs.model }}
output: ${{ steps.collect_output.outputs.output }}
output_types: ${{ steps.collect_output.outputs.output_types }}
steps:
- name: Checkout repository
uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd # v5
with:
persist-credentials: false
- name: Create gh-aw temp directory
run: |
mkdir -p /tmp/gh-aw/agent
mkdir -p /tmp/gh-aw/sandbox/agent/logs
echo "Created /tmp/gh-aw/agent directory for agentic workflow temporary files"
- name: Setup Python environment
run: "# Create working directory for Python scripts\nmkdir -p /tmp/gh-aw/python\nmkdir -p /tmp/gh-aw/python/data\nmkdir -p /tmp/gh-aw/python/charts\nmkdir -p /tmp/gh-aw/python/artifacts\n\necho \"Python environment setup complete\"\necho \"Working directory: /tmp/gh-aw/python\"\necho \"Data directory: /tmp/gh-aw/python/data\"\necho \"Charts directory: /tmp/gh-aw/python/charts\"\necho \"Artifacts directory: /tmp/gh-aw/python/artifacts\"\n"
- name: Install Python scientific libraries
run: "pip install --user numpy pandas matplotlib seaborn scipy\n\n# Verify installations\npython3 -c \"import numpy; print(f'NumPy {numpy.__version__} installed')\"\npython3 -c \"import pandas; print(f'Pandas {pandas.__version__} installed')\"\npython3 -c \"import matplotlib; print(f'Matplotlib {matplotlib.__version__} installed')\"\npython3 -c \"import seaborn; print(f'Seaborn {seaborn.__version__} installed')\"\npython3 -c \"import scipy; print(f'SciPy {scipy.__version__} installed')\"\n\necho \"All scientific libraries installed successfully\"\n"
- if: always()
name: Upload generated charts
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5
with:
if-no-files-found: warn
name: data-charts
path: /tmp/gh-aw/python/charts/*.png
retention-days: 30
- if: always()
name: Upload source files and data
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5
with:
if-no-files-found: warn
name: python-source-and-data
path: |
/tmp/gh-aw/python/*.py
/tmp/gh-aw/python/data/*
retention-days: 30
# Cache memory file share configuration from frontmatter processed below
- name: Create cache-memory directory
run: |
mkdir -p /tmp/gh-aw/cache-memory
echo "Cache memory directory created at /tmp/gh-aw/cache-memory"
echo "This folder provides persistent file storage across workflow runs"
echo "LLMs and agentic tools can freely read and write files in this directory"
- name: Restore cache memory file share data
uses: actions/cache/restore@0057852bfaa89a56745cba8c7296529d2fc39830 # v4
with:
key: memory-${{ github.workflow }}-${{ github.run_id }}
path: /tmp/gh-aw/cache-memory
restore-keys: |
memory-${{ github.workflow }}-
memory-
- name: Configure Git credentials
env:
REPO_NAME: ${{ github.repository }}
SERVER_URL: ${{ github.server_url }}
run: |
git config --global user.email "github-actions[bot]@users.noreply.github.com"
git config --global user.name "github-actions[bot]"
# Re-authenticate git with GitHub token
SERVER_URL_STRIPPED="${SERVER_URL#https://}"
git remote set-url origin "https://x-access-token:${{ github.token }}@${SERVER_URL_STRIPPED}/${REPO_NAME}.git"
echo "Git configured with standard GitHub Actions identity"
- name: Checkout PR branch
if: |
github.event.pull_request
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8
env:
GH_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN || secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }}
with:
github-token: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN || secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }}
script: |
async function main() {
const eventName = context.eventName;
const pullRequest = context.payload.pull_request;
if (!pullRequest) {
core.info("No pull request context available, skipping checkout");
return;
}
core.info(`Event: ${eventName}`);
core.info(`Pull Request #${pullRequest.number}`);
try {
if (eventName === "pull_request") {
const branchName = pullRequest.head.ref;
core.info(`Checking out PR branch: ${branchName}`);
await exec.exec("git", ["fetch", "origin", branchName]);
await exec.exec("git", ["checkout", branchName]);
core.info(`✅ Successfully checked out branch: ${branchName}`);
} else {
const prNumber = pullRequest.number;
core.info(`Checking out PR #${prNumber} using gh pr checkout`);
await exec.exec("gh", ["pr", "checkout", prNumber.toString()]);
core.info(`✅ Successfully checked out PR #${prNumber}`);
}
} catch (error) {
core.setFailed(`Failed to checkout PR branch: ${error instanceof Error ? error.message : String(error)}`);
}