Files
Sam Morrow ce2e4f9472 refactor: Introduce Inventory pattern with builder, filtering, and per-request optimization (#1589)
* refactor: separate ServerTool into own file with HandlerFunc pattern

- Extract ServerTool struct into pkg/toolsets/server_tool.go
- Add ToolDependencies struct for passing common dependencies to handlers
- HandlerFunc allows lazy handler generation from Tool definitions
- NewServerTool for new dependency-based tools
- NewServerToolLegacy for backward compatibility with existing handlers
- Update toolsets.go to store and pass dependencies
- Update all call sites to use NewServerToolLegacy

Co-authored-by: Adam Holt <4619+omgitsads@users.noreply.github.com>

* Wire ToolDependencies through toolsets

- Move ToolDependencies to pkg/github/dependencies.go with proper types
- Use 'any' in toolsets package to avoid circular dependencies
- Add NewTool/NewToolFromHandler helpers that isolate type assertion
- Tool implementations will be fully typed with no assertions scattered
- Infrastructure ready for incremental tool migration

* refactor(search): migrate search tools to new ServerTool pattern

Migrate search.go tools (SearchRepositories, SearchCode, SearchUsers,
SearchOrgs) to use the new NewTool helper and ToolDependencies pattern.

- Functions now take only TranslationHelperFunc and return ServerTool
- Handler generation uses ToolDependencies for typed access to clients
- Update tools.go call sites to remove getClient parameter
- Update tests to use new Handler(deps) pattern

This demonstrates the migration pattern for additional tool files.

Co-authored-by: Adam Holt <omgitsads@users.noreply.github.com>

* Migrate context_tools to new ServerTool pattern (#1590)

* refactor(search): migrate search tools to new ServerTool pattern

Migrate search.go tools (SearchRepositories, SearchCode, SearchUsers,
SearchOrgs) to use the new NewTool helper and ToolDependencies pattern.

- Functions now take only TranslationHelperFunc and return ServerTool
- Handler generation uses ToolDependencies for typed access to clients
- Update tools.go call sites to remove getClient parameter
- Update tests to use new Handler(deps) pattern

This demonstrates the migration pattern for additional tool files.

Co-authored-by: Adam Holt <oholt@github.com>

* Migrate context_tools to new ServerTool pattern

Convert GetMe, GetTeams, and GetTeamMembers to use the new typed
dependency injection pattern:
- Functions now take only translations helper, return toolsets.ServerTool
- Handler is generated lazily via deps.GetClient/deps.GetGQLClient
- Tests updated to use serverTool.Handler(deps) pattern
- Fixed error return pattern to return nil for Go error (via result.IsError)

Co-authored-by: Adam Holt <omgitsads@users.noreply.github.com>

* refactor(gists): migrate gists.go to NewTool pattern (#1591)

* Migrate context_tools to new ServerTool pattern

Convert GetMe, GetTeams, and GetTeamMembers to use the new typed
dependency injection pattern:
- Functions now take only translations helper, return toolsets.ServerTool
- Handler is generated lazily via deps.GetClient/deps.GetGQLClient
- Tests updated to use serverTool.Handler(deps) pattern
- Fixed error return pattern to return nil for Go error (via result.IsError)

Co-authored-by: Adam Holt <oholt@github.com>

* refactor(gists): migrate gists.go to NewTool pattern

Convert all gist tools (ListGists, GetGist, CreateGist, UpdateGist)
to use the new NewTool helper with ToolDependencies injection.

- Remove getClient parameter from function signatures
- Use deps.GetClient(ctx) inside handlers
- Standardize error handling with utils.NewToolResultErrorFromErr()
- Update all tests to use serverTool.Handler(deps) pattern

Co-authored-by: Adam Holt <omgitsads@users.noreply.github.com>

---------

Co-authored-by: Adam Holt <oholt@github.com>
Co-authored-by: Adam Holt <omgitsads@users.noreply.github.com>

---------

Co-authored-by: Adam Holt <oholt@github.com>
Co-authored-by: Adam Holt <omgitsads@users.noreply.github.com>

* refactor(notifications): migrate notifications.go to NewTool pattern (#1592)

* refactor(notifications): migrate notifications.go to NewTool pattern

Convert all notification tools to use the new NewTool helper with
ToolDependencies injection.

Co-authored-by: Adam Holt <omgitsads@users.noreply.github.com>

* Refactor repositories.go tools to use NewTool pattern with ToolDependencies

Convert all 18 tool functions in repositories.go to use the new NewTool helper
pattern with typed ToolDependencies, isolating type assertions to a single
location and improving code maintainability.

Functions converted:
- GetCommit, ListCommits, ListBranches
- CreateOrUpdateFile, CreateRepository, GetFileContents
- ForkRepository, DeleteFile, CreateBranch, PushFiles
- ListTags, GetTag, ListReleases, GetLatestRelease, GetReleaseByTag
- ListStarredRepositories, StarRepository, UnstarRepository

This is part of a stacked PR series to systematically migrate all tool
files to the new pattern.

Co-authored-by: Adam Holt <omgitsads@users.noreply.github.com>

* refactor(issues): migrate issues.go to NewTool pattern

Convert all 8 tool functions in issues.go to use the new NewTool
helper pattern which standardizes dependency injection:

- IssueRead: GetClient, GetGQLClient, RepoAccessCache, Flags
- ListIssueTypes: GetClient
- AddIssueComment: GetClient
- SubIssueWrite: GetClient
- SearchIssues: GetClient
- IssueWrite: GetClient, GetGQLClient
- ListIssues: GetGQLClient
- AssignCopilotToIssue: GetGQLClient

Updated tools.go to use direct function calls instead of
NewServerToolLegacy wrappers. Updated all tests in issues_test.go
to use the new ToolDependencies pattern and Handler() method.

Co-authored-by: Adam Holt <omgitsads@users.noreply.github.com>

* refactor(pullrequests): convert PR tools to NewTool pattern

Convert all 10 pull request tool functions to use the NewTool
pattern with ToolDependencies injection:
- PullRequestRead
- CreatePullRequest
- UpdatePullRequest
- ListPullRequests
- MergePullRequest
- SearchPullRequests
- UpdatePullRequestBranch
- PullRequestReviewWrite
- AddCommentToPendingReview
- RequestCopilotReview

Update tools.go to use direct function calls (removing
NewServerToolLegacy wrappers) for PR functions.

Update all tests in pullrequests_test.go to use the new
handler pattern with deps and 2-value return.

Co-authored-by: Adam Holt <omgitsads@users.noreply.github.com>

* Refactor actions.go to use NewTool pattern

Convert all 14 tool functions in actions.go to use the NewTool pattern with
ToolDependencies for dependency injection. This is part of a broader effort
to standardize the tool implementation pattern across the codebase.

Changes:
- ListWorkflows, ListWorkflowRuns, RunWorkflow, GetWorkflowRun
- GetWorkflowRunLogs, ListWorkflowJobs, GetJobLogs
- RerunWorkflowRun, RerunFailedJobs, CancelWorkflowRun
- ListWorkflowRunArtifacts, DownloadWorkflowRunArtifact
- DeleteWorkflowRunLogs, GetWorkflowRunUsage

The new pattern:
- Takes only translations.TranslationHelperFunc as parameter
- Returns toolsets.ServerTool with Tool and Handler
- Handler receives ToolDependencies for client access
- Enables better testability and consistent interface

Co-authored-by: Adam Holt <omgitsads@users.noreply.github.com>

* refactor(git): migrate GetRepositoryTree to NewTool pattern

* refactor(security): migrate code_scanning, secret_scanning, dependabot to NewTool pattern

Co-authored-by: Adam Holt <omgitsads@users.noreply.github.com>

* refactor(discussions): migrate to NewTool pattern

Co-authored-by: Adam Holt <omgitsads@users.noreply.github.com>

* Refactor security_advisories tools to use NewTool pattern

Convert 4 functions from NewServerToolLegacy wrapper to NewTool:
- ListGlobalSecurityAdvisories
- GetGlobalSecurityAdvisory
- ListRepositorySecurityAdvisories
- ListOrgRepositorySecurityAdvisories

Update tools.go toolset registration and tests.

Co-authored-by: Adam Holt <omgitsads@users.noreply.github.com>

* refactor: convert projects, labels, and dynamic_tools to NewTool pattern

This PR converts projects.go, labels.go, and dynamic_tools.go from the
legacy NewServerToolLegacy wrapper pattern to the new NewTool pattern with
proper ToolDependencies.

Changes:
- projects.go: Convert all 9 project functions to use NewTool with
  ToolHandlerFor[map[string]any, any] and 3-return-value handlers
- projects_test.go: Update tests to use new serverTool.Handler(deps) pattern
- labels.go: Convert GetLabel, ListLabels, and LabelWrite to NewTool pattern
- labels_test.go: Update tests to use new pattern
- dynamic_tools.go: Refactor functions to return ServerTool directly
  (using NewServerToolLegacy internally since they have special dependencies)
- tools.go: Remove NewServerToolLegacy wrappers for dynamic tools registration

Co-authored-by: Adam Holt <omgitsads@users.noreply.github.com>

* Add --features CLI flag for feature flag support

Add CLI flag and config support for feature flags in the local server:

- Add --features flag to main.go (StringSlice, comma-separated)
- Add EnabledFeatures field to StdioServerConfig and MCPServerConfig
- Create createFeatureChecker() that builds a set from enabled features
- Wire WithFeatureChecker() into the toolset group filter chain

This enables tools/resources/prompts that have FeatureFlagEnable set to
a flag name that is passed via --features. The checker uses a simple
set membership test for O(1) lookup.

Usage:
  github-mcp-server stdio --features=my_feature,another_feature
  GITHUB_FEATURES=my_feature github-mcp-server stdio

* Add validation tests for tools, resources, and prompts metadata

This commit adds comprehensive validation tests to ensure all MCP items
have required metadata:

- TestAllToolsHaveRequiredMetadata: Validates Toolset.ID and Annotations
- TestAllToolsHaveValidToolsetID: Ensures toolsets are in AvailableToolsets()
- TestAllResourcesHaveRequiredMetadata: Validates resource metadata
- TestAllPromptsHaveRequiredMetadata: Validates prompt metadata
- TestToolReadOnlyHintConsistency: Validates IsReadOnly() matches annotation
- TestNoDuplicate*Names: Ensures unique names across tools/resources/prompts
- TestAllToolsHaveHandlerFunc: Ensures all tools have handlers
- TestDefaultToolsetsAreValid: Validates default toolset IDs
- TestToolsetMetadataConsistency: Ensures consistent descriptions per toolset

Also fixes a bug discovered by these tests: ToolsetMetadataGit was defined
but not added to AvailableToolsets(), causing get_repository_tree to have
an invalid toolset ID.

* Fix default toolsets behavior when not in dynamic mode

When no toolsets are specified and dynamic mode is disabled, the server
should use the default toolsets. The bug was introduced when adding
dynamic toolsets support:

1. CleanToolsets(nil) was converting nil to empty slice
2. Empty slice passed to WithToolsets means 'no toolsets'
3. This resulted in zero tools being registered

Fix: Preserve nil for non-dynamic mode (nil = use defaults in WithToolsets)
and only set empty slice when dynamic mode is enabled without explicit
toolsets.

* refactor: address PR review feedback for toolsets

- Rename AddDeprecatedToolAliases to WithDeprecatedToolAliases for
  immutable filter chain consistency (returns new ToolsetGroup)
- Remove unused mockGetRawClient from generate_docs.go (use nil instead)
- Remove legacy ServerTool functions (NewServerToolLegacy and
  NewServerToolFromHandlerLegacy) - no usages
- Add panic in Handler()/RegisterFunc() when HandlerFunc is nil
- Add HasHandler() method for checking if tool has a handler
- Add tests for HasHandler and nil handler panic behavior
- Update all tests to use new WithDeprecatedToolAliases pattern

* refactor: Apply HandlerFunc pattern to resources for stateless NewToolsetGroup

This change applies the same HandlerFunc pattern used by tools to resources,
allowing NewToolsetGroup to be fully stateless (only requiring translations).

Key changes:
- Add ResourceHandlerFunc type to toolsets package
- Update ServerResourceTemplate to use HandlerFunc instead of direct Handler
- Add HasHandler() and Handler(deps) methods to ServerResourceTemplate
- Update RegisterResourceTemplates to take deps parameter
- Refactor repository resource definitions to use HandlerFunc pattern
- Make AllResources(t) stateless (only takes translations)
- Make NewToolsetGroup(t) stateless (only takes translations)
- Update generate_docs.go - no longer needs mock clients
- Update tests to use new patterns

This resolves the concern about mixed concerns in doc generation - the
toolset metadata and resource templates can now be created without any
runtime dependencies, while handlers are generated on-demand when deps
are provided during registration.

* refactor: simplify ForMCPRequest switch cases

* refactor(generate_docs): use strings.Builder and AllTools() iteration

- Replace slice joining with strings.Builder for all doc generation
- Iterate AllTools() directly instead of ToolsetIDs()/ToolsForToolset()
- Removes need for special 'dynamic' toolset handling (no tools = no output)
- Context toolset still explicitly handled for custom description
- Consistent pattern across generateToolsetsDoc, generateToolsDoc,
  generateRemoteToolsetsDoc, and generateDeprecatedAliasesTable

* feat(toolsets): add AvailableToolsets() with exclude filter

- Add AvailableToolsets() method that returns toolsets with actual tools
- Support variadic exclude parameter for filtering out specific toolsets
- Simplifies doc generation by removing manual skip logic
- Naturally excludes empty toolsets (like 'dynamic') without special cases

* refactor(generate_docs): hoist success logging to generateAllDocs

* refactor: consolidate toolset validation into ToolsetGroup

- Add Default field to ToolsetMetadata and derive defaults from metadata
- Move toolset validation into WithToolsets (trims whitespace, dedupes, tracks unrecognized)
- Add UnrecognizedToolsets() method for warning about typos
- Add DefaultToolsetIDs() method to derive defaults from metadata
- Remove redundant functions: CleanToolsets, GetValidToolsetIDs, AvailableToolsets, GetDefaultToolsetIDs
- Update DynamicTools to take ToolsetGroup for schema enum generation
- Add stubTranslator for cases needing ToolsetGroup without translations

This eliminates hardcoded toolset lists - everything is now derived from
the actual registered tools and their metadata.

* refactor: rename toolsets package to registry with builder pattern

- Rename pkg/toolsets to pkg/registry (better reflects its purpose)
- Split monolithic toolsets.go into focused files:
  - registry.go: Core Registry struct and MCP methods
  - builder.go: Builder pattern for creating Registry instances
  - filters.go: All filtering logic (toolsets, read-only, feature flags)
  - resources.go: ServerResourceTemplate type
  - prompts.go: ServerPrompt type
  - errors.go: Error types
  - server_tool.go: ServerTool and ToolsetMetadata (existing)
- Fix lint: Rename RegistryBuilder to Builder (avoid stuttering)
- Update all imports across ~45 files

This refactoring improves code organization and makes the registry's
purpose clearer. The builder pattern provides a clean API:

  reg := registry.NewBuilder().
      SetTools(tools).
      WithReadOnly(true).
      WithToolsets([]string{"repos"}).
      Build()

* fix: remove unnecessary type arguments in helper_test.go

* fix: restore correct behavior for --tools and --toolsets flags

Two behavioral regressions were fixed in resolveEnabledToolsets():

1. When --tools=X is used without --toolsets, the server should only
   register the specified tools, not the default toolsets. Now returns
   an empty slice instead of nil when EnabledTools is set.

2. When --toolsets=all --dynamic-toolsets is used, the 'all' and 'default'
   pseudo-toolsets should be removed so only the dynamic management tools
   are registered. This matches the original pre-refactor behavior.

* Move labels tools to issues toolset

Labels are closely related to issues - you add labels to issues,
search issues by label, etc. Keeping them in a separate toolset
required users to explicitly enable 'labels' to get this functionality.

Moving to issues toolset makes labels available by default since
issues is a default toolset.

* Restore labels toolset with get_label in both issues and labels

This restores conformance with the original behavior where:
- get_label is in issues toolset (read-only label access for issue workflows)
- get_label, list_label, label_write are in labels toolset (full management)

The duplicate get_label registration is intentional - it was in both toolsets
in the original implementation. Added test exception to allow this case.

* Fix instruction generation and capability advertisement

- Expand nil toolsets to default IDs before GenerateInstructions
  (nil means 'use defaults' in registry but instructions need actual names)
- Remove unconditional HasTools/HasResources/HasPrompts=true in NewServer
  (let SDK determine capabilities based on registered items, matching main)

* Add tests for dynamic toolset management tools

Tests cover:
- list_available_toolsets: verifies toolsets are listed with enabled status
- get_toolset_tools: verifies tools can be retrieved for a toolset
- enable_toolset: verifies toolset can be enabled and marked as enabled
- enable_toolset invalid: verifies proper error for non-existent toolset
- toolsets enum: verifies tools have proper enum values in schema

* Advertise all capabilities in dynamic toolsets mode

In dynamic mode, explicitly set HasTools/HasResources/HasPrompts=true
since toolsets with those capabilities can be enabled at runtime.
This ensures clients know the server supports these features even
when no tools/resources/prompts are initially registered.

* Improve conformance test with dynamic tool calls and JSON normalization

- Add dynamic tool call testing (list_available_toolsets, get_toolset_tools, enable_toolset)
- Parse and sort embedded JSON in text fields for proper comparison
- Separate progress output (stderr) from summary (stdout) for CI
- Add test type field to distinguish standard vs dynamic tests

* Add conformance-report to .gitignore

* Add conformance test CI workflow

- Runs on pull requests to main
- Compares PR branch against merge-base with origin/main
- Outputs full conformance report to GitHub Actions Job Summary
- Uploads detailed report as artifact for deeper investigation
- Does not fail the build on differences (may be intentional)

* Add map indexes for O(1) lookups in Registry

Address review feedback to use maps for collections. Added lookup maps
(toolsByName, resourcesByURI, promptsByName) while keeping slices for
ordered iteration. This provides O(1) lookup for:

- FindToolByName
- filterToolsByName (used by ForMCPRequest)
- filterResourcesByURI
- filterPromptsByName

Maps are built once during Build() and shared in ForMCPRequest copies.

* perf(registry): O(1) HasToolset lookup via pre-computed set

Add toolsetIDSet (map[ToolsetID]bool) to Registry for O(1) HasToolset lookups.
Previously HasToolset iterated through all tools, resourceTemplates, and prompts
to check if any belonged to the given toolset. Now it's a simple map lookup.

The set is populated during the single-pass processToolsets() call, which already
collected all valid toolset IDs. This adds zero new iteration - just returns the
existing validIDs map.

processToolsets now returns 6 values:
- enabledToolsets, unrecognized, toolsetIDs, toolsetIDSet, defaultToolsetIDs, descriptions

* simplify: remove lazy toolsByName map - not needed for actual use cases

FindToolByName() is only called once per request at most (to find toolset ID
for dynamic enablement). The SDK handles tool dispatch after registration.

A simple linear scan over ~90 tools is trivially fast and avoids:
- sync.Once complexity
- Map allocation
- Premature optimization for non-existent 'repeated lookups'

The pre-computed maps we keep (toolsetIDSet, etc.) are justified because
they're used for filtering logic that runs on every request.

* Add generic tool filtering mechanisms to registry package

- Add Enabled field to ServerTool for self-filtering based on context
- Add ToolFilter type and WithFilter method to Builder for cross-cutting filters
- Update isToolEnabled to check Enabled function and builder filters in order:
  1. Tool's Enabled function
  2. Feature flags (FeatureFlagEnable/FeatureFlagDisable)
  3. Read-only filter
  4. Builder filters
  5. Toolset/additional tools check
- Add FilteredTools method to Registry as alias for AvailableTools
- Add comprehensive tests for all new functionality
- All tests pass and linter is clean

Closes #1618

Co-authored-by: SamMorrowDrums <4811358+SamMorrowDrums@users.noreply.github.com>

* docs: improve filter evaluation order and FilteredTools documentation

- Add numbered filter evaluation order to isToolEnabled function doc
- Number inline comments for each filter step (1-5)
- Clarify FilteredTools error return is for future extensibility
- Document that library consumers may need to surface recoverable errors

Addresses review feedback on PR #1620

* Refactor GenerateToolsetsHelp() to use strings.Builder pattern

Co-authored-by: SamMorrowDrums <4811358+SamMorrowDrums@users.noreply.github.com>

---------

Co-authored-by: Adam Holt <omgitsads@users.noreply.github.com>
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: SamMorrowDrums <4811358+SamMorrowDrums@users.noreply.github.com>

* Port functional changes from main to registry pattern

Port three functional improvements from main branch:
- GraphQL review comments grouped as threads (#1554)
- get_file_contents description improvement (#1582)
- create_or_update_file SHA validation fix (#1621)

Adapted implementations to use the new registry pattern with:
- BaseDeps for providing clients via ToolDependencies interface
- deps.GetClient(ctx) and deps.GetGQLClient(ctx) patterns
- Updated tests to use GraphQL mocks for review comments
- Added SHA validation test cases for create_or_update_file

* fix(e2e): Fix e2e test compilation and add rate limit handling

- Fix DefaultToolsetIDs() type mismatch by using github.GetDefaultToolsetIDs()
- Add waitForRateLimit() to check and wait for rate limits before each test
- Add skip conditions for Copilot tests when Copilot isn't available
- Use multi-line file content in TestPullRequestReviewCommentSubmit for
  multi-line review comments to work correctly
- Improve error messages to include response details

* fix(gists): Use proper GitHub API error handling for observability

The gists.go file was using NewToolResultErrorFromErr for GitHub API
errors, which breaks the error middleware tracking that the remote
server uses for observability and incident detection.

Changed API errors (client.Gists.List, Get, Create, Edit) to use
ghErrors.NewGitHubAPIErrorResponse which properly:
- Records errors in the context for middleware access
- Preserves the response object for rate limit and status tracking
- Maintains consistency with other tools that use this pattern

This ensures production observability is maintained for Gist operations.

* chore: Update server.json schema to 2025-12-11

- Update schema URL to latest version (2025-12-11)
- Remove 'status' field (now managed by registry per 2025-09-29 changelog)

* fix(get_file_contents): Restore correct implementation from #1582

The refactor incorrectly restructured the GetFileContents logic:
- Move 'if rawOpts.SHA != "" { ref = rawOpts.SHA }' before GetContents call
- Always call GetContents first (not conditionally based on path suffix)
- Restore matchFiles helper function for proper fallback handling
- Use matchFiles when Contents API fails or raw API fails

This aligns with the improvements from PR #1582 that was merged into main.

* Rename registry to inventory in comments

Update remaining references to 'registry' in code comments to use
'inventory' consistently after the package rename.

---------

Co-authored-by: Adam Holt <4619+omgitsads@users.noreply.github.com>
Co-authored-by: Adam Holt <omgitsads@users.noreply.github.com>
Co-authored-by: Adam Holt <oholt@github.com>
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: SamMorrowDrums <4811358+SamMorrowDrums@users.noreply.github.com>
2025-12-17 09:56:24 +01:00

1402 lines
46 KiB
Go

package github
import (
"context"
"encoding/json"
"fmt"
"net/http"
"strconv"
"strings"
"github.com/github/github-mcp-server/internal/profiler"
buffer "github.com/github/github-mcp-server/pkg/buffer"
ghErrors "github.com/github/github-mcp-server/pkg/errors"
"github.com/github/github-mcp-server/pkg/inventory"
"github.com/github/github-mcp-server/pkg/translations"
"github.com/github/github-mcp-server/pkg/utils"
"github.com/google/go-github/v79/github"
"github.com/google/jsonschema-go/jsonschema"
"github.com/modelcontextprotocol/go-sdk/mcp"
)
const (
DescriptionRepositoryOwner = "Repository owner"
DescriptionRepositoryName = "Repository name"
)
// ListWorkflows creates a tool to list workflows in a repository
func ListWorkflows(t translations.TranslationHelperFunc) inventory.ServerTool {
return NewTool(
ToolsetMetadataActions,
mcp.Tool{
Name: "list_workflows",
Description: t("TOOL_LIST_WORKFLOWS_DESCRIPTION", "List workflows in a repository"),
Annotations: &mcp.ToolAnnotations{
Title: t("TOOL_LIST_WORKFLOWS_USER_TITLE", "List workflows"),
ReadOnlyHint: true,
},
InputSchema: WithPagination(&jsonschema.Schema{
Type: "object",
Properties: map[string]*jsonschema.Schema{
"owner": {
Type: "string",
Description: DescriptionRepositoryOwner,
},
"repo": {
Type: "string",
Description: DescriptionRepositoryName,
},
},
Required: []string{"owner", "repo"},
}),
},
func(deps ToolDependencies) mcp.ToolHandlerFor[map[string]any, any] {
return func(ctx context.Context, _ *mcp.CallToolRequest, args map[string]any) (*mcp.CallToolResult, any, error) {
client, err := deps.GetClient(ctx)
if err != nil {
return utils.NewToolResultErrorFromErr("failed to get GitHub client", err), nil, nil
}
owner, err := RequiredParam[string](args, "owner")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
repo, err := RequiredParam[string](args, "repo")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
// Get optional pagination parameters
pagination, err := OptionalPaginationParams(args)
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
// Set up list options
opts := &github.ListOptions{
PerPage: pagination.PerPage,
Page: pagination.Page,
}
workflows, resp, err := client.Actions.ListWorkflows(ctx, owner, repo, opts)
if err != nil {
return nil, nil, fmt.Errorf("failed to list workflows: %w", err)
}
defer func() { _ = resp.Body.Close() }()
r, err := json.Marshal(workflows)
if err != nil {
return nil, nil, fmt.Errorf("failed to marshal response: %w", err)
}
return utils.NewToolResultText(string(r)), nil, nil
}
},
)
}
// ListWorkflowRuns creates a tool to list workflow runs for a specific workflow
func ListWorkflowRuns(t translations.TranslationHelperFunc) inventory.ServerTool {
return NewTool(
ToolsetMetadataActions,
mcp.Tool{
Name: "list_workflow_runs",
Description: t("TOOL_LIST_WORKFLOW_RUNS_DESCRIPTION", "List workflow runs for a specific workflow"),
Annotations: &mcp.ToolAnnotations{
Title: t("TOOL_LIST_WORKFLOW_RUNS_USER_TITLE", "List workflow runs"),
ReadOnlyHint: true,
},
InputSchema: WithPagination(&jsonschema.Schema{
Type: "object",
Properties: map[string]*jsonschema.Schema{
"owner": {
Type: "string",
Description: DescriptionRepositoryOwner,
},
"repo": {
Type: "string",
Description: DescriptionRepositoryName,
},
"workflow_id": {
Type: "string",
Description: "The workflow ID or workflow file name",
},
"actor": {
Type: "string",
Description: "Returns someone's workflow runs. Use the login for the user who created the workflow run.",
},
"branch": {
Type: "string",
Description: "Returns workflow runs associated with a branch. Use the name of the branch.",
},
"event": {
Type: "string",
Description: "Returns workflow runs for a specific event type",
Enum: []any{
"branch_protection_rule",
"check_run",
"check_suite",
"create",
"delete",
"deployment",
"deployment_status",
"discussion",
"discussion_comment",
"fork",
"gollum",
"issue_comment",
"issues",
"label",
"merge_group",
"milestone",
"page_build",
"public",
"pull_request",
"pull_request_review",
"pull_request_review_comment",
"pull_request_target",
"push",
"registry_package",
"release",
"repository_dispatch",
"schedule",
"status",
"watch",
"workflow_call",
"workflow_dispatch",
"workflow_run",
},
},
"status": {
Type: "string",
Description: "Returns workflow runs with the check run status",
Enum: []any{"queued", "in_progress", "completed", "requested", "waiting"},
},
},
Required: []string{"owner", "repo", "workflow_id"},
}),
},
func(deps ToolDependencies) mcp.ToolHandlerFor[map[string]any, any] {
return func(ctx context.Context, _ *mcp.CallToolRequest, args map[string]any) (*mcp.CallToolResult, any, error) {
client, err := deps.GetClient(ctx)
if err != nil {
return utils.NewToolResultErrorFromErr("failed to get GitHub client", err), nil, nil
}
owner, err := RequiredParam[string](args, "owner")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
repo, err := RequiredParam[string](args, "repo")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
workflowID, err := RequiredParam[string](args, "workflow_id")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
// Get optional filtering parameters
actor, err := OptionalParam[string](args, "actor")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
branch, err := OptionalParam[string](args, "branch")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
event, err := OptionalParam[string](args, "event")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
status, err := OptionalParam[string](args, "status")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
// Get optional pagination parameters
pagination, err := OptionalPaginationParams(args)
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
// Set up list options
opts := &github.ListWorkflowRunsOptions{
Actor: actor,
Branch: branch,
Event: event,
Status: status,
ListOptions: github.ListOptions{
PerPage: pagination.PerPage,
Page: pagination.Page,
},
}
workflowRuns, resp, err := client.Actions.ListWorkflowRunsByFileName(ctx, owner, repo, workflowID, opts)
if err != nil {
return nil, nil, fmt.Errorf("failed to list workflow runs: %w", err)
}
defer func() { _ = resp.Body.Close() }()
r, err := json.Marshal(workflowRuns)
if err != nil {
return nil, nil, fmt.Errorf("failed to marshal response: %w", err)
}
return utils.NewToolResultText(string(r)), nil, nil
}
},
)
}
// RunWorkflow creates a tool to run an Actions workflow
func RunWorkflow(t translations.TranslationHelperFunc) inventory.ServerTool {
return NewTool(
ToolsetMetadataActions,
mcp.Tool{
Name: "run_workflow",
Description: t("TOOL_RUN_WORKFLOW_DESCRIPTION", "Run an Actions workflow by workflow ID or filename"),
Annotations: &mcp.ToolAnnotations{
Title: t("TOOL_RUN_WORKFLOW_USER_TITLE", "Run workflow"),
ReadOnlyHint: false,
},
InputSchema: &jsonschema.Schema{
Type: "object",
Properties: map[string]*jsonschema.Schema{
"owner": {
Type: "string",
Description: DescriptionRepositoryOwner,
},
"repo": {
Type: "string",
Description: DescriptionRepositoryName,
},
"workflow_id": {
Type: "string",
Description: "The workflow ID (numeric) or workflow file name (e.g., main.yml, ci.yaml)",
},
"ref": {
Type: "string",
Description: "The git reference for the workflow. The reference can be a branch or tag name.",
},
"inputs": {
Type: "object",
Description: "Inputs the workflow accepts",
},
},
Required: []string{"owner", "repo", "workflow_id", "ref"},
},
},
func(deps ToolDependencies) mcp.ToolHandlerFor[map[string]any, any] {
return func(ctx context.Context, _ *mcp.CallToolRequest, args map[string]any) (*mcp.CallToolResult, any, error) {
client, err := deps.GetClient(ctx)
if err != nil {
return utils.NewToolResultErrorFromErr("failed to get GitHub client", err), nil, nil
}
owner, err := RequiredParam[string](args, "owner")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
repo, err := RequiredParam[string](args, "repo")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
workflowID, err := RequiredParam[string](args, "workflow_id")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
ref, err := RequiredParam[string](args, "ref")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
// Get optional inputs parameter
var inputs map[string]interface{}
if requestInputs, ok := args["inputs"]; ok {
if inputsMap, ok := requestInputs.(map[string]interface{}); ok {
inputs = inputsMap
}
}
event := github.CreateWorkflowDispatchEventRequest{
Ref: ref,
Inputs: inputs,
}
var resp *github.Response
var workflowType string
if workflowIDInt, parseErr := strconv.ParseInt(workflowID, 10, 64); parseErr == nil {
resp, err = client.Actions.CreateWorkflowDispatchEventByID(ctx, owner, repo, workflowIDInt, event)
workflowType = "workflow_id"
} else {
resp, err = client.Actions.CreateWorkflowDispatchEventByFileName(ctx, owner, repo, workflowID, event)
workflowType = "workflow_file"
}
if err != nil {
return nil, nil, fmt.Errorf("failed to run workflow: %w", err)
}
defer func() { _ = resp.Body.Close() }()
result := map[string]any{
"message": "Workflow run has been queued",
"workflow_type": workflowType,
"workflow_id": workflowID,
"ref": ref,
"inputs": inputs,
"status": resp.Status,
"status_code": resp.StatusCode,
}
r, err := json.Marshal(result)
if err != nil {
return nil, nil, fmt.Errorf("failed to marshal response: %w", err)
}
return utils.NewToolResultText(string(r)), nil, nil
}
},
)
}
// GetWorkflowRun creates a tool to get details of a specific workflow run
func GetWorkflowRun(t translations.TranslationHelperFunc) inventory.ServerTool {
return NewTool(
ToolsetMetadataActions,
mcp.Tool{
Name: "get_workflow_run",
Description: t("TOOL_GET_WORKFLOW_RUN_DESCRIPTION", "Get details of a specific workflow run"),
Annotations: &mcp.ToolAnnotations{
Title: t("TOOL_GET_WORKFLOW_RUN_USER_TITLE", "Get workflow run"),
ReadOnlyHint: true,
},
InputSchema: &jsonschema.Schema{
Type: "object",
Properties: map[string]*jsonschema.Schema{
"owner": {
Type: "string",
Description: DescriptionRepositoryOwner,
},
"repo": {
Type: "string",
Description: DescriptionRepositoryName,
},
"run_id": {
Type: "number",
Description: "The unique identifier of the workflow run",
},
},
Required: []string{"owner", "repo", "run_id"},
},
},
func(deps ToolDependencies) mcp.ToolHandlerFor[map[string]any, any] {
return func(ctx context.Context, _ *mcp.CallToolRequest, args map[string]any) (*mcp.CallToolResult, any, error) {
client, err := deps.GetClient(ctx)
if err != nil {
return utils.NewToolResultErrorFromErr("failed to get GitHub client", err), nil, nil
}
owner, err := RequiredParam[string](args, "owner")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
repo, err := RequiredParam[string](args, "repo")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
runIDInt, err := RequiredInt(args, "run_id")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
runID := int64(runIDInt)
workflowRun, resp, err := client.Actions.GetWorkflowRunByID(ctx, owner, repo, runID)
if err != nil {
return nil, nil, fmt.Errorf("failed to get workflow run: %w", err)
}
defer func() { _ = resp.Body.Close() }()
r, err := json.Marshal(workflowRun)
if err != nil {
return nil, nil, fmt.Errorf("failed to marshal response: %w", err)
}
return utils.NewToolResultText(string(r)), nil, nil
}
},
)
}
// GetWorkflowRunLogs creates a tool to download logs for a specific workflow run
func GetWorkflowRunLogs(t translations.TranslationHelperFunc) inventory.ServerTool {
return NewTool(
ToolsetMetadataActions,
mcp.Tool{
Name: "get_workflow_run_logs",
Description: t("TOOL_GET_WORKFLOW_RUN_LOGS_DESCRIPTION", "Download logs for a specific workflow run (EXPENSIVE: downloads ALL logs as ZIP. Consider using get_job_logs with failed_only=true for debugging failed jobs)"),
Annotations: &mcp.ToolAnnotations{
Title: t("TOOL_GET_WORKFLOW_RUN_LOGS_USER_TITLE", "Get workflow run logs"),
ReadOnlyHint: true,
},
InputSchema: &jsonschema.Schema{
Type: "object",
Properties: map[string]*jsonschema.Schema{
"owner": {
Type: "string",
Description: DescriptionRepositoryOwner,
},
"repo": {
Type: "string",
Description: DescriptionRepositoryName,
},
"run_id": {
Type: "number",
Description: "The unique identifier of the workflow run",
},
},
Required: []string{"owner", "repo", "run_id"},
},
},
func(deps ToolDependencies) mcp.ToolHandlerFor[map[string]any, any] {
return func(ctx context.Context, _ *mcp.CallToolRequest, args map[string]any) (*mcp.CallToolResult, any, error) {
client, err := deps.GetClient(ctx)
if err != nil {
return utils.NewToolResultErrorFromErr("failed to get GitHub client", err), nil, nil
}
owner, err := RequiredParam[string](args, "owner")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
repo, err := RequiredParam[string](args, "repo")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
runIDInt, err := RequiredInt(args, "run_id")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
runID := int64(runIDInt)
// Get the download URL for the logs
url, resp, err := client.Actions.GetWorkflowRunLogs(ctx, owner, repo, runID, 1)
if err != nil {
return nil, nil, fmt.Errorf("failed to get workflow run logs: %w", err)
}
defer func() { _ = resp.Body.Close() }()
// Create response with the logs URL and information
result := map[string]any{
"logs_url": url.String(),
"message": "Workflow run logs are available for download",
"note": "The logs_url provides a download link for the complete workflow run logs as a ZIP archive. You can download this archive to extract and examine individual job logs.",
"warning": "This downloads ALL logs as a ZIP file which can be large and expensive. For debugging failed jobs, consider using get_job_logs with failed_only=true and run_id instead.",
"optimization_tip": "Use: get_job_logs with parameters {run_id: " + fmt.Sprintf("%d", runID) + ", failed_only: true} for more efficient failed job debugging",
}
r, err := json.Marshal(result)
if err != nil {
return nil, nil, fmt.Errorf("failed to marshal response: %w", err)
}
return utils.NewToolResultText(string(r)), nil, nil
}
},
)
}
// ListWorkflowJobs creates a tool to list jobs for a specific workflow run
func ListWorkflowJobs(t translations.TranslationHelperFunc) inventory.ServerTool {
return NewTool(
ToolsetMetadataActions,
mcp.Tool{
Name: "list_workflow_jobs",
Description: t("TOOL_LIST_WORKFLOW_JOBS_DESCRIPTION", "List jobs for a specific workflow run"),
Annotations: &mcp.ToolAnnotations{
Title: t("TOOL_LIST_WORKFLOW_JOBS_USER_TITLE", "List workflow jobs"),
ReadOnlyHint: true,
},
InputSchema: WithPagination(&jsonschema.Schema{
Type: "object",
Properties: map[string]*jsonschema.Schema{
"owner": {
Type: "string",
Description: DescriptionRepositoryOwner,
},
"repo": {
Type: "string",
Description: DescriptionRepositoryName,
},
"run_id": {
Type: "number",
Description: "The unique identifier of the workflow run",
},
"filter": {
Type: "string",
Description: "Filters jobs by their completed_at timestamp",
Enum: []any{"latest", "all"},
},
},
Required: []string{"owner", "repo", "run_id"},
}),
},
func(deps ToolDependencies) mcp.ToolHandlerFor[map[string]any, any] {
return func(ctx context.Context, _ *mcp.CallToolRequest, args map[string]any) (*mcp.CallToolResult, any, error) {
client, err := deps.GetClient(ctx)
if err != nil {
return utils.NewToolResultErrorFromErr("failed to get GitHub client", err), nil, nil
}
owner, err := RequiredParam[string](args, "owner")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
repo, err := RequiredParam[string](args, "repo")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
runIDInt, err := RequiredInt(args, "run_id")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
runID := int64(runIDInt)
// Get optional filtering parameters
filter, err := OptionalParam[string](args, "filter")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
// Get optional pagination parameters
pagination, err := OptionalPaginationParams(args)
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
// Set up list options
opts := &github.ListWorkflowJobsOptions{
Filter: filter,
ListOptions: github.ListOptions{
PerPage: pagination.PerPage,
Page: pagination.Page,
},
}
jobs, resp, err := client.Actions.ListWorkflowJobs(ctx, owner, repo, runID, opts)
if err != nil {
return nil, nil, fmt.Errorf("failed to list workflow jobs: %w", err)
}
defer func() { _ = resp.Body.Close() }()
// Add optimization tip for failed job debugging
response := map[string]any{
"jobs": jobs,
"optimization_tip": "For debugging failed jobs, consider using get_job_logs with failed_only=true and run_id=" + fmt.Sprintf("%d", runID) + " to get logs directly without needing to list jobs first",
}
r, err := json.Marshal(response)
if err != nil {
return nil, nil, fmt.Errorf("failed to marshal response: %w", err)
}
return utils.NewToolResultText(string(r)), nil, nil
}
},
)
}
// GetJobLogs creates a tool to download logs for a specific workflow job or efficiently get all failed job logs for a workflow run
func GetJobLogs(t translations.TranslationHelperFunc) inventory.ServerTool {
return NewTool(
ToolsetMetadataActions,
mcp.Tool{
Name: "get_job_logs",
Description: t("TOOL_GET_JOB_LOGS_DESCRIPTION", "Download logs for a specific workflow job or efficiently get all failed job logs for a workflow run"),
Annotations: &mcp.ToolAnnotations{
Title: t("TOOL_GET_JOB_LOGS_USER_TITLE", "Get job logs"),
ReadOnlyHint: true,
},
InputSchema: &jsonschema.Schema{
Type: "object",
Properties: map[string]*jsonschema.Schema{
"owner": {
Type: "string",
Description: DescriptionRepositoryOwner,
},
"repo": {
Type: "string",
Description: DescriptionRepositoryName,
},
"job_id": {
Type: "number",
Description: "The unique identifier of the workflow job (required for single job logs)",
},
"run_id": {
Type: "number",
Description: "Workflow run ID (required when using failed_only)",
},
"failed_only": {
Type: "boolean",
Description: "When true, gets logs for all failed jobs in run_id",
},
"return_content": {
Type: "boolean",
Description: "Returns actual log content instead of URLs",
},
"tail_lines": {
Type: "number",
Description: "Number of lines to return from the end of the log",
Default: json.RawMessage(`500`),
},
},
Required: []string{"owner", "repo"},
},
},
func(deps ToolDependencies) mcp.ToolHandlerFor[map[string]any, any] {
return func(ctx context.Context, _ *mcp.CallToolRequest, args map[string]any) (*mcp.CallToolResult, any, error) {
client, err := deps.GetClient(ctx)
if err != nil {
return utils.NewToolResultErrorFromErr("failed to get GitHub client", err), nil, nil
}
owner, err := RequiredParam[string](args, "owner")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
repo, err := RequiredParam[string](args, "repo")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
// Get optional parameters
jobID, err := OptionalIntParam(args, "job_id")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
runID, err := OptionalIntParam(args, "run_id")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
failedOnly, err := OptionalParam[bool](args, "failed_only")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
returnContent, err := OptionalParam[bool](args, "return_content")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
tailLines, err := OptionalIntParam(args, "tail_lines")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
// Default to 500 lines if not specified
if tailLines == 0 {
tailLines = 500
}
// Validate parameters
if failedOnly && runID == 0 {
return utils.NewToolResultError("run_id is required when failed_only is true"), nil, nil
}
if !failedOnly && jobID == 0 {
return utils.NewToolResultError("job_id is required when failed_only is false"), nil, nil
}
if failedOnly && runID > 0 {
// Handle failed-only mode: get logs for all failed jobs in the workflow run
return handleFailedJobLogs(ctx, client, owner, repo, int64(runID), returnContent, tailLines, deps.GetContentWindowSize())
} else if jobID > 0 {
// Handle single job mode
return handleSingleJobLogs(ctx, client, owner, repo, int64(jobID), returnContent, tailLines, deps.GetContentWindowSize())
}
return utils.NewToolResultError("Either job_id must be provided for single job logs, or run_id with failed_only=true for failed job logs"), nil, nil
}
},
)
}
// handleFailedJobLogs gets logs for all failed jobs in a workflow run
func handleFailedJobLogs(ctx context.Context, client *github.Client, owner, repo string, runID int64, returnContent bool, tailLines int, contentWindowSize int) (*mcp.CallToolResult, any, error) {
// First, get all jobs for the workflow run
jobs, resp, err := client.Actions.ListWorkflowJobs(ctx, owner, repo, runID, &github.ListWorkflowJobsOptions{
Filter: "latest",
})
if err != nil {
return ghErrors.NewGitHubAPIErrorResponse(ctx, "failed to list workflow jobs", resp, err), nil, nil
}
defer func() { _ = resp.Body.Close() }()
// Filter for failed jobs
var failedJobs []*github.WorkflowJob
for _, job := range jobs.Jobs {
if job.GetConclusion() == "failure" {
failedJobs = append(failedJobs, job)
}
}
if len(failedJobs) == 0 {
result := map[string]any{
"message": "No failed jobs found in this workflow run",
"run_id": runID,
"total_jobs": len(jobs.Jobs),
"failed_jobs": 0,
}
r, _ := json.Marshal(result)
return utils.NewToolResultText(string(r)), nil, nil
}
// Collect logs for all failed jobs
var logResults []map[string]any
for _, job := range failedJobs {
jobResult, resp, err := getJobLogData(ctx, client, owner, repo, job.GetID(), job.GetName(), returnContent, tailLines, contentWindowSize)
if err != nil {
// Continue with other jobs even if one fails
jobResult = map[string]any{
"job_id": job.GetID(),
"job_name": job.GetName(),
"error": err.Error(),
}
// Enable reporting of status codes and error causes
_, _ = ghErrors.NewGitHubAPIErrorToCtx(ctx, "failed to get job logs", resp, err) // Explicitly ignore error for graceful handling
}
logResults = append(logResults, jobResult)
}
result := map[string]any{
"message": fmt.Sprintf("Retrieved logs for %d failed jobs", len(failedJobs)),
"run_id": runID,
"total_jobs": len(jobs.Jobs),
"failed_jobs": len(failedJobs),
"logs": logResults,
"return_format": map[string]bool{"content": returnContent, "urls": !returnContent},
}
r, err := json.Marshal(result)
if err != nil {
return nil, nil, fmt.Errorf("failed to marshal response: %w", err)
}
return utils.NewToolResultText(string(r)), nil, nil
}
// handleSingleJobLogs gets logs for a single job
func handleSingleJobLogs(ctx context.Context, client *github.Client, owner, repo string, jobID int64, returnContent bool, tailLines int, contentWindowSize int) (*mcp.CallToolResult, any, error) {
jobResult, resp, err := getJobLogData(ctx, client, owner, repo, jobID, "", returnContent, tailLines, contentWindowSize)
if err != nil {
return ghErrors.NewGitHubAPIErrorResponse(ctx, "failed to get job logs", resp, err), nil, nil
}
r, err := json.Marshal(jobResult)
if err != nil {
return nil, nil, fmt.Errorf("failed to marshal response: %w", err)
}
return utils.NewToolResultText(string(r)), nil, nil
}
// getJobLogData retrieves log data for a single job, either as URL or content
func getJobLogData(ctx context.Context, client *github.Client, owner, repo string, jobID int64, jobName string, returnContent bool, tailLines int, contentWindowSize int) (map[string]any, *github.Response, error) {
// Get the download URL for the job logs
url, resp, err := client.Actions.GetWorkflowJobLogs(ctx, owner, repo, jobID, 1)
if err != nil {
return nil, resp, fmt.Errorf("failed to get job logs for job %d: %w", jobID, err)
}
defer func() { _ = resp.Body.Close() }()
result := map[string]any{
"job_id": jobID,
}
if jobName != "" {
result["job_name"] = jobName
}
if returnContent {
// Download and return the actual log content
content, originalLength, httpResp, err := downloadLogContent(ctx, url.String(), tailLines, contentWindowSize) //nolint:bodyclose // Response body is closed in downloadLogContent, but we need to return httpResp
if err != nil {
// To keep the return value consistent wrap the response as a GitHub Response
ghRes := &github.Response{
Response: httpResp,
}
return nil, ghRes, fmt.Errorf("failed to download log content for job %d: %w", jobID, err)
}
result["logs_content"] = content
result["message"] = "Job logs content retrieved successfully"
result["original_length"] = originalLength
} else {
// Return just the URL
result["logs_url"] = url.String()
result["message"] = "Job logs are available for download"
result["note"] = "The logs_url provides a download link for the individual job logs in plain text format. Use return_content=true to get the actual log content."
}
return result, resp, nil
}
func downloadLogContent(ctx context.Context, logURL string, tailLines int, maxLines int) (string, int, *http.Response, error) {
prof := profiler.New(nil, profiler.IsProfilingEnabled())
finish := prof.Start(ctx, "log_buffer_processing")
httpResp, err := http.Get(logURL) //nolint:gosec
if err != nil {
return "", 0, httpResp, fmt.Errorf("failed to download logs: %w", err)
}
defer func() { _ = httpResp.Body.Close() }()
if httpResp.StatusCode != http.StatusOK {
return "", 0, httpResp, fmt.Errorf("failed to download logs: HTTP %d", httpResp.StatusCode)
}
bufferSize := tailLines
if bufferSize > maxLines {
bufferSize = maxLines
}
processedInput, totalLines, httpResp, err := buffer.ProcessResponseAsRingBufferToEnd(httpResp, bufferSize)
if err != nil {
return "", 0, httpResp, fmt.Errorf("failed to process log content: %w", err)
}
lines := strings.Split(processedInput, "\n")
if len(lines) > tailLines {
lines = lines[len(lines)-tailLines:]
}
finalResult := strings.Join(lines, "\n")
_ = finish(len(lines), int64(len(finalResult)))
return finalResult, totalLines, httpResp, nil
}
// RerunWorkflowRun creates a tool to re-run an entire workflow run
func RerunWorkflowRun(t translations.TranslationHelperFunc) inventory.ServerTool {
return NewTool(
ToolsetMetadataActions,
mcp.Tool{
Name: "rerun_workflow_run",
Description: t("TOOL_RERUN_WORKFLOW_RUN_DESCRIPTION", "Re-run an entire workflow run"),
Annotations: &mcp.ToolAnnotations{
Title: t("TOOL_RERUN_WORKFLOW_RUN_USER_TITLE", "Rerun workflow run"),
ReadOnlyHint: false,
},
InputSchema: &jsonschema.Schema{
Type: "object",
Properties: map[string]*jsonschema.Schema{
"owner": {
Type: "string",
Description: DescriptionRepositoryOwner,
},
"repo": {
Type: "string",
Description: DescriptionRepositoryName,
},
"run_id": {
Type: "number",
Description: "The unique identifier of the workflow run",
},
},
Required: []string{"owner", "repo", "run_id"},
},
},
func(deps ToolDependencies) mcp.ToolHandlerFor[map[string]any, any] {
return func(ctx context.Context, _ *mcp.CallToolRequest, args map[string]any) (*mcp.CallToolResult, any, error) {
client, err := deps.GetClient(ctx)
if err != nil {
return utils.NewToolResultErrorFromErr("failed to get GitHub client", err), nil, nil
}
owner, err := RequiredParam[string](args, "owner")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
repo, err := RequiredParam[string](args, "repo")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
runIDInt, err := RequiredInt(args, "run_id")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
runID := int64(runIDInt)
resp, err := client.Actions.RerunWorkflowByID(ctx, owner, repo, runID)
if err != nil {
return ghErrors.NewGitHubAPIErrorResponse(ctx, "failed to rerun workflow run", resp, err), nil, nil
}
defer func() { _ = resp.Body.Close() }()
result := map[string]any{
"message": "Workflow run has been queued for re-run",
"run_id": runID,
"status": resp.Status,
"status_code": resp.StatusCode,
}
r, err := json.Marshal(result)
if err != nil {
return nil, nil, fmt.Errorf("failed to marshal response: %w", err)
}
return utils.NewToolResultText(string(r)), nil, nil
}
},
)
}
// RerunFailedJobs creates a tool to re-run only the failed jobs in a workflow run
func RerunFailedJobs(t translations.TranslationHelperFunc) inventory.ServerTool {
return NewTool(
ToolsetMetadataActions,
mcp.Tool{
Name: "rerun_failed_jobs",
Description: t("TOOL_RERUN_FAILED_JOBS_DESCRIPTION", "Re-run only the failed jobs in a workflow run"),
Annotations: &mcp.ToolAnnotations{
Title: t("TOOL_RERUN_FAILED_JOBS_USER_TITLE", "Rerun failed jobs"),
ReadOnlyHint: false,
},
InputSchema: &jsonschema.Schema{
Type: "object",
Properties: map[string]*jsonschema.Schema{
"owner": {
Type: "string",
Description: DescriptionRepositoryOwner,
},
"repo": {
Type: "string",
Description: DescriptionRepositoryName,
},
"run_id": {
Type: "number",
Description: "The unique identifier of the workflow run",
},
},
Required: []string{"owner", "repo", "run_id"},
},
},
func(deps ToolDependencies) mcp.ToolHandlerFor[map[string]any, any] {
return func(ctx context.Context, _ *mcp.CallToolRequest, args map[string]any) (*mcp.CallToolResult, any, error) {
client, err := deps.GetClient(ctx)
if err != nil {
return utils.NewToolResultErrorFromErr("failed to get GitHub client", err), nil, nil
}
owner, err := RequiredParam[string](args, "owner")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
repo, err := RequiredParam[string](args, "repo")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
runIDInt, err := RequiredInt(args, "run_id")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
runID := int64(runIDInt)
resp, err := client.Actions.RerunFailedJobsByID(ctx, owner, repo, runID)
if err != nil {
return ghErrors.NewGitHubAPIErrorResponse(ctx, "failed to rerun failed jobs", resp, err), nil, nil
}
defer func() { _ = resp.Body.Close() }()
result := map[string]any{
"message": "Failed jobs have been queued for re-run",
"run_id": runID,
"status": resp.Status,
"status_code": resp.StatusCode,
}
r, err := json.Marshal(result)
if err != nil {
return nil, nil, fmt.Errorf("failed to marshal response: %w", err)
}
return utils.NewToolResultText(string(r)), nil, nil
}
},
)
}
// CancelWorkflowRun creates a tool to cancel a workflow run
func CancelWorkflowRun(t translations.TranslationHelperFunc) inventory.ServerTool {
return NewTool(
ToolsetMetadataActions,
mcp.Tool{
Name: "cancel_workflow_run",
Description: t("TOOL_CANCEL_WORKFLOW_RUN_DESCRIPTION", "Cancel a workflow run"),
Annotations: &mcp.ToolAnnotations{
Title: t("TOOL_CANCEL_WORKFLOW_RUN_USER_TITLE", "Cancel workflow run"),
ReadOnlyHint: false,
},
InputSchema: &jsonschema.Schema{
Type: "object",
Properties: map[string]*jsonschema.Schema{
"owner": {
Type: "string",
Description: DescriptionRepositoryOwner,
},
"repo": {
Type: "string",
Description: DescriptionRepositoryName,
},
"run_id": {
Type: "number",
Description: "The unique identifier of the workflow run",
},
},
Required: []string{"owner", "repo", "run_id"},
},
},
func(deps ToolDependencies) mcp.ToolHandlerFor[map[string]any, any] {
return func(ctx context.Context, _ *mcp.CallToolRequest, args map[string]any) (*mcp.CallToolResult, any, error) {
client, err := deps.GetClient(ctx)
if err != nil {
return utils.NewToolResultErrorFromErr("failed to get GitHub client", err), nil, nil
}
owner, err := RequiredParam[string](args, "owner")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
repo, err := RequiredParam[string](args, "repo")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
runIDInt, err := RequiredInt(args, "run_id")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
runID := int64(runIDInt)
resp, err := client.Actions.CancelWorkflowRunByID(ctx, owner, repo, runID)
if err != nil {
if _, ok := err.(*github.AcceptedError); !ok {
return ghErrors.NewGitHubAPIErrorResponse(ctx, "failed to cancel workflow run", resp, err), nil, nil
}
}
defer func() { _ = resp.Body.Close() }()
result := map[string]any{
"message": "Workflow run has been cancelled",
"run_id": runID,
"status": resp.Status,
"status_code": resp.StatusCode,
}
r, err := json.Marshal(result)
if err != nil {
return nil, nil, fmt.Errorf("failed to marshal response: %w", err)
}
return utils.NewToolResultText(string(r)), nil, nil
}
},
)
}
// ListWorkflowRunArtifacts creates a tool to list artifacts for a workflow run
func ListWorkflowRunArtifacts(t translations.TranslationHelperFunc) inventory.ServerTool {
return NewTool(
ToolsetMetadataActions,
mcp.Tool{
Name: "list_workflow_run_artifacts",
Description: t("TOOL_LIST_WORKFLOW_RUN_ARTIFACTS_DESCRIPTION", "List artifacts for a workflow run"),
Annotations: &mcp.ToolAnnotations{
Title: t("TOOL_LIST_WORKFLOW_RUN_ARTIFACTS_USER_TITLE", "List workflow artifacts"),
ReadOnlyHint: true,
},
InputSchema: WithPagination(&jsonschema.Schema{
Type: "object",
Properties: map[string]*jsonschema.Schema{
"owner": {
Type: "string",
Description: DescriptionRepositoryOwner,
},
"repo": {
Type: "string",
Description: DescriptionRepositoryName,
},
"run_id": {
Type: "number",
Description: "The unique identifier of the workflow run",
},
},
Required: []string{"owner", "repo", "run_id"},
}),
},
func(deps ToolDependencies) mcp.ToolHandlerFor[map[string]any, any] {
return func(ctx context.Context, _ *mcp.CallToolRequest, args map[string]any) (*mcp.CallToolResult, any, error) {
client, err := deps.GetClient(ctx)
if err != nil {
return utils.NewToolResultErrorFromErr("failed to get GitHub client", err), nil, nil
}
owner, err := RequiredParam[string](args, "owner")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
repo, err := RequiredParam[string](args, "repo")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
runIDInt, err := RequiredInt(args, "run_id")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
runID := int64(runIDInt)
// Get optional pagination parameters
pagination, err := OptionalPaginationParams(args)
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
// Set up list options
opts := &github.ListOptions{
PerPage: pagination.PerPage,
Page: pagination.Page,
}
artifacts, resp, err := client.Actions.ListWorkflowRunArtifacts(ctx, owner, repo, runID, opts)
if err != nil {
return ghErrors.NewGitHubAPIErrorResponse(ctx, "failed to list workflow run artifacts", resp, err), nil, nil
}
defer func() { _ = resp.Body.Close() }()
r, err := json.Marshal(artifacts)
if err != nil {
return nil, nil, fmt.Errorf("failed to marshal response: %w", err)
}
return utils.NewToolResultText(string(r)), nil, nil
}
},
)
}
// DownloadWorkflowRunArtifact creates a tool to download a workflow run artifact
func DownloadWorkflowRunArtifact(t translations.TranslationHelperFunc) inventory.ServerTool {
return NewTool(
ToolsetMetadataActions,
mcp.Tool{
Name: "download_workflow_run_artifact",
Description: t("TOOL_DOWNLOAD_WORKFLOW_RUN_ARTIFACT_DESCRIPTION", "Get download URL for a workflow run artifact"),
Annotations: &mcp.ToolAnnotations{
Title: t("TOOL_DOWNLOAD_WORKFLOW_RUN_ARTIFACT_USER_TITLE", "Download workflow artifact"),
ReadOnlyHint: true,
},
InputSchema: &jsonschema.Schema{
Type: "object",
Properties: map[string]*jsonschema.Schema{
"owner": {
Type: "string",
Description: DescriptionRepositoryOwner,
},
"repo": {
Type: "string",
Description: DescriptionRepositoryName,
},
"artifact_id": {
Type: "number",
Description: "The unique identifier of the artifact",
},
},
Required: []string{"owner", "repo", "artifact_id"},
},
},
func(deps ToolDependencies) mcp.ToolHandlerFor[map[string]any, any] {
return func(ctx context.Context, _ *mcp.CallToolRequest, args map[string]any) (*mcp.CallToolResult, any, error) {
client, err := deps.GetClient(ctx)
if err != nil {
return utils.NewToolResultErrorFromErr("failed to get GitHub client", err), nil, nil
}
owner, err := RequiredParam[string](args, "owner")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
repo, err := RequiredParam[string](args, "repo")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
artifactIDInt, err := RequiredInt(args, "artifact_id")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
artifactID := int64(artifactIDInt)
// Get the download URL for the artifact
url, resp, err := client.Actions.DownloadArtifact(ctx, owner, repo, artifactID, 1)
if err != nil {
return ghErrors.NewGitHubAPIErrorResponse(ctx, "failed to get artifact download URL", resp, err), nil, nil
}
defer func() { _ = resp.Body.Close() }()
// Create response with the download URL and information
result := map[string]any{
"download_url": url.String(),
"message": "Artifact is available for download",
"note": "The download_url provides a download link for the artifact as a ZIP archive. The link is temporary and expires after a short time.",
"artifact_id": artifactID,
}
r, err := json.Marshal(result)
if err != nil {
return nil, nil, fmt.Errorf("failed to marshal response: %w", err)
}
return utils.NewToolResultText(string(r)), nil, nil
}
},
)
}
// DeleteWorkflowRunLogs creates a tool to delete logs for a workflow run
func DeleteWorkflowRunLogs(t translations.TranslationHelperFunc) inventory.ServerTool {
return NewTool(
ToolsetMetadataActions,
mcp.Tool{
Name: "delete_workflow_run_logs",
Description: t("TOOL_DELETE_WORKFLOW_RUN_LOGS_DESCRIPTION", "Delete logs for a workflow run"),
Annotations: &mcp.ToolAnnotations{
Title: t("TOOL_DELETE_WORKFLOW_RUN_LOGS_USER_TITLE", "Delete workflow logs"),
ReadOnlyHint: false,
DestructiveHint: jsonschema.Ptr(true),
},
InputSchema: &jsonschema.Schema{
Type: "object",
Properties: map[string]*jsonschema.Schema{
"owner": {
Type: "string",
Description: DescriptionRepositoryOwner,
},
"repo": {
Type: "string",
Description: DescriptionRepositoryName,
},
"run_id": {
Type: "number",
Description: "The unique identifier of the workflow run",
},
},
Required: []string{"owner", "repo", "run_id"},
},
},
func(deps ToolDependencies) mcp.ToolHandlerFor[map[string]any, any] {
return func(ctx context.Context, _ *mcp.CallToolRequest, args map[string]any) (*mcp.CallToolResult, any, error) {
client, err := deps.GetClient(ctx)
if err != nil {
return utils.NewToolResultErrorFromErr("failed to get GitHub client", err), nil, nil
}
owner, err := RequiredParam[string](args, "owner")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
repo, err := RequiredParam[string](args, "repo")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
runIDInt, err := RequiredInt(args, "run_id")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
runID := int64(runIDInt)
resp, err := client.Actions.DeleteWorkflowRunLogs(ctx, owner, repo, runID)
if err != nil {
return ghErrors.NewGitHubAPIErrorResponse(ctx, "failed to delete workflow run logs", resp, err), nil, nil
}
defer func() { _ = resp.Body.Close() }()
result := map[string]any{
"message": "Workflow run logs have been deleted",
"run_id": runID,
"status": resp.Status,
"status_code": resp.StatusCode,
}
r, err := json.Marshal(result)
if err != nil {
return nil, nil, fmt.Errorf("failed to marshal response: %w", err)
}
return utils.NewToolResultText(string(r)), nil, nil
}
},
)
}
// GetWorkflowRunUsage creates a tool to get usage metrics for a workflow run
func GetWorkflowRunUsage(t translations.TranslationHelperFunc) inventory.ServerTool {
return NewTool(
ToolsetMetadataActions,
mcp.Tool{
Name: "get_workflow_run_usage",
Description: t("TOOL_GET_WORKFLOW_RUN_USAGE_DESCRIPTION", "Get usage metrics for a workflow run"),
Annotations: &mcp.ToolAnnotations{
Title: t("TOOL_GET_WORKFLOW_RUN_USAGE_USER_TITLE", "Get workflow usage"),
ReadOnlyHint: true,
},
InputSchema: &jsonschema.Schema{
Type: "object",
Properties: map[string]*jsonschema.Schema{
"owner": {
Type: "string",
Description: DescriptionRepositoryOwner,
},
"repo": {
Type: "string",
Description: DescriptionRepositoryName,
},
"run_id": {
Type: "number",
Description: "The unique identifier of the workflow run",
},
},
Required: []string{"owner", "repo", "run_id"},
},
},
func(deps ToolDependencies) mcp.ToolHandlerFor[map[string]any, any] {
return func(ctx context.Context, _ *mcp.CallToolRequest, args map[string]any) (*mcp.CallToolResult, any, error) {
client, err := deps.GetClient(ctx)
if err != nil {
return utils.NewToolResultErrorFromErr("failed to get GitHub client", err), nil, nil
}
owner, err := RequiredParam[string](args, "owner")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
repo, err := RequiredParam[string](args, "repo")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
runIDInt, err := RequiredInt(args, "run_id")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
runID := int64(runIDInt)
usage, resp, err := client.Actions.GetWorkflowRunUsageByID(ctx, owner, repo, runID)
if err != nil {
return ghErrors.NewGitHubAPIErrorResponse(ctx, "failed to get workflow run usage", resp, err), nil, nil
}
defer func() { _ = resp.Body.Close() }()
r, err := json.Marshal(usage)
if err != nil {
return nil, nil, fmt.Errorf("failed to marshal response: %w", err)
}
return utils.NewToolResultText(string(r)), nil, nil
}
},
)
}