Files
github--github-mcp-server/pkg/github/projects.go
T
Sam Morrow 10a0f98c15 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>
2025-12-16 21:53:05 +01:00

1110 lines
34 KiB
Go

package github
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
ghErrors "github.com/github/github-mcp-server/pkg/errors"
"github.com/github/github-mcp-server/pkg/registry"
"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 (
ProjectUpdateFailedError = "failed to update a project item"
ProjectAddFailedError = "failed to add a project item"
ProjectDeleteFailedError = "failed to delete a project item"
ProjectListFailedError = "failed to list project items"
MaxProjectsPerPage = 50
)
func ListProjects(t translations.TranslationHelperFunc) registry.ServerTool {
return NewTool(
ToolsetMetadataProjects,
mcp.Tool{
Name: "list_projects",
Description: t("TOOL_LIST_PROJECTS_DESCRIPTION", `List Projects for a user or organization`),
Annotations: &mcp.ToolAnnotations{
Title: t("TOOL_LIST_PROJECTS_USER_TITLE", "List projects"),
ReadOnlyHint: true,
},
InputSchema: &jsonschema.Schema{
Type: "object",
Properties: map[string]*jsonschema.Schema{
"owner_type": {
Type: "string",
Description: "Owner type",
Enum: []any{"user", "org"},
},
"owner": {
Type: "string",
Description: "If owner_type == user it is the handle for the GitHub user account. If owner_type == org it is the name of the organization. The name is not case sensitive.",
},
"query": {
Type: "string",
Description: `Filter projects by title text and open/closed state; permitted qualifiers: is:open, is:closed; examples: "roadmap is:open", "is:open feature planning".`,
},
"per_page": {
Type: "number",
Description: fmt.Sprintf("Results per page (max %d)", MaxProjectsPerPage),
},
"after": {
Type: "string",
Description: "Forward pagination cursor from previous pageInfo.nextCursor.",
},
"before": {
Type: "string",
Description: "Backward pagination cursor from previous pageInfo.prevCursor (rare).",
},
},
Required: []string{"owner_type", "owner"},
},
},
func(deps ToolDependencies) mcp.ToolHandlerFor[map[string]any, any] {
return func(ctx context.Context, _ *mcp.CallToolRequest, args map[string]any) (*mcp.CallToolResult, any, error) {
owner, err := RequiredParam[string](args, "owner")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
ownerType, err := RequiredParam[string](args, "owner_type")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
queryStr, err := OptionalParam[string](args, "query")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
pagination, err := extractPaginationOptionsFromArgs(args)
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
client, err := deps.GetClient(ctx)
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
var resp *github.Response
var projects []*github.ProjectV2
var queryPtr *string
if queryStr != "" {
queryPtr = &queryStr
}
minimalProjects := []MinimalProject{}
opts := &github.ListProjectsOptions{
ListProjectsPaginationOptions: pagination,
Query: queryPtr,
}
if ownerType == "org" {
projects, resp, err = client.Projects.ListOrganizationProjects(ctx, owner, opts)
} else {
projects, resp, err = client.Projects.ListUserProjects(ctx, owner, opts)
}
if err != nil {
return ghErrors.NewGitHubAPIErrorResponse(ctx,
"failed to list projects",
resp,
err,
), nil, nil
}
defer func() { _ = resp.Body.Close() }()
for _, project := range projects {
minimalProjects = append(minimalProjects, *convertToMinimalProject(project))
}
response := map[string]any{
"projects": minimalProjects,
"pageInfo": buildPageInfo(resp),
}
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
}
},
)
}
func GetProject(t translations.TranslationHelperFunc) registry.ServerTool {
return NewTool(
ToolsetMetadataProjects,
mcp.Tool{
Name: "get_project",
Description: t("TOOL_GET_PROJECT_DESCRIPTION", "Get Project for a user or org"),
Annotations: &mcp.ToolAnnotations{
Title: t("TOOL_GET_PROJECT_USER_TITLE", "Get project"),
ReadOnlyHint: true,
},
InputSchema: &jsonschema.Schema{
Type: "object",
Properties: map[string]*jsonschema.Schema{
"project_number": {
Type: "number",
Description: "The project's number",
},
"owner_type": {
Type: "string",
Description: "Owner type",
Enum: []any{"user", "org"},
},
"owner": {
Type: "string",
Description: "If owner_type == user it is the handle for the GitHub user account. If owner_type == org it is the name of the organization. The name is not case sensitive.",
},
},
Required: []string{"project_number", "owner_type", "owner"},
},
},
func(deps ToolDependencies) mcp.ToolHandlerFor[map[string]any, any] {
return func(ctx context.Context, _ *mcp.CallToolRequest, args map[string]any) (*mcp.CallToolResult, any, error) {
projectNumber, err := RequiredInt(args, "project_number")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
owner, err := RequiredParam[string](args, "owner")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
ownerType, err := RequiredParam[string](args, "owner_type")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
client, err := deps.GetClient(ctx)
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
var resp *github.Response
var project *github.ProjectV2
if ownerType == "org" {
project, resp, err = client.Projects.GetOrganizationProject(ctx, owner, projectNumber)
} else {
project, resp, err = client.Projects.GetUserProject(ctx, owner, projectNumber)
}
if err != nil {
return ghErrors.NewGitHubAPIErrorResponse(ctx,
"failed to get project",
resp,
err,
), nil, nil
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, nil, fmt.Errorf("failed to read response body: %w", err)
}
return utils.NewToolResultError(fmt.Sprintf("failed to get project: %s", string(body))), nil, nil
}
minimalProject := convertToMinimalProject(project)
r, err := json.Marshal(minimalProject)
if err != nil {
return nil, nil, fmt.Errorf("failed to marshal response: %w", err)
}
return utils.NewToolResultText(string(r)), nil, nil
}
},
)
}
func ListProjectFields(t translations.TranslationHelperFunc) registry.ServerTool {
return NewTool(
ToolsetMetadataProjects,
mcp.Tool{
Name: "list_project_fields",
Description: t("TOOL_LIST_PROJECT_FIELDS_DESCRIPTION", "List Project fields for a user or org"),
Annotations: &mcp.ToolAnnotations{
Title: t("TOOL_LIST_PROJECT_FIELDS_USER_TITLE", "List project fields"),
ReadOnlyHint: true,
},
InputSchema: &jsonschema.Schema{
Type: "object",
Properties: map[string]*jsonschema.Schema{
"owner_type": {
Type: "string",
Description: "Owner type",
Enum: []any{"user", "org"},
},
"owner": {
Type: "string",
Description: "If owner_type == user it is the handle for the GitHub user account. If owner_type == org it is the name of the organization. The name is not case sensitive.",
},
"project_number": {
Type: "number",
Description: "The project's number.",
},
"per_page": {
Type: "number",
Description: fmt.Sprintf("Results per page (max %d)", MaxProjectsPerPage),
},
"after": {
Type: "string",
Description: "Forward pagination cursor from previous pageInfo.nextCursor.",
},
"before": {
Type: "string",
Description: "Backward pagination cursor from previous pageInfo.prevCursor (rare).",
},
},
Required: []string{"owner_type", "owner", "project_number"},
},
},
func(deps ToolDependencies) mcp.ToolHandlerFor[map[string]any, any] {
return func(ctx context.Context, _ *mcp.CallToolRequest, args map[string]any) (*mcp.CallToolResult, any, error) {
owner, err := RequiredParam[string](args, "owner")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
ownerType, err := RequiredParam[string](args, "owner_type")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
projectNumber, err := RequiredInt(args, "project_number")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
pagination, err := extractPaginationOptionsFromArgs(args)
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
client, err := deps.GetClient(ctx)
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
var resp *github.Response
var projectFields []*github.ProjectV2Field
opts := &github.ListProjectsOptions{
ListProjectsPaginationOptions: pagination,
}
if ownerType == "org" {
projectFields, resp, err = client.Projects.ListOrganizationProjectFields(ctx, owner, projectNumber, opts)
} else {
projectFields, resp, err = client.Projects.ListUserProjectFields(ctx, owner, projectNumber, opts)
}
if err != nil {
return ghErrors.NewGitHubAPIErrorResponse(ctx,
"failed to list project fields",
resp,
err,
), nil, nil
}
defer func() { _ = resp.Body.Close() }()
response := map[string]any{
"fields": projectFields,
"pageInfo": buildPageInfo(resp),
}
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
}
},
)
}
func GetProjectField(t translations.TranslationHelperFunc) registry.ServerTool {
return NewTool(
ToolsetMetadataProjects,
mcp.Tool{
Name: "get_project_field",
Description: t("TOOL_GET_PROJECT_FIELD_DESCRIPTION", "Get Project field for a user or org"),
Annotations: &mcp.ToolAnnotations{
Title: t("TOOL_GET_PROJECT_FIELD_USER_TITLE", "Get project field"),
ReadOnlyHint: true,
},
InputSchema: &jsonschema.Schema{
Type: "object",
Properties: map[string]*jsonschema.Schema{
"owner_type": {
Type: "string",
Description: "Owner type",
Enum: []any{"user", "org"},
},
"owner": {
Type: "string",
Description: "If owner_type == user it is the handle for the GitHub user account. If owner_type == org it is the name of the organization. The name is not case sensitive.",
},
"project_number": {
Type: "number",
Description: "The project's number.",
},
"field_id": {
Type: "number",
Description: "The field's id.",
},
},
Required: []string{"owner_type", "owner", "project_number", "field_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) {
owner, err := RequiredParam[string](args, "owner")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
ownerType, err := RequiredParam[string](args, "owner_type")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
projectNumber, err := RequiredInt(args, "project_number")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
fieldID, err := RequiredBigInt(args, "field_id")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
client, err := deps.GetClient(ctx)
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
var resp *github.Response
var projectField *github.ProjectV2Field
if ownerType == "org" {
projectField, resp, err = client.Projects.GetOrganizationProjectField(ctx, owner, projectNumber, fieldID)
} else {
projectField, resp, err = client.Projects.GetUserProjectField(ctx, owner, projectNumber, fieldID)
}
if err != nil {
return ghErrors.NewGitHubAPIErrorResponse(ctx,
"failed to get project field",
resp,
err,
), nil, nil
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, nil, fmt.Errorf("failed to read response body: %w", err)
}
return utils.NewToolResultError(fmt.Sprintf("failed to get project field: %s", string(body))), nil, nil
}
r, err := json.Marshal(projectField)
if err != nil {
return nil, nil, fmt.Errorf("failed to marshal response: %w", err)
}
return utils.NewToolResultText(string(r)), nil, nil
}
},
)
}
func ListProjectItems(t translations.TranslationHelperFunc) registry.ServerTool {
return NewTool(
ToolsetMetadataProjects,
mcp.Tool{
Name: "list_project_items",
Description: t("TOOL_LIST_PROJECT_ITEMS_DESCRIPTION", `Search project items with advanced filtering`),
Annotations: &mcp.ToolAnnotations{
Title: t("TOOL_LIST_PROJECT_ITEMS_USER_TITLE", "List project items"),
ReadOnlyHint: true,
},
InputSchema: &jsonschema.Schema{
Type: "object",
Properties: map[string]*jsonschema.Schema{
"owner_type": {
Type: "string",
Description: "Owner type",
Enum: []any{"user", "org"},
},
"owner": {
Type: "string",
Description: "If owner_type == user it is the handle for the GitHub user account. If owner_type == org it is the name of the organization. The name is not case sensitive.",
},
"project_number": {
Type: "number",
Description: "The project's number.",
},
"query": {
Type: "string",
Description: `Query string for advanced filtering of project items using GitHub's project filtering syntax.`,
},
"per_page": {
Type: "number",
Description: fmt.Sprintf("Results per page (max %d)", MaxProjectsPerPage),
},
"after": {
Type: "string",
Description: "Forward pagination cursor from previous pageInfo.nextCursor.",
},
"before": {
Type: "string",
Description: "Backward pagination cursor from previous pageInfo.prevCursor (rare).",
},
"fields": {
Type: "array",
Description: "Field IDs to include (e.g. [\"102589\", \"985201\"]). CRITICAL: Always provide to get field values. Without this, only titles returned.",
Items: &jsonschema.Schema{
Type: "string",
},
},
},
Required: []string{"owner_type", "owner", "project_number"},
},
},
func(deps ToolDependencies) mcp.ToolHandlerFor[map[string]any, any] {
return func(ctx context.Context, _ *mcp.CallToolRequest, args map[string]any) (*mcp.CallToolResult, any, error) {
owner, err := RequiredParam[string](args, "owner")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
ownerType, err := RequiredParam[string](args, "owner_type")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
projectNumber, err := RequiredInt(args, "project_number")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
queryStr, err := OptionalParam[string](args, "query")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
fields, err := OptionalBigIntArrayParam(args, "fields")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
pagination, err := extractPaginationOptionsFromArgs(args)
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
client, err := deps.GetClient(ctx)
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
var resp *github.Response
var projectItems []*github.ProjectV2Item
var queryPtr *string
if queryStr != "" {
queryPtr = &queryStr
}
opts := &github.ListProjectItemsOptions{
Fields: fields,
ListProjectsOptions: github.ListProjectsOptions{
ListProjectsPaginationOptions: pagination,
Query: queryPtr,
},
}
if ownerType == "org" {
projectItems, resp, err = client.Projects.ListOrganizationProjectItems(ctx, owner, projectNumber, opts)
} else {
projectItems, resp, err = client.Projects.ListUserProjectItems(ctx, owner, projectNumber, opts)
}
if err != nil {
return ghErrors.NewGitHubAPIErrorResponse(ctx,
ProjectListFailedError,
resp,
err,
), nil, nil
}
defer func() { _ = resp.Body.Close() }()
response := map[string]any{
"items": projectItems,
"pageInfo": buildPageInfo(resp),
}
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
}
},
)
}
func GetProjectItem(t translations.TranslationHelperFunc) registry.ServerTool {
return NewTool(
ToolsetMetadataProjects,
mcp.Tool{
Name: "get_project_item",
Description: t("TOOL_GET_PROJECT_ITEM_DESCRIPTION", "Get a specific Project item for a user or org"),
Annotations: &mcp.ToolAnnotations{
Title: t("TOOL_GET_PROJECT_ITEM_USER_TITLE", "Get project item"),
ReadOnlyHint: true,
},
InputSchema: &jsonschema.Schema{
Type: "object",
Properties: map[string]*jsonschema.Schema{
"owner_type": {
Type: "string",
Description: "Owner type",
Enum: []any{"user", "org"},
},
"owner": {
Type: "string",
Description: "If owner_type == user it is the handle for the GitHub user account. If owner_type == org it is the name of the organization. The name is not case sensitive.",
},
"project_number": {
Type: "number",
Description: "The project's number.",
},
"item_id": {
Type: "number",
Description: "The item's ID.",
},
"fields": {
Type: "array",
Description: "Specific list of field IDs to include in the response (e.g. [\"102589\", \"985201\", \"169875\"]). If not provided, only the title field is included.",
Items: &jsonschema.Schema{
Type: "string",
},
},
},
Required: []string{"owner_type", "owner", "project_number", "item_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) {
owner, err := RequiredParam[string](args, "owner")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
ownerType, err := RequiredParam[string](args, "owner_type")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
projectNumber, err := RequiredInt(args, "project_number")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
itemID, err := RequiredBigInt(args, "item_id")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
fields, err := OptionalBigIntArrayParam(args, "fields")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
client, err := deps.GetClient(ctx)
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
var resp *github.Response
var projectItem *github.ProjectV2Item
var opts *github.GetProjectItemOptions
if len(fields) > 0 {
opts = &github.GetProjectItemOptions{
Fields: fields,
}
}
if ownerType == "org" {
projectItem, resp, err = client.Projects.GetOrganizationProjectItem(ctx, owner, projectNumber, itemID, opts)
} else {
projectItem, resp, err = client.Projects.GetUserProjectItem(ctx, owner, projectNumber, itemID, opts)
}
if err != nil {
return ghErrors.NewGitHubAPIErrorResponse(ctx,
"failed to get project item",
resp,
err,
), nil, nil
}
defer func() { _ = resp.Body.Close() }()
r, err := json.Marshal(projectItem)
if err != nil {
return nil, nil, fmt.Errorf("failed to marshal response: %w", err)
}
return utils.NewToolResultText(string(r)), nil, nil
}
},
)
}
func AddProjectItem(t translations.TranslationHelperFunc) registry.ServerTool {
return NewTool(
ToolsetMetadataProjects,
mcp.Tool{
Name: "add_project_item",
Description: t("TOOL_ADD_PROJECT_ITEM_DESCRIPTION", "Add a specific Project item for a user or org"),
Annotations: &mcp.ToolAnnotations{
Title: t("TOOL_ADD_PROJECT_ITEM_USER_TITLE", "Add project item"),
ReadOnlyHint: false,
},
InputSchema: &jsonschema.Schema{
Type: "object",
Properties: map[string]*jsonschema.Schema{
"owner_type": {
Type: "string",
Description: "Owner type",
Enum: []any{"user", "org"},
},
"owner": {
Type: "string",
Description: "If owner_type == user it is the handle for the GitHub user account. If owner_type == org it is the name of the organization. The name is not case sensitive.",
},
"project_number": {
Type: "number",
Description: "The project's number.",
},
"item_type": {
Type: "string",
Description: "The item's type, either issue or pull_request.",
Enum: []any{"issue", "pull_request"},
},
"item_id": {
Type: "number",
Description: "The numeric ID of the issue or pull request to add to the project.",
},
},
Required: []string{"owner_type", "owner", "project_number", "item_type", "item_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) {
owner, err := RequiredParam[string](args, "owner")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
ownerType, err := RequiredParam[string](args, "owner_type")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
projectNumber, err := RequiredInt(args, "project_number")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
itemID, err := RequiredBigInt(args, "item_id")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
itemType, err := RequiredParam[string](args, "item_type")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
if itemType != "issue" && itemType != "pull_request" {
return utils.NewToolResultError("item_type must be either 'issue' or 'pull_request'"), nil, nil
}
client, err := deps.GetClient(ctx)
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
newItem := &github.AddProjectItemOptions{
ID: itemID,
Type: toNewProjectType(itemType),
}
var resp *github.Response
var addedItem *github.ProjectV2Item
if ownerType == "org" {
addedItem, resp, err = client.Projects.AddOrganizationProjectItem(ctx, owner, projectNumber, newItem)
} else {
addedItem, resp, err = client.Projects.AddUserProjectItem(ctx, owner, projectNumber, newItem)
}
if err != nil {
return ghErrors.NewGitHubAPIErrorResponse(ctx,
ProjectAddFailedError,
resp,
err,
), nil, nil
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusCreated {
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, nil, fmt.Errorf("failed to read response body: %w", err)
}
return utils.NewToolResultError(fmt.Sprintf("%s: %s", ProjectAddFailedError, string(body))), nil, nil
}
r, err := json.Marshal(addedItem)
if err != nil {
return nil, nil, fmt.Errorf("failed to marshal response: %w", err)
}
return utils.NewToolResultText(string(r)), nil, nil
}
},
)
}
func UpdateProjectItem(t translations.TranslationHelperFunc) registry.ServerTool {
return NewTool(
ToolsetMetadataProjects,
mcp.Tool{
Name: "update_project_item",
Description: t("TOOL_UPDATE_PROJECT_ITEM_DESCRIPTION", "Update a specific Project item for a user or org"),
Annotations: &mcp.ToolAnnotations{
Title: t("TOOL_UPDATE_PROJECT_ITEM_USER_TITLE", "Update project item"),
ReadOnlyHint: false,
},
InputSchema: &jsonschema.Schema{
Type: "object",
Properties: map[string]*jsonschema.Schema{
"owner_type": {
Type: "string",
Description: "Owner type",
Enum: []any{"user", "org"},
},
"owner": {
Type: "string",
Description: "If owner_type == user it is the handle for the GitHub user account. If owner_type == org it is the name of the organization. The name is not case sensitive.",
},
"project_number": {
Type: "number",
Description: "The project's number.",
},
"item_id": {
Type: "number",
Description: "The unique identifier of the project item. This is not the issue or pull request ID.",
},
"updated_field": {
Type: "object",
Description: "Object consisting of the ID of the project field to update and the new value for the field. To clear the field, set value to null. Example: {\"id\": 123456, \"value\": \"New Value\"}",
},
},
Required: []string{"owner_type", "owner", "project_number", "item_id", "updated_field"},
},
},
func(deps ToolDependencies) mcp.ToolHandlerFor[map[string]any, any] {
return func(ctx context.Context, _ *mcp.CallToolRequest, args map[string]any) (*mcp.CallToolResult, any, error) {
owner, err := RequiredParam[string](args, "owner")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
ownerType, err := RequiredParam[string](args, "owner_type")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
projectNumber, err := RequiredInt(args, "project_number")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
itemID, err := RequiredBigInt(args, "item_id")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
rawUpdatedField, exists := args["updated_field"]
if !exists {
return utils.NewToolResultError("missing required parameter: updated_field"), nil, nil
}
fieldValue, ok := rawUpdatedField.(map[string]any)
if !ok || fieldValue == nil {
return utils.NewToolResultError("field_value must be an object"), nil, nil
}
updatePayload, err := buildUpdateProjectItem(fieldValue)
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
client, err := deps.GetClient(ctx)
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
var resp *github.Response
var updatedItem *github.ProjectV2Item
if ownerType == "org" {
updatedItem, resp, err = client.Projects.UpdateOrganizationProjectItem(ctx, owner, projectNumber, itemID, updatePayload)
} else {
updatedItem, resp, err = client.Projects.UpdateUserProjectItem(ctx, owner, projectNumber, itemID, updatePayload)
}
if err != nil {
return ghErrors.NewGitHubAPIErrorResponse(ctx,
ProjectUpdateFailedError,
resp,
err,
), nil, nil
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, nil, fmt.Errorf("failed to read response body: %w", err)
}
return utils.NewToolResultError(fmt.Sprintf("%s: %s", ProjectUpdateFailedError, string(body))), nil, nil
}
r, err := json.Marshal(updatedItem)
if err != nil {
return nil, nil, fmt.Errorf("failed to marshal response: %w", err)
}
return utils.NewToolResultText(string(r)), nil, nil
}
},
)
}
func DeleteProjectItem(t translations.TranslationHelperFunc) registry.ServerTool {
return NewTool(
ToolsetMetadataProjects,
mcp.Tool{
Name: "delete_project_item",
Description: t("TOOL_DELETE_PROJECT_ITEM_DESCRIPTION", "Delete a specific Project item for a user or org"),
Annotations: &mcp.ToolAnnotations{
Title: t("TOOL_DELETE_PROJECT_ITEM_USER_TITLE", "Delete project item"),
ReadOnlyHint: false,
},
InputSchema: &jsonschema.Schema{
Type: "object",
Properties: map[string]*jsonschema.Schema{
"owner_type": {
Type: "string",
Description: "Owner type",
Enum: []any{"user", "org"},
},
"owner": {
Type: "string",
Description: "If owner_type == user it is the handle for the GitHub user account. If owner_type == org it is the name of the organization. The name is not case sensitive.",
},
"project_number": {
Type: "number",
Description: "The project's number.",
},
"item_id": {
Type: "number",
Description: "The internal project item ID to delete from the project (not the issue or pull request ID).",
},
},
Required: []string{"owner_type", "owner", "project_number", "item_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) {
owner, err := RequiredParam[string](args, "owner")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
ownerType, err := RequiredParam[string](args, "owner_type")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
projectNumber, err := RequiredInt(args, "project_number")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
itemID, err := RequiredBigInt(args, "item_id")
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
client, err := deps.GetClient(ctx)
if err != nil {
return utils.NewToolResultError(err.Error()), nil, nil
}
var resp *github.Response
if ownerType == "org" {
resp, err = client.Projects.DeleteOrganizationProjectItem(ctx, owner, projectNumber, itemID)
} else {
resp, err = client.Projects.DeleteUserProjectItem(ctx, owner, projectNumber, itemID)
}
if err != nil {
return ghErrors.NewGitHubAPIErrorResponse(ctx,
ProjectDeleteFailedError,
resp,
err,
), nil, nil
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusNoContent {
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, nil, fmt.Errorf("failed to read response body: %w", err)
}
return utils.NewToolResultError(fmt.Sprintf("%s: %s", ProjectDeleteFailedError, string(body))), nil, nil
}
return utils.NewToolResultText("project item successfully deleted"), nil, nil
}
},
)
}
type pageInfo struct {
HasNextPage bool `json:"hasNextPage"`
HasPreviousPage bool `json:"hasPreviousPage"`
NextCursor string `json:"nextCursor,omitempty"`
PrevCursor string `json:"prevCursor,omitempty"`
}
func toNewProjectType(projType string) string {
switch strings.ToLower(projType) {
case "issue":
return "Issue"
case "pull_request":
return "PullRequest"
default:
return ""
}
}
// validateAndConvertToInt64 ensures the value is a number and converts it to int64.
func validateAndConvertToInt64(value any) (int64, error) {
switch v := value.(type) {
case float64:
// Validate that the float64 can be safely converted to int64
intVal := int64(v)
if float64(intVal) != v {
return 0, fmt.Errorf("value must be a valid integer (got %v)", v)
}
return intVal, nil
case int64:
return v, nil
case int:
return int64(v), nil
default:
return 0, fmt.Errorf("value must be a number (got %T)", v)
}
}
// buildUpdateProjectItem constructs UpdateProjectItemOptions from the input map.
func buildUpdateProjectItem(input map[string]any) (*github.UpdateProjectItemOptions, error) {
if input == nil {
return nil, fmt.Errorf("updated_field must be an object")
}
idField, ok := input["id"]
if !ok {
return nil, fmt.Errorf("updated_field.id is required")
}
fieldID, err := validateAndConvertToInt64(idField)
if err != nil {
return nil, fmt.Errorf("updated_field.id: %w", err)
}
valueField, ok := input["value"]
if !ok {
return nil, fmt.Errorf("updated_field.value is required")
}
payload := &github.UpdateProjectItemOptions{
Fields: []*github.UpdateProjectV2Field{{
ID: fieldID,
Value: valueField,
}},
}
return payload, nil
}
func buildPageInfo(resp *github.Response) pageInfo {
return pageInfo{
HasNextPage: resp.After != "",
HasPreviousPage: resp.Before != "",
NextCursor: resp.After,
PrevCursor: resp.Before,
}
}
func extractPaginationOptionsFromArgs(args map[string]any) (github.ListProjectsPaginationOptions, error) {
perPage, err := OptionalIntParamWithDefault(args, "per_page", MaxProjectsPerPage)
if err != nil {
return github.ListProjectsPaginationOptions{}, err
}
if perPage > MaxProjectsPerPage {
perPage = MaxProjectsPerPage
}
after, err := OptionalParam[string](args, "after")
if err != nil {
return github.ListProjectsPaginationOptions{}, err
}
before, err := OptionalParam[string](args, "before")
if err != nil {
return github.ListProjectsPaginationOptions{}, err
}
opts := github.ListProjectsPaginationOptions{
PerPage: &perPage,
}
// Only set After/Before if they have non-empty values
if after != "" {
opts.After = &after
}
if before != "" {
opts.Before = &before
}
return opts, nil
}