
| Remote Server | Local Server |
|---|
| Remote Server | Local Server |
|---|---|
| - -```json -{ - "type": "http", - "url": "https://api.githubcopilot.com/mcp/", - "headers": { - "X-MCP-Features": "remote_mcp_ui_apps" - } -} -``` - - | -- -```json -{ - "type": "stdio", - "command": "go", - "args": [ - "run", - "./cmd/github-mcp-server", - "stdio", - "--features=remote_mcp_ui_apps" - ], - "env": { - "GITHUB_PERSONAL_ACCESS_TOKEN": "${input:github_token}" - } -} -``` - - | -
content
" + } + calls := 0 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + calls++ + assert.Equal(t, "/api/v3/repos/o/r/issues/12/artifacts", r.URL.Path) + w.Header().Set("Content-Type", "application/json") + if method == "create" { + assert.Equal(t, http.MethodPost, r.Method) + var body map[string]string + require.NoError(t, json.NewDecoder(r.Body).Decode(&body)) + assert.Equal(t, map[string]string{"type": artifactType, "name": "Artifact", "body": inputBody}, body) + w.WriteHeader(http.StatusCreated) + require.NoError(t, json.NewEncoder(w).Encode(artifact)) + } else { + assert.Equal(t, http.MethodGet, r.Method) + assert.Equal(t, artifactType, r.URL.Query().Get("type")) + require.NoError(t, json.NewEncoder(w).Encode([]IssueArtifact{artifact})) + } + })) + defer server.Close() + client, err := gogithub.NewClient( + gogithub.WithHTTPClient(server.Client()), + gogithub.WithEnterpriseURLs(server.URL+"/", server.URL+"/"), + ) + require.NoError(t, err) + tool := IssueArtifactRead(translations.NullTranslationHelper) + args := map[string]any{"owner": "o", "repo": "r", "issue_number": 12, "method": method, "type": artifactType} + if method == "create" { + tool = IssueArtifactWrite(translations.NullTranslationHelper) + args["name"], args["body"] = "Artifact", inputBody + } + result := callArtifactTool(t, tool, BaseDeps{Client: client}, args) + require.False(t, result.IsError, "%s", getTextResult(t, result).Text) + assert.Equal(t, 1, calls) + var output IssueArtifactReadOutput + require.NoError(t, json.Unmarshal([]byte(getTextResult(t, result).Text), &output)) + if method == "create" { + require.NotNil(t, output.Artifact) + assert.Equal(t, artifact, *output.Artifact) + } else { + require.NotNil(t, output.List) + assert.Equal(t, []IssueArtifact{artifact}, output.List.Artifacts) + } + }) + } + } +} + +func TestIssueArtifactListPagination(t *testing.T) { + for _, withLink := range []bool{false, true} { + name := "without Link headers" + if withLink { + name = "with Link headers" + } + t.Run(name, func(t *testing.T) { + calls := 0 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + calls++ + assert.Equal(t, http.MethodGet, r.Method) + assert.Equal(t, "/api/v3/repos/o/r/issues/12/artifacts", r.URL.Path) + assert.Equal(t, "2", r.URL.Query().Get("per_page")) + w.Header().Set("Content-Type", "application/json") + switch r.URL.Query().Get("page") { + case "1": + if withLink { + w.Header().Set("Link", `; rel="next"`) + } + _, _ = w.Write([]byte(`[{"id":999,"number":3,"type":"plan","name":"First","body":"first"},{"id":1000,"number":4,"type":"generic","name":"Second","body":"second"}]`)) + case "2": + if withLink { + w.Header().Set("Link", `; rel="prev"`) + } + _, _ = w.Write([]byte(`[{"id":1001,"number":5,"type":"link","name":"Third","body":"third"}]`)) + default: + t.Errorf("unexpected page: %s", r.URL.Query().Get("page")) + w.WriteHeader(http.StatusBadRequest) + } + })) + defer server.Close() + client, err := gogithub.NewClient( + gogithub.WithHTTPClient(server.Client()), + gogithub.WithEnterpriseURLs(server.URL+"/", server.URL+"/"), + ) + require.NoError(t, err) + for page := 1; page <= 2; page++ { + result := callArtifactTool(t, IssueArtifactRead(translations.NullTranslationHelper), BaseDeps{Client: client}, + map[string]any{"owner": "o", "repo": "r", "issue_number": 12, "method": "list", "page": page, "perPage": 2}) + require.False(t, result.IsError, "%s", getTextResult(t, result).Text) + var output IssueArtifactReadOutput + require.NoError(t, json.Unmarshal([]byte(getTextResult(t, result).Text), &output)) + require.NotNil(t, output.List) + assert.Equal(t, page, output.List.Page) + assert.Equal(t, 2, output.List.PerPage) + assert.Len(t, output.List.Artifacts, 3-page) + assert.Equal(t, page, calls, "each tool call must fetch only the requested page") + } + }) + } +} + +func TestIssueArtifactFailures(t *testing.T) { + for index := range 5 { + tool, method := artifactTestOperation(index) + t.Run(method, func(t *testing.T) { + args := map[string]any{"owner": "o", "repo": "r", "issue_number": 12, "method": method} + switch method { + case "create": + args["name"], args["type"], args["body"] = "Plan", "plan", "" + case "update": + args["artifact_number"], args["body"] = 3, "" + case "get", "delete": + args["artifact_number"] = 3 + } + t.Run("lockdown", func(t *testing.T) { + result := callArtifactTool(t, tool, BaseDeps{Flags: FeatureFlags{LockdownMode: true}}, args) + assert.True(t, result.IsError) + assert.Contains(t, getTextResult(t, result).Text, "lockdown") + }) + for _, status := range []int{401, 403, 404, 422, 500} { + t.Run(http.StatusText(status), func(t *testing.T) { + calls := 0 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + calls++ + w.WriteHeader(status) + _, _ = w.Write([]byte(`{"message":"artifact access failed"}`)) + })) + defer server.Close() + client, err := gogithub.NewClient( + gogithub.WithHTTPClient(server.Client()), + gogithub.WithEnterpriseURLs(server.URL+"/", server.URL+"/"), + ) + require.NoError(t, err) + result := callArtifactTool(t, tool, BaseDeps{Client: client}, args) + assert.True(t, result.IsError) + assert.Contains(t, getTextResult(t, result).Text, "artifact") + assert.Equal(t, 1, calls, "requests must not be retried") + }) + } + }) + } +} diff --git a/pkg/github/issue_dependencies.go b/pkg/github/issue_dependencies.go index dc78c9eccc..19a3b7db82 100644 --- a/pkg/github/issue_dependencies.go +++ b/pkg/github/issue_dependencies.go @@ -7,12 +7,12 @@ import ( "net/http" "strings" - ghErrors "github.com/github/github-mcp-server/pkg/errors" - "github.com/github/github-mcp-server/pkg/inventory" - "github.com/github/github-mcp-server/pkg/scopes" - "github.com/github/github-mcp-server/pkg/translations" - "github.com/github/github-mcp-server/pkg/utils" - "github.com/google/go-github/v89/github" + ghErrors "github.com/github/github-mcp-server/v2/pkg/errors" + "github.com/github/github-mcp-server/v2/pkg/inventory" + "github.com/github/github-mcp-server/v2/pkg/scopes" + "github.com/github/github-mcp-server/v2/pkg/translations" + "github.com/github/github-mcp-server/v2/pkg/utils" + "github.com/google/go-github/v92/github" "github.com/google/jsonschema-go/jsonschema" "github.com/modelcontextprotocol/go-sdk/mcp" ) @@ -51,7 +51,7 @@ Options are: } WithPagination(schema) - st := NewTool( + st := NewToolWithSchemaOptions[IssueDependencyReadInput, *IssueDependencyReadOutput]( ToolsetMetadataIssues, mcp.Tool{ Name: "issue_dependency_read", @@ -60,32 +60,27 @@ Options are: Title: t("TOOL_ISSUE_DEPENDENCY_READ_USER_TITLE", "Read issue dependencies"), ReadOnlyHint: true, }, - InputSchema: schema, + InputSchema: schema, + OutputSchema: issueDependencyReadOutputSchema(), }, scopes.PublicRead(scopes.Repo), - func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, args map[string]any) (*mcp.CallToolResult, any, error) { - method, err := RequiredParam[string](args, "method") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil + inventory.TypedSchemaOptions{ValidationInputSchema: issuePaginationValidationSchema(schema), PreserveHandlerContent: true}, + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, input IssueDependencyReadInput) (*mcp.CallToolResult, *IssueDependencyReadOutput, error) { + method, owner, repo, issueNumber := input.Method, input.Owner, input.Repo, input.IssueNumber + if method == "" { + return utils.NewToolResultError("missing required parameter: method"), nil, nil } - owner, err := RequiredParam[string](args, "owner") - if err != nil { + if err := validateIssueCoordinate(owner, repo, issueNumber); 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 + page, perPage := input.Page, input.PerPage + if page == 0 { + page = 1 } - issueNumber, err := RequiredInt(args, "issue_number") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil + if perPage == 0 { + perPage = 30 } - - pagination, err := OptionalPaginationParams(args) - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - opts := &github.ListOptions{Page: pagination.Page, PerPage: pagination.PerPage} + opts := &github.ListOptions{Page: page, PerPage: perPage} client, err := deps.GetClient(ctx) if err != nil { @@ -94,70 +89,98 @@ Options are: switch method { case "get_blocked_by": - result, err := GetIssueBlockedBy(ctx, client, owner, repo, issueNumber, opts) - return result, nil, err + return getIssueBlockedByOutput(ctx, client, owner, repo, issueNumber, opts) case "get_blocking": - result, err := GetIssueBlocking(ctx, client, owner, repo, issueNumber, opts) - return result, nil, err + return getIssueBlockingOutput(ctx, client, owner, repo, issueNumber, opts) default: return utils.NewToolResultError(fmt.Sprintf("unknown method: %s", method)), nil, nil } - }) + }, normalizeIssueStrings([]string{"method", "owner", "repo"}, nil), + normalizeIssueIntegers([]string{"issue_number"}, []string{"page", "perPage"}), + normalizeTypedReadArguments(nil, false)) st.FeatureRule = featureEnabledRule(FeatureFlagIssueDependencies) return st } // GetIssueBlockedBy lists the issues that block the given issue. func GetIssueBlockedBy(ctx context.Context, client *github.Client, owner, repo string, issueNumber int, opts *github.ListOptions) (*mcp.CallToolResult, error) { + result, _, err := getIssueBlockedByOutput(ctx, client, owner, repo, issueNumber, opts) + return result, err +} + +func getIssueBlockedByOutput(ctx context.Context, client *github.Client, owner, repo string, issueNumber int, opts *github.ListOptions) (*mcp.CallToolResult, *IssueDependencyReadOutput, error) { issues, resp, err := client.Issues.ListBlockedBy(ctx, owner, repo, int64(issueNumber), opts) if err != nil { - return ghErrors.NewGitHubAPIErrorResponse(ctx, "failed to list blocked-by issues", resp, err), nil + return ghErrors.NewGitHubAPIErrorResponse(ctx, "failed to list blocked-by issues", 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, fmt.Errorf("failed to read response body: %w", err) + return nil, nil, fmt.Errorf("failed to read response body: %w", err) } - return ghErrors.NewGitHubAPIStatusErrorResponse(ctx, "failed to list blocked-by issues", resp, body), nil + return ghErrors.NewGitHubAPIStatusErrorResponse(ctx, "failed to list blocked-by issues", resp, body), nil, nil } - return dependencyReadResult(issues, resp), nil + output := dependencyReadOutput(issues, resp) + return dependencyReadTextResult(issues, resp), output, nil } // GetIssueBlocking lists the issues that the given issue blocks. func GetIssueBlocking(ctx context.Context, client *github.Client, owner, repo string, issueNumber int, opts *github.ListOptions) (*mcp.CallToolResult, error) { + result, _, err := getIssueBlockingOutput(ctx, client, owner, repo, issueNumber, opts) + return result, err +} + +func getIssueBlockingOutput(ctx context.Context, client *github.Client, owner, repo string, issueNumber int, opts *github.ListOptions) (*mcp.CallToolResult, *IssueDependencyReadOutput, error) { issues, resp, err := client.Issues.ListBlocking(ctx, owner, repo, int64(issueNumber), opts) if err != nil { - return ghErrors.NewGitHubAPIErrorResponse(ctx, "failed to list blocking issues", resp, err), nil + return ghErrors.NewGitHubAPIErrorResponse(ctx, "failed to list blocking issues", 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, fmt.Errorf("failed to read response body: %w", err) + return nil, nil, fmt.Errorf("failed to read response body: %w", err) } - return ghErrors.NewGitHubAPIStatusErrorResponse(ctx, "failed to list blocking issues", resp, body), nil + return ghErrors.NewGitHubAPIStatusErrorResponse(ctx, "failed to list blocking issues", resp, body), nil, nil } - return dependencyReadResult(issues, resp), nil + output := dependencyReadOutput(issues, resp) + return dependencyReadTextResult(issues, resp), output, nil } -// dependencyReadResult projects a list of related issues into the minimal +// dependencyReadOutput projects a list of related issues into the minimal // dependency shape and attaches page-based pagination info. -func dependencyReadResult(issues []*github.Issue, resp *github.Response) *mcp.CallToolResult { - refs := make([]MinimalIssueRef, 0, len(issues)) +func dependencyReadOutput(issues []*github.Issue, resp *github.Response) *IssueDependencyReadOutput { + refs := make([]MinimalIssueDependencyRef, 0, len(issues)) for _, issue := range issues { if issue == nil { continue } - refs = append(refs, issueToDependencyRef(issue)) + refs = append(refs, dependencyRefOutput(issueToDependencyRef(issue))) + } + return &IssueDependencyReadOutput{ + Issues: refs, + PageInfo: IssueDependencyPageInfo{ + HasNextPage: resp.NextPage != 0, + NextPage: resp.NextPage, + }, + } +} + +func dependencyReadTextResult(issues []*github.Issue, resp *github.Response) *mcp.CallToolResult { + refs := make([]MinimalIssueRef, 0, len(issues)) + for _, issue := range issues { + if issue != nil { + refs = append(refs, issueToDependencyRef(issue)) + } } - return MarshalledTextResult(map[string]any{ - "issues": refs, - "pageInfo": map[string]any{ - "hasNextPage": resp.NextPage != 0, - "nextPage": resp.NextPage, + return MarshalledTextResult(IssueDependencyReadLegacyOutput{ + Issues: refs, + PageInfo: IssueDependencyPageInfo{ + HasNextPage: resp.NextPage != 0, + NextPage: resp.NextPage, }, }) } @@ -189,7 +212,7 @@ func issueToDependencyRef(issue *github.Issue) MinimalIssueRef { // expressed as "the blocked issue is blocked_by the blocking issue", so both // directions are served by the same endpoint pair with the two issues swapped. func IssueDependencyWrite(t translations.TranslationHelperFunc) inventory.ServerTool { - st := NewTool( + st := NewToolWithSchemaOptions[IssueDependencyWriteInput, *IssueDependencyWriteOutput]( ToolsetMetadataIssues, mcp.Tool{ Name: "issue_dependency_write", @@ -248,41 +271,27 @@ Options are: }, Required: []string{"method", "type", "owner", "repo", "issue_number", "related_issue_number"}, }, + OutputSchema: issueDependencyWriteOutputSchema(), }, scopes.RequireAll(scopes.Repo), - func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, args map[string]any) (*mcp.CallToolResult, any, error) { - method, err := RequiredParam[string](args, "method") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - relationshipType, err := RequiredParam[string](args, "type") - 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 - } - repo, err := RequiredParam[string](args, "repo") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - issueNumber, err := RequiredInt(args, "issue_number") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil + inventory.TypedSchemaOptions{PreserveHandlerContent: true}, + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, input IssueDependencyWriteInput) (*mcp.CallToolResult, *IssueDependencyWriteOutput, error) { + method, relationshipType := input.Method, input.Type + if method == "" { + return utils.NewToolResultError("missing required parameter: method"), nil, nil } - relatedIssueNumber, err := RequiredInt(args, "related_issue_number") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil + if relationshipType == "" { + return utils.NewToolResultError("missing required parameter: type"), nil, nil } - relatedOwner, err := OptionalParam[string](args, "related_owner") - if err != nil { + owner, repo, issueNumber := input.Owner, input.Repo, input.IssueNumber + if err := validateIssueCoordinate(owner, repo, issueNumber); err != nil { return utils.NewToolResultError(err.Error()), nil, nil } - relatedRepo, err := OptionalParam[string](args, "related_repo") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil + relatedIssueNumber := input.RelatedIssueNumber + if relatedIssueNumber == 0 { + return utils.NewToolResultError("missing required parameter: related_issue_number"), nil, nil } + relatedOwner, relatedRepo := input.RelatedOwner, input.RelatedRepo if relatedOwner == "" { relatedOwner = owner } @@ -318,9 +327,9 @@ Options are: return utils.NewToolResultErrorFromErr("failed to get GitHub client", err), nil, nil } - result, err := writeIssueDependency(ctx, client, method, blocked, blocking) - return result, nil, err - }) + return writeIssueDependency(ctx, client, method, blocked, blocking) + }, normalizeIssueStrings([]string{"method", "type", "owner", "repo"}, []string{"related_owner", "related_repo"}), + normalizeIssueIntegers([]string{"issue_number", "related_issue_number"}, nil), normalizeIssueDependencyWriteArguments) st.FeatureRule = featureEnabledRule(FeatureFlagIssueDependencies) return st } @@ -334,12 +343,12 @@ type issueCoordinate struct { // writeIssueDependency resolves the blocking issue to its global database ID and // then adds or removes the blocked-by relationship on the blocked issue. -func writeIssueDependency(ctx context.Context, client *github.Client, method string, blocked, blocking issueCoordinate) (*mcp.CallToolResult, error) { +func writeIssueDependency(ctx context.Context, client *github.Client, method string, blocked, blocking issueCoordinate) (*mcp.CallToolResult, *IssueDependencyWriteOutput, error) { // The REST API identifies the blocking issue by its global database ID // (not its number), so resolve the number to an ID first. blockingIssue, resp, err := client.Issues.Get(ctx, blocking.owner, blocking.repo, blocking.number) if err != nil { - return ghErrors.NewGitHubAPIErrorResponse(ctx, "failed to resolve blocking issue", resp, err), nil + return ghErrors.NewGitHubAPIErrorResponse(ctx, "failed to resolve blocking issue", resp, err), nil, nil } _ = resp.Body.Close() blockingID := blockingIssue.GetID() @@ -348,41 +357,43 @@ func writeIssueDependency(ctx context.Context, client *github.Client, method str case "add": blockedIssue, opResp, err := client.Issues.AddBlockedBy(ctx, blocked.owner, blocked.repo, int64(blocked.number), github.IssueDependencyRequest{IssueID: blockingID}) if err != nil { - return ghErrors.NewGitHubAPIErrorResponse(ctx, "failed to add issue dependency", opResp, err), nil + return ghErrors.NewGitHubAPIErrorResponse(ctx, "failed to add issue dependency", opResp, err), nil, nil } defer func() { _ = opResp.Body.Close() }() if opResp.StatusCode != http.StatusCreated { body, readErr := io.ReadAll(opResp.Body) if readErr != nil { - return nil, fmt.Errorf("failed to read response body: %w", readErr) + return nil, nil, fmt.Errorf("failed to read response body: %w", readErr) } - return ghErrors.NewGitHubAPIStatusErrorResponse(ctx, "failed to add issue dependency", opResp, body), nil + return ghErrors.NewGitHubAPIStatusErrorResponse(ctx, "failed to add issue dependency", opResp, body), nil, nil } - return dependencyWriteResult("dependency added", blockedIssue, blockingIssue, blocked, blocking), nil + output := dependencyWriteOutput("dependency added", blockedIssue, blockingIssue, blocked, blocking) + return dependencyWriteTextResult("dependency added", blockedIssue, blockingIssue, blocked, blocking), output, nil case "remove": blockedIssue, opResp, err := client.Issues.RemoveBlockedBy(ctx, blocked.owner, blocked.repo, int64(blocked.number), blockingID) if err != nil { - return ghErrors.NewGitHubAPIErrorResponse(ctx, "failed to remove issue dependency", opResp, err), nil + return ghErrors.NewGitHubAPIErrorResponse(ctx, "failed to remove issue dependency", opResp, err), nil, nil } defer func() { _ = opResp.Body.Close() }() if opResp.StatusCode != http.StatusOK { body, readErr := io.ReadAll(opResp.Body) if readErr != nil { - return nil, fmt.Errorf("failed to read response body: %w", readErr) + return nil, nil, fmt.Errorf("failed to read response body: %w", readErr) } - return ghErrors.NewGitHubAPIStatusErrorResponse(ctx, "failed to remove issue dependency", opResp, body), nil + return ghErrors.NewGitHubAPIStatusErrorResponse(ctx, "failed to remove issue dependency", opResp, body), nil, nil } - return dependencyWriteResult("dependency removed", blockedIssue, blockingIssue, blocked, blocking), nil + output := dependencyWriteOutput("dependency removed", blockedIssue, blockingIssue, blocked, blocking) + return dependencyWriteTextResult("dependency removed", blockedIssue, blockingIssue, blocked, blocking), output, nil default: - return utils.NewToolResultError(fmt.Sprintf("unknown method: %s", method)), nil + return utils.NewToolResultError(fmt.Sprintf("unknown method: %s", method)), nil, nil } } -// dependencyWriteResult builds the minimal description of the affected issues. +// dependencyWriteOutput builds the minimal description of the affected issues. // The blocked issue comes from the mutation response and the blocking issue from // the earlier resolve; each falls back to its known coordinate when the API // response omits the repository URL. -func dependencyWriteResult(message string, blockedIssue, blockingIssue *github.Issue, blocked, blocking issueCoordinate) *mcp.CallToolResult { +func dependencyWriteOutput(message string, blockedIssue, blockingIssue *github.Issue, blocked, blocking issueCoordinate) *IssueDependencyWriteOutput { blockedRef := issueToDependencyRef(blockedIssue) if blockedRef.Repository == "" { blockedRef.Repository = blocked.owner + "/" + blocked.repo @@ -391,9 +402,23 @@ func dependencyWriteResult(message string, blockedIssue, blockingIssue *github.I if blockingRef.Repository == "" { blockingRef.Repository = blocking.owner + "/" + blocking.repo } - return MarshalledTextResult(map[string]any{ - "message": message, - "blocked_issue": blockedRef, - "blocking_issue": blockingRef, + return &IssueDependencyWriteOutput{ + BlockedIssue: dependencyRefOutput(blockedRef), BlockingIssue: dependencyRefOutput(blockingRef), Message: message, + } +} + +func dependencyWriteTextResult(message string, blockedIssue, blockingIssue *github.Issue, blocked, blocking issueCoordinate) *mcp.CallToolResult { + return MarshalledTextResult(IssueDependencyWriteLegacyOutput{ + BlockedIssue: issueToLegacyDependencyRef(blockedIssue, blocked), + BlockingIssue: issueToLegacyDependencyRef(blockingIssue, blocking), + Message: message, }) } + +func issueToLegacyDependencyRef(issue *github.Issue, coordinate issueCoordinate) MinimalIssueRef { + ref := issueToDependencyRef(issue) + if ref.Repository == "" { + ref.Repository = coordinate.owner + "/" + coordinate.repo + } + return ref +} diff --git a/pkg/github/issue_dependencies_test.go b/pkg/github/issue_dependencies_test.go index 35baa815ee..9d411b0153 100644 --- a/pkg/github/issue_dependencies_test.go +++ b/pkg/github/issue_dependencies_test.go @@ -7,9 +7,9 @@ import ( "strconv" "testing" - "github.com/github/github-mcp-server/internal/toolsnaps" - "github.com/github/github-mcp-server/pkg/inventory" - "github.com/github/github-mcp-server/pkg/translations" + "github.com/github/github-mcp-server/v2/internal/toolsnaps" + "github.com/github/github-mcp-server/v2/pkg/inventory" + "github.com/github/github-mcp-server/v2/pkg/translations" "github.com/google/jsonschema-go/jsonschema" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" diff --git a/pkg/github/issue_fields.go b/pkg/github/issue_fields.go index 325fb548e2..9937f74bfd 100644 --- a/pkg/github/issue_fields.go +++ b/pkg/github/issue_fields.go @@ -6,12 +6,12 @@ import ( "fmt" "strconv" - ghcontext "github.com/github/github-mcp-server/pkg/context" - ghErrors "github.com/github/github-mcp-server/pkg/errors" - "github.com/github/github-mcp-server/pkg/ifc" - "github.com/github/github-mcp-server/pkg/inventory" - "github.com/github/github-mcp-server/pkg/translations" - "github.com/github/github-mcp-server/pkg/utils" + ghcontext "github.com/github/github-mcp-server/v2/pkg/context" + ghErrors "github.com/github/github-mcp-server/v2/pkg/errors" + "github.com/github/github-mcp-server/v2/pkg/ifc" + "github.com/github/github-mcp-server/v2/pkg/inventory" + "github.com/github/github-mcp-server/v2/pkg/translations" + "github.com/github/github-mcp-server/v2/pkg/utils" "github.com/google/jsonschema-go/jsonschema" "github.com/modelcontextprotocol/go-sdk/mcp" "github.com/shurcooL/githubv4" @@ -104,7 +104,7 @@ type issueFieldsOrgQuery struct { // ListIssueFields creates a tool to list issue field definitions for a repository or organization. func ListIssueFields(t translations.TranslationHelperFunc) inventory.ServerTool { - st := NewTool( + st := NewToolWithSchemaOptions[IssueMetadataInput, []IssueFieldOutput]( ToolsetMetadataIssues, mcp.Tool{ Name: "list_issue_fields", @@ -127,16 +127,14 @@ func ListIssueFields(t translations.TranslationHelperFunc) inventory.ServerTool }, Required: []string{"owner"}, }, + OutputSchema: listIssueFieldsOutputSchema(), }, repositoryOrOrganizationScopeAccess(), - func(ctx context.Context, deps ToolDependencies, _ *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 - } - repo, err := OptionalParam[string](args, "repo") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil + inventory.TypedSchemaOptions{PreserveHandlerContent: true}, + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, input IssueMetadataInput) (*mcp.CallToolResult, []IssueFieldOutput, error) { + owner, repo := input.Owner, input.Repo + if owner == "" { + return utils.NewToolResultError("missing required parameter: owner"), nil, nil } gqlClient, err := deps.GetGQLClient(ctx) @@ -164,8 +162,8 @@ func ListIssueFields(t translations.TranslationHelperFunc) inventory.ServerTool } else { result = attachRepoVisibilityIFCLabelLazy(ctx, deps, owner, repo, result, ifc.LabelRepoMetadata) } - return result, nil, nil - }) + return result, issueFieldOutputs(fields), nil + }, normalizeIssueStrings([]string{"owner"}, []string{"repo"})) return st } diff --git a/pkg/github/issue_fields_test.go b/pkg/github/issue_fields_test.go index 54ae2f97eb..f30cdab256 100644 --- a/pkg/github/issue_fields_test.go +++ b/pkg/github/issue_fields_test.go @@ -5,9 +5,9 @@ import ( "encoding/json" "testing" - "github.com/github/github-mcp-server/internal/githubv4mock" - "github.com/github/github-mcp-server/internal/toolsnaps" - "github.com/github/github-mcp-server/pkg/translations" + "github.com/github/github-mcp-server/v2/internal/githubv4mock" + "github.com/github/github-mcp-server/v2/internal/toolsnaps" + "github.com/github/github-mcp-server/v2/pkg/translations" "github.com/google/jsonschema-go/jsonschema" "github.com/shurcooL/githubv4" "github.com/stretchr/testify/assert" diff --git a/pkg/github/issue_tool_types.go b/pkg/github/issue_tool_types.go new file mode 100644 index 0000000000..97d000cd2f --- /dev/null +++ b/pkg/github/issue_tool_types.go @@ -0,0 +1,514 @@ +package github + +import ( + "encoding/json" + "fmt" + "strings" + + "github.com/github/github-mcp-server/v2/pkg/inventory" + "github.com/google/go-github/v92/github" + "github.com/google/jsonschema-go/jsonschema" +) + +type IssueMetadataInput struct { + Owner string `json:"owner"` + Repo string `json:"repo,omitempty"` +} + +type IssueReadInput struct { + Method string `json:"method"` + Owner string `json:"owner"` + Repo string `json:"repo"` + IssueNumber int `json:"issue_number"` + Page int `json:"page,omitempty"` + PerPage int `json:"perPage,omitempty"` +} + +type SubIssueWriteInput struct { + Method string `json:"method"` + Owner string `json:"owner"` + Repo string `json:"repo"` + IssueNumber int `json:"issue_number"` + SubIssueID int `json:"sub_issue_id"` + ReplaceParent bool `json:"replace_parent,omitempty"` + AfterID int `json:"after_id,omitempty"` + BeforeID int `json:"before_id,omitempty"` +} + +type IssueTypeOutput struct { + ID *int64 `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Description *string `json:"description,omitempty"` + Color *string `json:"color,omitempty"` + IsEnabled *bool `json:"is_enabled,omitempty"` +} + +func issueTypeOutputs(types []*github.IssueType) []*IssueTypeOutput { + if types == nil { + return nil + } + output := make([]*IssueTypeOutput, len(types)) + for i, item := range types { + if item != nil { + output[i] = &IssueTypeOutput{ + ID: item.ID, Name: item.Name, Description: item.Description, + Color: item.Color, IsEnabled: item.IsEnabled, + } + } + } + return output +} + +type AddIssueCommentInput struct { + Owner string `json:"owner"` + Repo string `json:"repo"` + IssueNumber int `json:"issue_number"` + CommentID *int64 `json:"comment_id,omitempty"` + Body *string `json:"body,omitempty"` + Reaction *string `json:"reaction,omitempty"` +} + +type UpdateIssueCommentInput struct { + Owner string `json:"owner"` + Repo string `json:"repo"` + CommentID int64 `json:"comment_id"` + Body *string `json:"body"` +} + +type IssueCommentOutput struct { + ID string `json:"id"` + HTMLURL string `json:"html_url,omitempty"` +} + +func (output IssueCommentOutput) MarshalJSON() ([]byte, error) { + if output.ID == "" && output.HTMLURL == "" { + return []byte("null"), nil + } + type wireOutput IssueCommentOutput + return json.Marshal(wireOutput(output)) +} + +type IssueReactionOutput struct { + ID string `json:"id"` +} + +type IssueCommentAndReactionOutput struct { + Comment IssueCommentOutput `json:"comment"` + Reaction IssueReactionOutput `json:"reaction"` +} + +type AddIssueCommentOutput struct { + Single *IssueCommentOutput + Combined *IssueCommentAndReactionOutput +} + +func (output AddIssueCommentOutput) MarshalJSON() ([]byte, error) { + if output.Combined != nil { + return json.Marshal(output.Combined) + } + return json.Marshal(output.Single) +} + +type AddIssueCommentLegacyOutput struct { + Single *MinimalResponse + Combined *IssueCommentAndReactionLegacyOutput +} + +type IssueCommentAndReactionLegacyOutput struct { + Comment MinimalResponse `json:"comment"` + Reaction MinimalResponse `json:"reaction"` +} + +func (output AddIssueCommentLegacyOutput) MarshalJSON() ([]byte, error) { + if output.Combined != nil { + return json.Marshal(output.Combined) + } + return json.Marshal(output.Single) +} + +func addIssueCommentOutputSchema() *jsonschema.Schema { + comment := func() *jsonschema.Schema { + return issueCommentOutputObjectSchema(true) + } + reaction := func() *jsonschema.Schema { + return &jsonschema.Schema{Type: "object", Properties: map[string]*jsonschema.Schema{ + "id": {Type: "string", Description: "The ID of the created reaction."}, + }, Required: []string{"id"}, AdditionalProperties: &jsonschema.Schema{Not: &jsonschema.Schema{}}} + } + return &jsonschema.Schema{ + Types: []string{"object", "null"}, + OneOf: []*jsonschema.Schema{ + {Type: "null"}, + comment(), + { + Type: "object", + Properties: map[string]*jsonschema.Schema{ + "id": {Type: "string", Description: "The ID of the created reaction."}, + }, + Required: []string{"id"}, + AdditionalProperties: &jsonschema.Schema{Not: &jsonschema.Schema{}}, + }, + { + Type: "object", + Properties: map[string]*jsonschema.Schema{ + "comment": comment(), "reaction": reaction(), + }, + Required: []string{"comment", "reaction"}, + AdditionalProperties: &jsonschema.Schema{Not: &jsonschema.Schema{}}, + }, + }, + } +} + +func issueCommentOutputSchema() *jsonschema.Schema { + return &jsonschema.Schema{ + Types: []string{"object", "null"}, + OneOf: []*jsonschema.Schema{ + {Type: "null"}, + issueCommentOutputObjectSchema(true), + }, + } +} + +func issueCommentOutputObjectSchema(includeURL bool) *jsonschema.Schema { + properties := map[string]*jsonschema.Schema{ + "id": {Type: "string", Description: "The ID of the created comment or reaction."}, + } + required := []string{"id"} + if includeURL { + properties["html_url"] = &jsonschema.Schema{ + Type: "string", Description: "The web URL of the created issue comment.", + } + required = append(required, "html_url") + } + return &jsonschema.Schema{ + Type: "object", Properties: properties, Required: required, + AdditionalProperties: &jsonschema.Schema{Not: &jsonschema.Schema{}}, + } +} + +type IssueDependencyState string + +type MinimalIssueDependencyRef struct { + Number int `json:"number"` + Title string `json:"title"` + State IssueDependencyState `json:"state"` + HTMLURL string `json:"html_url"` + Repository string `json:"repository,omitempty"` +} + +func dependencyRefOutput(ref MinimalIssueRef) MinimalIssueDependencyRef { + return MinimalIssueDependencyRef{ + Number: ref.Number, Title: ref.Title, State: IssueDependencyState(ref.State), + HTMLURL: ref.URL, Repository: ref.Repository, + } +} + +type IssueDependencyReadInput struct { + Method string `json:"method"` + Owner string `json:"owner"` + Repo string `json:"repo"` + IssueNumber int `json:"issue_number"` + Page int `json:"page,omitempty"` + PerPage int `json:"perPage,omitempty"` +} + +type IssueDependencyPageInfo struct { + HasNextPage bool `json:"hasNextPage"` + NextPage int `json:"nextPage"` +} + +type IssueDependencyReadOutput struct { + Issues []MinimalIssueDependencyRef `json:"issues"` + PageInfo IssueDependencyPageInfo `json:"pageInfo"` +} + +type IssueDependencyReadLegacyOutput struct { + Issues []MinimalIssueRef `json:"issues"` + PageInfo IssueDependencyPageInfo `json:"pageInfo"` +} + +type IssueDependencyWriteInput struct { + Method string `json:"method"` + Type string `json:"type"` + Owner string `json:"owner"` + Repo string `json:"repo"` + IssueNumber int `json:"issue_number"` + RelatedIssueNumber int `json:"related_issue_number"` + RelatedOwner string `json:"related_owner,omitempty"` + RelatedRepo string `json:"related_repo,omitempty"` +} + +type IssueDependencyWriteOutput struct { + BlockedIssue MinimalIssueDependencyRef `json:"blocked_issue"` + BlockingIssue MinimalIssueDependencyRef `json:"blocking_issue"` + Message string `json:"message"` +} + +type IssueDependencyWriteLegacyOutput struct { + BlockedIssue MinimalIssueRef `json:"blocked_issue"` + BlockingIssue MinimalIssueRef `json:"blocking_issue"` + Message string `json:"message"` +} + +type DuplicateIssueState string + +type MinimalDuplicateIssue struct { + Number int `json:"number"` + Title string `json:"title"` + State DuplicateIssueState `json:"state"` + HTMLURL string `json:"html_url"` +} + +type DuplicateConfidence string + +type DuplicateCandidate struct { + Issue MinimalDuplicateIssue `json:"issue"` + Score *float64 `json:"score"` + Confidence DuplicateConfidence `json:"confidence"` + LikelyDuplicate bool `json:"likely_duplicate"` +} + +type LegacyDuplicateCandidate struct { + Issue MinimalIssueRef `json:"issue"` + Score *float64 `json:"score"` + Confidence DuplicateConfidence `json:"confidence"` + LikelyDuplicate bool `json:"likely_duplicate"` +} + +type FindDuplicateInput struct { + Owner string `json:"owner"` + Repo string `json:"repo"` + IssueNumber int `json:"issue_number"` + ConfidenceThreshold *float64 `json:"confidence_threshold,omitempty"` + Page *int `json:"page,omitempty"` + PerPage *int `json:"perPage,omitempty"` +} + +type IssueFieldOutput struct { + ID string `json:"id"` + DatabaseID int64 `json:"full_database_id,omitempty"` + Name string `json:"name"` + Description string `json:"description,omitempty"` + DataType string `json:"data_type"` + Visibility string `json:"visibility"` + Options []IssueFieldOptionOutput `json:"options,omitempty"` +} + +type IssueFieldOptionOutput struct { + ID string `json:"id"` + Name string `json:"name"` + Description string `json:"description,omitempty"` + Color string `json:"color"` + Priority *int `json:"priority,omitempty"` +} + +func issueFieldOutputs(fields []IssueField) []IssueFieldOutput { + if fields == nil { + return nil + } + output := make([]IssueFieldOutput, len(fields)) + for i, field := range fields { + output[i] = IssueFieldOutput{ + ID: field.ID, DatabaseID: field.DatabaseID, Name: field.Name, + Description: field.Description, DataType: field.DataType, + Visibility: field.Visibility, + } + if field.Options != nil { + output[i].Options = make([]IssueFieldOptionOutput, len(field.Options)) + for j, option := range field.Options { + output[i].Options[j] = IssueFieldOptionOutput(option) + } + } + } + return output +} + +func issueOutputSchema[T any]() *jsonschema.Schema { + schema, err := inventory.CachedSchemaFor[T](nil) + if err != nil { + panic(fmt.Sprintf("failed to generate issue output schema: %v", err)) + } + return inventory.CloneSchema(schema) +} + +func issuePaginationValidationSchema(advertised *jsonschema.Schema) *jsonschema.Schema { + validation := inventory.CloneSchemaWithoutDefaults(advertised) + for _, name := range []string{"page", "perPage"} { + property := validation.Properties[name] + property.Minimum = new(0.0) + } + return validation +} + +func listIssueFieldsOutputSchema() *jsonschema.Schema { + schema := issueOutputSchema[[]IssueFieldOutput]() + schema.Items.Properties["id"].Description = "The node ID of the issue field." + schema.Items.Properties["full_database_id"].Description = "The database ID of the issue field, when available." + schema.Items.Properties["name"].Description = "The field name." + schema.Items.Properties["description"].Description = "The field description, when available." + schema.Items.Properties["data_type"].Description = "The field value type." + schema.Items.Properties["visibility"].Description = "The visibility policy for the field." + schema.Items.Properties["options"].Description = "Available values for single-select fields." + schema.Items.Properties["data_type"].Enum = []any{"TEXT", "NUMBER", "DATE", "SINGLE_SELECT"} + schema.Items.Properties["options"].Items.Properties["id"].Description = "The option node ID." + schema.Items.Properties["options"].Items.Properties["name"].Description = "The option name." + schema.Items.Properties["options"].Items.Properties["description"].Description = "The option description, when available." + schema.Items.Properties["options"].Items.Properties["color"].Description = "The option color." + schema.Items.Properties["options"].Items.Properties["priority"].Description = "Display order of this option, when set." + return schema +} + +func issueTypeOutputSchema() *jsonschema.Schema { + schema := issueOutputSchema[[]*IssueTypeOutput]() + schema.Items.Properties["id"].Description = "The issue type ID." + schema.Items.Properties["name"].Description = "The issue type name." + schema.Items.Properties["description"].Description = "The issue type description, when available." + schema.Items.Properties["color"].Description = "The issue type color, when set." + schema.Items.Properties["is_enabled"].Description = "Whether this issue type is enabled." + return schema +} + +func issueDependencyReadOutputSchema() *jsonschema.Schema { + schema := issueOutputSchema[*IssueDependencyReadOutput]() + ref := schema.Properties["issues"].Items.Properties + ref["number"].Description = "The related issue number." + ref["title"].Description = "The sanitized title of the related issue." + ref["state"].Description = "The related issue state." + ref["html_url"].Description = "The web URL of the related issue." + ref["repository"].Description = "The related repository in owner/name form." + schema.Properties["issues"].Description = "Related issues in the requested dependency direction." + schema.Properties["pageInfo"].Properties["hasNextPage"].Description = "Whether another page of related issues is available." + schema.Properties["pageInfo"].Properties["nextPage"].Description = "The next page number, or 0 when no next page exists." + return schema +} + +func issueDependencyWriteOutputSchema() *jsonschema.Schema { + schema := issueOutputSchema[*IssueDependencyWriteOutput]() + for _, field := range []string{"blocked_issue", "blocking_issue"} { + ref := schema.Properties[field].Properties + ref["number"].Description = "The issue number." + ref["title"].Description = "The sanitized issue title." + ref["state"].Description = "The issue state." + ref["html_url"].Description = "The web URL of the issue." + ref["repository"].Description = "The repository in owner/name form." + } + schema.Properties["message"].Description = "Whether the dependency relationship was added or removed." + return schema +} + +func findDuplicateOutputSchema() *jsonschema.Schema { + schema := issueOutputSchema[[]DuplicateCandidate]() + issue := schema.Items.Properties["issue"].Properties + issue["number"].Description = "The candidate issue number." + issue["title"].Description = "The sanitized candidate issue title." + issue["state"].Description = "The candidate issue state." + issue["html_url"].Description = "The web URL of the candidate issue." + schema.Items.Properties["score"].Description = "Similarity score on the API-defined scale; null when the API does not return a score." + schema.Items.Properties["confidence"].Description = "The API-provided confidence category." + schema.Items.Properties["likely_duplicate"].Description = "Whether the API considers this candidate a likely duplicate." + return schema +} + +func validateIssueCoordinate(owner, repo string, number int) error { + if owner == "" { + return fmt.Errorf("missing required parameter: owner") + } + if repo == "" { + return fmt.Errorf("missing required parameter: repo") + } + if number == 0 { + return fmt.Errorf("missing required parameter: issue_number") + } + return nil +} + +// Only the dependency writer historically accepted case-insensitive methods +// and directions. Do not broaden the dependency reader's method handling. +func normalizeIssueDependencyWriteArguments(raw json.RawMessage) (json.RawMessage, error) { + var args map[string]json.RawMessage + if err := json.Unmarshal(raw, &args); err != nil { + return nil, err + } + for _, field := range []string{"method", "type"} { + var value string + if err := json.Unmarshal(args[field], &value); err == nil { + args[field], _ = json.Marshal(strings.ToLower(value)) + } + } + return json.Marshal(args) +} + +func normalizeIssueCommentID(raw json.RawMessage) (json.RawMessage, error) { + var args map[string]any + if err := json.Unmarshal(raw, &args); err != nil { + return nil, err + } + if value, exists := args["comment_id"]; exists { + id, err := toInt64(value) + if err != nil { + return nil, fmt.Errorf("parameter comment_id is not a valid number: %w", err) + } + args["comment_id"] = id + } + return json.Marshal(args) +} + +func normalizeIssueStrings(required, optional []string) inventory.InputNormalizer { + return func(raw json.RawMessage) (json.RawMessage, error) { + var args map[string]any + if err := json.Unmarshal(raw, &args); err != nil { + return nil, err + } + for _, field := range required { + if _, err := RequiredParam[string](args, field); err != nil { + return nil, err + } + } + + for _, field := range optional { + if _, err := OptionalParam[string](args, field); err != nil { + return nil, err + } + } + return raw, nil + } +} + +func normalizeIssueIntegers(required, optional []string) inventory.InputNormalizer { + return func(raw json.RawMessage) (json.RawMessage, error) { + var args map[string]any + if err := json.Unmarshal(raw, &args); err != nil { + return nil, err + } + for _, field := range required { + value, err := RequiredInt(args, field) + if err != nil { + return nil, err + } + args[field] = value + } + for _, field := range optional { + if _, exists := args[field]; !exists { + continue + } + value, err := OptionalIntParam(args, field) + if err != nil { + return nil, err + } + args[field] = value + } + return json.Marshal(args) + } +} + +func normalizeDuplicateThreshold(raw json.RawMessage) (json.RawMessage, error) { + var args map[string]any + if err := json.Unmarshal(raw, &args); err != nil { + return nil, err + } + if _, err := OptionalParam[float64](args, "confidence_threshold"); err != nil { + return nil, err + } + return raw, nil +} diff --git a/pkg/github/issues.go b/pkg/github/issues.go index f1de84eb27..30005854aa 100644 --- a/pkg/github/issues.go +++ b/pkg/github/issues.go @@ -7,20 +7,21 @@ import ( "fmt" "io" "net/http" + "slices" "strconv" "strings" "time" - ghcontext "github.com/github/github-mcp-server/pkg/context" - ghErrors "github.com/github/github-mcp-server/pkg/errors" - "github.com/github/github-mcp-server/pkg/ifc" - "github.com/github/github-mcp-server/pkg/inventory" - "github.com/github/github-mcp-server/pkg/lockdown" - "github.com/github/github-mcp-server/pkg/sanitize" - "github.com/github/github-mcp-server/pkg/scopes" - "github.com/github/github-mcp-server/pkg/translations" - "github.com/github/github-mcp-server/pkg/utils" - "github.com/google/go-github/v89/github" + ghcontext "github.com/github/github-mcp-server/v2/pkg/context" + ghErrors "github.com/github/github-mcp-server/v2/pkg/errors" + "github.com/github/github-mcp-server/v2/pkg/ifc" + "github.com/github/github-mcp-server/v2/pkg/inventory" + "github.com/github/github-mcp-server/v2/pkg/lockdown" + "github.com/github/github-mcp-server/v2/pkg/sanitize" + "github.com/github/github-mcp-server/v2/pkg/scopes" + "github.com/github/github-mcp-server/v2/pkg/translations" + "github.com/github/github-mcp-server/v2/pkg/utils" + "github.com/google/go-github/v92/github" "github.com/google/jsonschema-go/jsonschema" "github.com/modelcontextprotocol/go-sdk/mcp" "github.com/shurcooL/githubv4" @@ -821,11 +822,12 @@ func IssueRead(t translations.TranslationHelperFunc) inventory.ServerTool { } WithPagination(schema) - return NewTool( + return NewTool[IssueReadInput, *IssueReadOutput]( ToolsetMetadataIssues, mcp.Tool{ - Name: "issue_read", - Description: t("TOOL_ISSUE_READ_DESCRIPTION", "Get information about a specific issue in a GitHub repository."), + Name: "issue_read", + OutputSchema: issueReadOutputSchema(), + Description: t("TOOL_ISSUE_READ_DESCRIPTION", "Get information about a specific issue in a GitHub repository."), Annotations: &mcp.ToolAnnotations{ Title: t("TOOL_ISSUE_READ_USER_TITLE", "Get issue details"), ReadOnlyHint: true, @@ -833,7 +835,11 @@ func IssueRead(t translations.TranslationHelperFunc) inventory.ServerTool { InputSchema: schema, }, scopes.PublicRead(scopes.Repo), - func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, args map[string]any) (*mcp.CallToolResult, any, error) { + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, input IssueReadInput) (*mcp.CallToolResult, *IssueReadOutput, error) { + args, err := discussionNotificationArguments(input) + if err != nil { + return nil, nil, err + } method, err := RequiredParam[string](args, "method") if err != nil { return utils.NewToolResultError(err.Error()), nil, nil @@ -874,50 +880,55 @@ func IssueRead(t translations.TranslationHelperFunc) inventory.ServerTool { switch method { case "get": - result, err := GetIssue(ctx, client, deps, owner, repo, issueNumber) - return attachIFC(result), nil, err + result, output, err := getIssue(ctx, client, deps, owner, repo, issueNumber) + return attachIFC(result), output, err case "get_comments": - result, err := GetIssueComments(ctx, client, deps, owner, repo, issueNumber, pagination) - return attachIFC(result), nil, err + result, output, err := getIssueComments(ctx, client, deps, owner, repo, issueNumber, pagination) + return attachIFC(result), output, err case "get_sub_issues": - result, err := GetSubIssues(ctx, client, deps, owner, repo, issueNumber, pagination) - return attachIFC(result), nil, err + result, output, err := getSubIssues(ctx, client, deps, owner, repo, issueNumber, pagination) + return attachIFC(result), output, err case "get_parent": - result, err := GetIssueParent(ctx, gqlClient, deps, owner, repo, issueNumber) - return attachIFC(result), nil, err + result, output, err := getIssueParent(ctx, gqlClient, deps, owner, repo, issueNumber) + return attachIFC(result), output, err case "get_labels": - result, err := GetIssueLabels(ctx, gqlClient, owner, repo, issueNumber) - return attachIFC(result), nil, err + result, output, err := getIssueLabels(ctx, gqlClient, owner, repo, issueNumber) + return attachIFC(result), output, err default: return utils.NewToolResultError(fmt.Sprintf("unknown method: %s", method)), nil, nil } - }) + }, normalizeConsolidatedIssueArguments("read")) } func GetIssue(ctx context.Context, client *github.Client, deps ToolDependencies, owner string, repo string, issueNumber int) (*mcp.CallToolResult, error) { + result, _, err := getIssue(ctx, client, deps, owner, repo, issueNumber) + return result, err +} + +func getIssue(ctx context.Context, client *github.Client, deps ToolDependencies, owner string, repo string, issueNumber int) (*mcp.CallToolResult, *IssueReadOutput, error) { cache, err := deps.GetRepoAccessCache(ctx) if err != nil { - return nil, fmt.Errorf("failed to get repo access cache: %w", err) + return nil, nil, fmt.Errorf("failed to get repo access cache: %w", err) } flags := deps.GetFlags(ctx) issue, resp, err := client.Issues.Get(ctx, owner, repo, issueNumber) if err != nil { - return nil, fmt.Errorf("failed to get issue: %w", err) + return nil, nil, fmt.Errorf("failed to get issue: %w", err) } defer func() { _ = resp.Body.Close() }() if resp.StatusCode != http.StatusOK { body, err := io.ReadAll(resp.Body) if err != nil { - return nil, fmt.Errorf("failed to read response body: %w", err) + return nil, nil, fmt.Errorf("failed to read response body: %w", err) } - return ghErrors.NewGitHubAPIStatusErrorResponse(ctx, "failed to get issue", resp, body), nil + return ghErrors.NewGitHubAPIStatusErrorResponse(ctx, "failed to get issue", resp, body), nil, nil } if flags.LockdownMode { if restricted, err := authorLockdownResult(ctx, cache, owner, repo, issue.GetUser().GetLogin(), lockdownIssueRestrictedMessage); restricted != nil || err != nil { - return restricted, err + return restricted, nil, err } } @@ -936,7 +947,7 @@ func GetIssue(ctx context.Context, client *github.Client, deps ToolDependencies, } } - return MarshalledTextResult(minimalIssue), nil + return MarshalledTextResult(minimalIssue), &IssueReadOutput{Method: "get", Issue: issueDetailsOutput(minimalIssue)}, nil } // applyIssueReadEnrichment populates the hierarchy relationship signals (has_parent/has_children, @@ -1003,35 +1014,38 @@ func isSafeRefContent(ctx context.Context, cache *lockdown.RepoAccessCache, repo } func GetIssueComments(ctx context.Context, client *github.Client, deps ToolDependencies, owner string, repo string, issueNumber int, pagination PaginationParams) (*mcp.CallToolResult, error) { + result, _, err := getIssueComments(ctx, client, deps, owner, repo, issueNumber, pagination) + return result, err +} + +func getIssueComments(ctx context.Context, client *github.Client, deps ToolDependencies, owner string, repo string, issueNumber int, pagination PaginationParams) (*mcp.CallToolResult, *IssueReadOutput, error) { cache, err := deps.GetRepoAccessCache(ctx) if err != nil { - return nil, fmt.Errorf("failed to get repo access cache: %w", err) + return nil, nil, fmt.Errorf("failed to get repo access cache: %w", err) } flags := deps.GetFlags(ctx) opts := &github.IssueListCommentsOptions{ - ListOptions: github.ListOptions{ - Page: pagination.Page, - PerPage: pagination.PerPage, - }, + Page: pagination.Page, + PerPage: pagination.PerPage, } comments, resp, err := client.Issues.ListComments(ctx, owner, repo, issueNumber, opts) if err != nil { - return nil, fmt.Errorf("failed to get issue comments: %w", err) + return nil, nil, fmt.Errorf("failed to get issue comments: %w", err) } defer func() { _ = resp.Body.Close() }() if resp.StatusCode != http.StatusOK { body, err := io.ReadAll(resp.Body) if err != nil { - return nil, fmt.Errorf("failed to read response body: %w", err) + return nil, nil, fmt.Errorf("failed to read response body: %w", err) } - return ghErrors.NewGitHubAPIStatusErrorResponse(ctx, "failed to get issue comments", resp, body), nil + return ghErrors.NewGitHubAPIStatusErrorResponse(ctx, "failed to get issue comments", resp, body), nil, nil } if flags.LockdownMode { if cache == nil { - return nil, fmt.Errorf("lockdown cache is not configured") + return nil, nil, fmt.Errorf("lockdown cache is not configured") } filteredComments := make([]*github.IssueComment, 0, len(comments)) for _, comment := range comments { @@ -1045,7 +1059,7 @@ func GetIssueComments(ctx context.Context, client *github.Client, deps ToolDepen } isSafeContent, err := cache.IsSafeContent(ctx, login, owner, repo) if err != nil { - return utils.NewToolResultError(fmt.Sprintf("failed to check lockdown mode: %v", err)), nil + return utils.NewToolResultError(fmt.Sprintf("failed to check lockdown mode: %v", err)), nil, nil } if isSafeContent { filteredComments = append(filteredComments, comment) @@ -1059,13 +1073,19 @@ func GetIssueComments(ctx context.Context, client *github.Client, deps ToolDepen minimalComments = append(minimalComments, convertToMinimalIssueComment(comment)) } - return MarshalledTextResult(minimalComments), nil + output := issueCommentOutputs(minimalComments) + return MarshalledTextResult(minimalComments), &IssueReadOutput{Method: "get_comments", Comments: &output}, nil } func GetSubIssues(ctx context.Context, client *github.Client, deps ToolDependencies, owner string, repo string, issueNumber int, pagination PaginationParams) (*mcp.CallToolResult, error) { + result, _, err := getSubIssues(ctx, client, deps, owner, repo, issueNumber, pagination) + return result, err +} + +func getSubIssues(ctx context.Context, client *github.Client, deps ToolDependencies, owner string, repo string, issueNumber int, pagination PaginationParams) (*mcp.CallToolResult, *IssueReadOutput, error) { cache, err := deps.GetRepoAccessCache(ctx) if err != nil { - return nil, fmt.Errorf("failed to get repo access cache: %w", err) + return nil, nil, fmt.Errorf("failed to get repo access cache: %w", err) } featureFlags := deps.GetFlags(ctx) @@ -1080,7 +1100,7 @@ func GetSubIssues(ctx context.Context, client *github.Client, deps ToolDependenc "failed to list sub-issues", resp, err, - ), nil + ), nil, nil } defer func() { _ = resp.Body.Close() }() @@ -1088,14 +1108,14 @@ func GetSubIssues(ctx context.Context, client *github.Client, deps ToolDependenc if resp.StatusCode != http.StatusOK { body, err := io.ReadAll(resp.Body) if err != nil { - return nil, fmt.Errorf("failed to read response body: %w", err) + return nil, nil, fmt.Errorf("failed to read response body: %w", err) } - return ghErrors.NewGitHubAPIStatusErrorResponse(ctx, "failed to list sub-issues", resp, body), nil + return ghErrors.NewGitHubAPIStatusErrorResponse(ctx, "failed to list sub-issues", resp, body), nil, nil } if featureFlags.LockdownMode { if cache == nil { - return nil, fmt.Errorf("lockdown cache is not configured") + return nil, nil, fmt.Errorf("lockdown cache is not configured") } filteredSubIssues := make([]*github.SubIssue, 0, len(subIssues)) for _, subIssue := range subIssues { @@ -1109,7 +1129,7 @@ func GetSubIssues(ctx context.Context, client *github.Client, deps ToolDependenc } isSafeContent, err := cache.IsSafeContent(ctx, login, owner, repo) if err != nil { - return utils.NewToolResultError(fmt.Sprintf("failed to check lockdown mode: %v", err)), nil + return utils.NewToolResultError(fmt.Sprintf("failed to check lockdown mode: %v", err)), nil, nil } if isSafeContent { filteredSubIssues = append(filteredSubIssues, subIssue) @@ -1123,10 +1143,21 @@ func GetSubIssues(ctx context.Context, client *github.Client, deps ToolDependenc } r, err := json.Marshal(subIssues) if err != nil { - return nil, fmt.Errorf("failed to marshal response: %w", err) + return nil, nil, fmt.Errorf("failed to marshal response: %w", err) } - return utils.NewToolResultText(string(r)), nil + var output []*SubIssueOutput + if subIssues != nil { + output = make([]*SubIssueOutput, 0, len(subIssues)) + } + for _, issue := range subIssues { + item, err := subIssueOutput(issue) + if err != nil { + return nil, nil, fmt.Errorf("failed to build sub-issue output: %w", err) + } + output = append(output, item) + } + return utils.NewToolResultText(string(r)), &IssueReadOutput{Method: "get_sub_issues", SubIssues: &output}, nil } // GetIssueParent returns the parent issue of the given issue, or a null @@ -1137,9 +1168,14 @@ func GetSubIssues(ctx context.Context, client *github.Client, deps ToolDependenc // lockdown mode the parent is only returned when its author has push // access to the parent repo (mirroring GetIssue); otherwise it is omitted. func GetIssueParent(ctx context.Context, client *githubv4.Client, deps ToolDependencies, owner string, repo string, issueNumber int) (*mcp.CallToolResult, error) { + result, _, err := getIssueParent(ctx, client, deps, owner, repo, issueNumber) + return result, err +} + +func getIssueParent(ctx context.Context, client *githubv4.Client, deps ToolDependencies, owner string, repo string, issueNumber int) (*mcp.CallToolResult, *IssueReadOutput, error) { cache, err := deps.GetRepoAccessCache(ctx) if err != nil { - return nil, fmt.Errorf("failed to get repo access cache: %w", err) + return nil, nil, fmt.Errorf("failed to get repo access cache: %w", err) } flags := deps.GetFlags(ctx) @@ -1169,43 +1205,48 @@ func GetIssueParent(ctx context.Context, client *githubv4.Client, deps ToolDepen } if err := client.Query(ctx, &query, vars); err != nil { - return ghErrors.NewGitHubGraphQLErrorResponse(ctx, "failed to get issue parent", err), nil + return ghErrors.NewGitHubGraphQLErrorResponse(ctx, "failed to get issue parent", err), nil, nil } parent := query.Repository.Issue.Parent if parent == nil { - return MarshalledTextResult(map[string]any{"parent": nil}), nil + output := &IssueParentOutput{} + return MarshalledTextResult(output), &IssueReadOutput{Method: "get_parent", Parent: output.Parent}, nil } if flags.LockdownMode { if cache == nil { - return nil, fmt.Errorf("lockdown cache is not configured") + return nil, nil, fmt.Errorf("lockdown cache is not configured") } // Fail closed: omit the parent if anything needed for the safe-content // check is missing or unverifiable. parentAuthorLogin := string(parent.Author.Login) parentOwner, parentRepo, ok := strings.Cut(string(parent.Repository.NameWithOwner), "/") if parentAuthorLogin == "" || !ok || parentOwner == "" || parentRepo == "" { - return MarshalledTextResult(map[string]any{"parent": nil}), nil + output := &IssueParentOutput{} + return MarshalledTextResult(output), &IssueReadOutput{Method: "get_parent", Parent: output.Parent}, nil } isSafeContent, err := cache.IsSafeContent(ctx, parentAuthorLogin, parentOwner, parentRepo) if err != nil || !isSafeContent { - return MarshalledTextResult(map[string]any{"parent": nil}), nil + output := &IssueParentOutput{} + return MarshalledTextResult(output), &IssueReadOutput{Method: "get_parent", Parent: output.Parent}, nil } } - return MarshalledTextResult(map[string]any{ - "parent": map[string]any{ - "number": int(parent.Number), - "title": sanitize.PlainText(string(parent.Title)), - "state": string(parent.State), - "url": string(parent.URL), - "repository": string(parent.Repository.NameWithOwner), - }, - }), nil + output := &IssueParentOutput{Parent: &IssueParentRef{ + Number: int(parent.Number), Title: sanitize.PlainText(string(parent.Title)), + State: string(parent.State), URL: string(parent.URL), + Repository: string(parent.Repository.NameWithOwner), + }} + return MarshalledTextResult(output), &IssueReadOutput{Method: "get_parent", Parent: output.Parent}, nil } func GetIssueLabels(ctx context.Context, client *githubv4.Client, owner string, repo string, issueNumber int) (*mcp.CallToolResult, error) { + result, _, err := getIssueLabels(ctx, client, owner, repo, issueNumber) + return result, err +} + +func getIssueLabels(ctx context.Context, client *githubv4.Client, owner string, repo string, issueNumber int) (*mcp.CallToolResult, *IssueReadOutput, error) { // Get current labels on the issue using GraphQL var query struct { Repository struct { @@ -1230,37 +1271,34 @@ func GetIssueLabels(ctx context.Context, client *githubv4.Client, owner string, } if err := client.Query(ctx, &query, vars); err != nil { - return ghErrors.NewGitHubGraphQLErrorResponse(ctx, "Failed to get issue labels", err), nil + return ghErrors.NewGitHubGraphQLErrorResponse(ctx, "Failed to get issue labels", err), nil, nil } // Extract label information - issueLabels := make([]map[string]any, len(query.Repository.Issue.Labels.Nodes)) + issueLabels := make([]IssueLabelOutput, len(query.Repository.Issue.Labels.Nodes)) for i, label := range query.Repository.Issue.Labels.Nodes { - issueLabels[i] = map[string]any{ - "id": fmt.Sprintf("%v", label.ID), - "name": string(label.Name), - "color": string(label.Color), - "description": string(label.Description), + issueLabels[i] = IssueLabelOutput{ + ID: fmt.Sprintf("%v", label.ID), Name: string(label.Name), + Color: string(label.Color), Description: string(label.Description), } } - response := map[string]any{ - "labels": issueLabels, - "totalCount": int(query.Repository.Issue.Labels.TotalCount), + response := &IssueLabelsOutput{ + Labels: issueLabels, TotalCount: int(query.Repository.Issue.Labels.TotalCount), } out, err := json.Marshal(response) if err != nil { - return nil, fmt.Errorf("failed to marshal response: %w", err) + return nil, nil, fmt.Errorf("failed to marshal response: %w", err) } - return utils.NewToolResultText(string(out)), nil + return utils.NewToolResultText(string(out)), &IssueReadOutput{Method: "get_labels", Labels: &response.Labels, TotalCount: &response.TotalCount}, nil } // ListIssueTypes creates a tool to list defined issue types for an organization or repository. // This can be used to understand supported issue type values for creating or updating issues. func ListIssueTypes(t translations.TranslationHelperFunc) inventory.ServerTool { - st := NewTool( + st := NewTool[IssueMetadataInput, []*IssueTypeOutput]( ToolsetMetadataIssues, mcp.Tool{ Name: "list_issue_types", @@ -1283,16 +1321,13 @@ func ListIssueTypes(t translations.TranslationHelperFunc) inventory.ServerTool { }, Required: []string{"owner"}, }, + OutputSchema: issueTypeOutputSchema(), }, repositoryOrOrganizationScopeAccess(), - func(ctx context.Context, deps ToolDependencies, _ *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 - } - repo, err := OptionalParam[string](args, "repo") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, input IssueMetadataInput) (*mcp.CallToolResult, []*IssueTypeOutput, error) { + owner, repo := input.Owner, input.Repo + if owner == "" { + return utils.NewToolResultError("missing required parameter: owner"), nil, nil } client, err := deps.GetClient(ctx) @@ -1328,7 +1363,7 @@ func ListIssueTypes(t translations.TranslationHelperFunc) inventory.ServerTool { result := utils.NewToolResultText(string(r)) result = attachRepoVisibilityIFCLabelLazy(ctx, deps, owner, repo, result, ifc.LabelRepoMetadata) - return result, nil, nil + return result, issueTypeOutputs(issueTypes), nil } issueTypes, resp, err := client.Organizations.ListIssueTypes(ctx, owner) @@ -1356,14 +1391,14 @@ func ListIssueTypes(t translations.TranslationHelperFunc) inventory.ServerTool { // than a single repo, so confidentiality is conservatively treated // as private (restricted to org members). result = attachStaticIFCLabel(ctx, deps, result, ifc.LabelRepoMetadata(true)) - return result, nil, nil - }) + return result, issueTypeOutputs(issueTypes), nil + }, normalizeIssueStrings([]string{"owner"}, []string{"repo"})) return st } // AddIssueComment creates a tool to add a comment or reaction to an issue. func AddIssueComment(t translations.TranslationHelperFunc) inventory.ServerTool { - return NewTool( + return NewTool[AddIssueCommentInput, *AddIssueCommentOutput]( ToolsetMetadataIssues, mcp.Tool{ Name: "add_issue_comment", @@ -1390,12 +1425,12 @@ func AddIssueComment(t translations.TranslationHelperFunc) inventory.ServerTool "comment_id": { Type: "integer", Description: "The numeric ID of the issue or pull request comment to react to. Use this for reactions to comments; omit it to react to the issue or pull request itself. Cannot be combined with body.", - Minimum: jsonschema.Ptr(1.0), + Minimum: new(1.0), }, "body": { Type: "string", Description: "Comment content. Required unless reaction is provided.", - MinLength: jsonschema.Ptr(1), + MinLength: new(1), }, "reaction": { Type: "string", @@ -1405,40 +1440,29 @@ func AddIssueComment(t translations.TranslationHelperFunc) inventory.ServerTool }, Required: []string{"owner", "repo", "issue_number"}, }, + OutputSchema: addIssueCommentOutputSchema(), }, publicRepositoryWriteScopeAccess(), - func(ctx context.Context, deps ToolDependencies, _ *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 - } - repo, err := RequiredParam[string](args, "repo") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - issueNumber, err := RequiredInt(args, "issue_number") - if err != nil { + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, input AddIssueCommentInput) (*mcp.CallToolResult, *AddIssueCommentOutput, error) { + owner, repo, issueNumber := input.Owner, input.Repo, input.IssueNumber + if err := validateIssueCoordinate(owner, repo, issueNumber); err != nil { return utils.NewToolResultError(err.Error()), nil, nil } var commentID int64 - hasCommentID := false - if value, ok := args["comment_id"]; ok { - commentID, err = toInt64(value) - if err != nil { - return utils.NewToolResultError(fmt.Sprintf("parameter comment_id is not a valid number: %v", err)), nil, nil - } + hasCommentID := input.CommentID != nil + if hasCommentID { + commentID = *input.CommentID if commentID < 1 { return utils.NewToolResultError("comment_id must be greater than 0"), nil, nil } - hasCommentID = true } - body, hasBody, err := OptionalParamOK[string](args, "body") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil + hasBody, hasReaction := input.Body != nil, input.Reaction != nil + var body, reactionContent string + if hasBody { + body = *input.Body } - reactionContent, hasReaction, err := OptionalParamOK[string](args, "reaction") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil + if hasReaction { + reactionContent = *input.Reaction } if hasCommentID && hasBody { return utils.NewToolResultError("comment_id cannot be combined with body"), nil, nil @@ -1507,8 +1531,8 @@ func AddIssueComment(t translations.TranslationHelperFunc) inventory.ServerTool var commentResponse *MinimalResponse if hasBody { - comment := &github.IssueComment{ - Body: github.Ptr(body), + comment := github.IssueCommentRequest{ + Body: body, } createdComment, resp, err := client.Issues.CreateComment(ctx, owner, repo, issueNumber, comment) if err != nil { @@ -1530,31 +1554,40 @@ func AddIssueComment(t translations.TranslationHelperFunc) inventory.ServerTool } } - var result any + legacyResult := &AddIssueCommentLegacyOutput{} + result := &AddIssueCommentOutput{} switch { case hasBody && hasReaction: - result = map[string]MinimalResponse{ - "comment": *commentResponse, - "reaction": *reactionResponse, + legacyResult.Combined = &IssueCommentAndReactionLegacyOutput{ + Comment: *commentResponse, Reaction: *reactionResponse, + } + result.Combined = &IssueCommentAndReactionOutput{ + Comment: IssueCommentOutput{ID: commentResponse.ID, HTMLURL: commentResponse.URL}, + Reaction: IssueReactionOutput{ID: reactionResponse.ID}, } case hasReaction: - result = reactionResponse + legacyResult.Single = reactionResponse + result.Single = &IssueCommentOutput{ID: reactionResponse.ID} default: - result = commentResponse + legacyResult.Single = commentResponse + if commentResponse != nil { + result.Single = &IssueCommentOutput{ID: commentResponse.ID, HTMLURL: commentResponse.URL} + } } - r, err := json.Marshal(result) + r, err := json.Marshal(legacyResult) if err != nil { return utils.NewToolResultErrorFromErr("failed to marshal response", err), nil, nil } - return utils.NewToolResultText(string(r)), nil, nil - }) + return utils.NewToolResultText(string(r)), result, nil + }, normalizeIssueStrings([]string{"owner", "repo"}, []string{"body", "reaction"}), + normalizeIssueIntegers([]string{"issue_number"}, nil), normalizeIssueCommentID) } // UpdateIssueComment creates a tool to update an issue or pull request conversation comment. func UpdateIssueComment(t translations.TranslationHelperFunc) inventory.ServerTool { - return NewTool( + return NewToolWithSchemaOptions[UpdateIssueCommentInput, *IssueCommentOutput]( ToolsetMetadataIssues, mcp.Tool{ Name: "update_issue_comment", @@ -1577,41 +1610,38 @@ func UpdateIssueComment(t translations.TranslationHelperFunc) inventory.ServerTo "comment_id": { Type: "integer", Description: "The numeric ID of the issue or pull request conversation comment to update. Do not use a pull request review comment ID.", - Minimum: jsonschema.Ptr(1.0), + Minimum: new(1.0), }, "body": { Type: "string", Description: "New comment content", - MinLength: jsonschema.Ptr(1), + MinLength: new(1), }, }, Required: []string{"owner", "repo", "comment_id", "body"}, }, + OutputSchema: issueCommentOutputSchema(), }, publicRepositoryWriteScopeAccess(), - func(ctx context.Context, deps ToolDependencies, _ *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 + inventory.TypedSchemaOptions{PreserveHandlerContent: true}, + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, input UpdateIssueCommentInput) (*mcp.CallToolResult, *IssueCommentOutput, error) { + owner, repo, commentID := input.Owner, input.Repo, input.CommentID + if owner == "" { + return utils.NewToolResultError("missing required parameter: owner"), nil, nil } - repo, err := RequiredParam[string](args, "repo") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil + if repo == "" { + return utils.NewToolResultError("missing required parameter: repo"), nil, nil } - commentID, err := RequiredBigInt(args, "comment_id") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil + if commentID == 0 { + return utils.NewToolResultError("missing required parameter: comment_id"), nil, nil } if commentID < 1 { return utils.NewToolResultError("comment_id must be greater than 0"), nil, nil } - body, hasBody, err := OptionalParamOK[string](args, "body") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - if !hasBody { + if input.Body == nil { return utils.NewToolResultError("missing required parameter: body"), nil, nil } + body := *input.Body if body == "" { return utils.NewToolResultError("body cannot be empty when provided"), nil, nil } @@ -1621,8 +1651,8 @@ func UpdateIssueComment(t translations.TranslationHelperFunc) inventory.ServerTo return utils.NewToolResultErrorFromErr("failed to get GitHub client", err), nil, nil } - updatedComment, resp, err := client.Issues.EditComment(ctx, owner, repo, commentID, &github.IssueComment{ - Body: github.Ptr(body), + updatedComment, resp, err := client.Issues.UpdateComment(ctx, owner, repo, commentID, github.IssueCommentRequest{ + Body: body, }) if resp != nil && resp.Body != nil { defer func() { _ = resp.Body.Close() }() @@ -1631,16 +1661,18 @@ func UpdateIssueComment(t translations.TranslationHelperFunc) inventory.ServerTo return ghErrors.NewGitHubAPIErrorResponse(ctx, "failed to update issue comment", resp, err), nil, nil } - r, err := json.Marshal(MinimalResponse{ + legacyOutput := &MinimalResponse{ ID: fmt.Sprintf("%d", updatedComment.GetID()), URL: updatedComment.GetHTMLURL(), - }) + } + output := &IssueCommentOutput{ID: legacyOutput.ID, HTMLURL: legacyOutput.URL} + r, err := json.Marshal(legacyOutput) if err != nil { return utils.NewToolResultErrorFromErr("failed to marshal response", err), nil, nil } - return utils.NewToolResultText(string(r)), nil, nil - }) + return utils.NewToolResultText(string(r)), output, nil + }, normalizeIssueStrings([]string{"owner", "repo"}, []string{"body"}), normalizeIssueCommentID) } func isValidIssueReaction(reaction string) bool { @@ -1663,11 +1695,12 @@ func issueNumberFromIssueURL(issueURL string) (int, error) { // SubIssueWrite creates a tool to add a sub-issue to a parent issue. func SubIssueWrite(t translations.TranslationHelperFunc) inventory.ServerTool { - st := NewTool( + st := NewTool[SubIssueWriteInput, *SubIssueWriteOutput]( ToolsetMetadataIssues, mcp.Tool{ - Name: "sub_issue_write", - Description: t("TOOL_SUB_ISSUE_WRITE_DESCRIPTION", "Add a sub-issue to a parent issue in a GitHub repository."), + Name: "sub_issue_write", + OutputSchema: subIssueWriteOutputSchema(), + Description: t("TOOL_SUB_ISSUE_WRITE_DESCRIPTION", "Add a sub-issue to a parent issue in a GitHub repository."), Annotations: &mcp.ToolAnnotations{ Title: t("TOOL_SUB_ISSUE_WRITE_USER_TITLE", "Change sub-issue"), ReadOnlyHint: false, @@ -1717,7 +1750,11 @@ func SubIssueWrite(t translations.TranslationHelperFunc) inventory.ServerTool { }, }, scopes.RequireAll(scopes.Repo), - func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, args map[string]any) (*mcp.CallToolResult, any, error) { + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, input SubIssueWriteInput) (*mcp.CallToolResult, *SubIssueWriteOutput, error) { + args, err := discussionNotificationArguments(input) + if err != nil { + return nil, nil, err + } method, err := RequiredParam[string](args, "method") if err != nil { return utils.NewToolResultError(err.Error()), nil, nil @@ -1759,28 +1796,30 @@ func SubIssueWrite(t translations.TranslationHelperFunc) inventory.ServerTool { switch strings.ToLower(method) { case "add": - result, err := AddSubIssue(ctx, client, owner, repo, issueNumber, subIssueID, replaceParent) - return result, nil, err + return subIssueWriteResult("add")(addSubIssue(ctx, client, owner, repo, issueNumber, subIssueID, replaceParent)) case "remove": // Call the remove sub-issue function - result, err := RemoveSubIssue(ctx, client, owner, repo, issueNumber, subIssueID) - return result, nil, err + return subIssueWriteResult("remove")(removeSubIssue(ctx, client, owner, repo, issueNumber, subIssueID)) case "reprioritize": // Call the reprioritize sub-issue function - result, err := ReprioritizeSubIssue(ctx, client, owner, repo, issueNumber, subIssueID, afterID, beforeID) - return result, nil, err + return subIssueWriteResult("reprioritize")(reprioritizeSubIssue(ctx, client, owner, repo, issueNumber, subIssueID, afterID, beforeID)) default: return utils.NewToolResultError(fmt.Sprintf("unknown method: %s", method)), nil, nil } - }) + }, normalizeConsolidatedIssueArguments("sub")) st.FeatureRule = issuesConsolidatedFeatureRule return st } func AddSubIssue(ctx context.Context, client *github.Client, owner string, repo string, issueNumber int, subIssueID int, replaceParent bool) (*mcp.CallToolResult, error) { + result, _, err := addSubIssue(ctx, client, owner, repo, issueNumber, subIssueID, replaceParent) + return result, err +} + +func addSubIssue(ctx context.Context, client *github.Client, owner string, repo string, issueNumber int, subIssueID int, replaceParent bool) (*mcp.CallToolResult, *SubIssueOutput, error) { subIssueRequest := github.SubIssueRequest{ SubIssueID: int64(subIssueID), - ReplaceParent: github.Ptr(replaceParent), + ReplaceParent: new(replaceParent), } subIssue, resp, err := client.SubIssue.Add(ctx, owner, repo, int64(issueNumber), subIssueRequest) @@ -1789,7 +1828,7 @@ func AddSubIssue(ctx context.Context, client *github.Client, owner string, repo "failed to add sub-issue", resp, err, - ), nil + ), nil, nil } defer func() { _ = resp.Body.Close() }() @@ -1797,21 +1836,27 @@ func AddSubIssue(ctx context.Context, client *github.Client, owner string, repo if resp.StatusCode != http.StatusCreated { body, err := io.ReadAll(resp.Body) if err != nil { - return nil, fmt.Errorf("failed to read response body: %w", err) + return nil, nil, fmt.Errorf("failed to read response body: %w", err) } - return ghErrors.NewGitHubAPIStatusErrorResponse(ctx, "failed to add sub-issue", resp, body), nil + return ghErrors.NewGitHubAPIStatusErrorResponse(ctx, "failed to add sub-issue", resp, body), nil, nil } sanitizeSubIssueTitleAndBody(subIssue) r, err := json.Marshal(subIssue) if err != nil { - return nil, fmt.Errorf("failed to marshal response: %w", err) + return nil, nil, fmt.Errorf("failed to marshal response: %w", err) } - return utils.NewToolResultText(string(r)), nil + output, err := subIssueOutput(subIssue) + return utils.NewToolResultText(string(r)), output, err } func RemoveSubIssue(ctx context.Context, client *github.Client, owner string, repo string, issueNumber int, subIssueID int) (*mcp.CallToolResult, error) { + result, _, err := removeSubIssue(ctx, client, owner, repo, issueNumber, subIssueID) + return result, err +} + +func removeSubIssue(ctx context.Context, client *github.Client, owner string, repo string, issueNumber int, subIssueID int) (*mcp.CallToolResult, *SubIssueOutput, error) { subIssueRequest := github.SubIssueRequest{ SubIssueID: int64(subIssueID), } @@ -1822,34 +1867,40 @@ func RemoveSubIssue(ctx context.Context, client *github.Client, owner string, re "failed to remove sub-issue", resp, err, - ), nil + ), nil, nil } defer func() { _ = resp.Body.Close() }() if resp.StatusCode != http.StatusOK { body, err := io.ReadAll(resp.Body) if err != nil { - return nil, fmt.Errorf("failed to read response body: %w", err) + return nil, nil, fmt.Errorf("failed to read response body: %w", err) } - return ghErrors.NewGitHubAPIStatusErrorResponse(ctx, "failed to remove sub-issue", resp, body), nil + return ghErrors.NewGitHubAPIStatusErrorResponse(ctx, "failed to remove sub-issue", resp, body), nil, nil } sanitizeSubIssueTitleAndBody(subIssue) r, err := json.Marshal(subIssue) if err != nil { - return nil, fmt.Errorf("failed to marshal response: %w", err) + return nil, nil, fmt.Errorf("failed to marshal response: %w", err) } - return utils.NewToolResultText(string(r)), nil + output, err := subIssueOutput(subIssue) + return utils.NewToolResultText(string(r)), output, err } func ReprioritizeSubIssue(ctx context.Context, client *github.Client, owner string, repo string, issueNumber int, subIssueID int, afterID int, beforeID int) (*mcp.CallToolResult, error) { + result, _, err := reprioritizeSubIssue(ctx, client, owner, repo, issueNumber, subIssueID, afterID, beforeID) + return result, err +} + +func reprioritizeSubIssue(ctx context.Context, client *github.Client, owner string, repo string, issueNumber int, subIssueID int, afterID int, beforeID int) (*mcp.CallToolResult, *SubIssueOutput, error) { // Validate that either after_id or before_id is specified, but not both if afterID == 0 && beforeID == 0 { - return utils.NewToolResultError("either after_id or before_id must be specified"), nil + return utils.NewToolResultError("either after_id or before_id must be specified"), nil, nil } if afterID != 0 && beforeID != 0 { - return utils.NewToolResultError("only one of after_id or before_id should be specified, not both"), nil + return utils.NewToolResultError("only one of after_id or before_id should be specified, not both"), nil, nil } subIssueRequest := github.SubIssueRequest{ @@ -1871,7 +1922,7 @@ func ReprioritizeSubIssue(ctx context.Context, client *github.Client, owner stri "failed to reprioritize sub-issue", resp, err, - ), nil + ), nil, nil } defer func() { _ = resp.Body.Close() }() @@ -1879,18 +1930,19 @@ func ReprioritizeSubIssue(ctx context.Context, client *github.Client, owner stri if resp.StatusCode != http.StatusOK { body, err := io.ReadAll(resp.Body) if err != nil { - return nil, fmt.Errorf("failed to read response body: %w", err) + return nil, nil, fmt.Errorf("failed to read response body: %w", err) } - return ghErrors.NewGitHubAPIStatusErrorResponse(ctx, "failed to reprioritize sub-issue", resp, body), nil + return ghErrors.NewGitHubAPIStatusErrorResponse(ctx, "failed to reprioritize sub-issue", resp, body), nil, nil } sanitizeSubIssueTitleAndBody(subIssue) r, err := json.Marshal(subIssue) if err != nil { - return nil, fmt.Errorf("failed to marshal response: %w", err) + return nil, nil, fmt.Errorf("failed to marshal response: %w", err) } - return utils.NewToolResultText(string(r)), nil + output, err := subIssueOutput(subIssue) + return utils.NewToolResultText(string(r)), output, err } // The two search engines want opposite things from a caller, so steering advice @@ -1970,7 +2022,7 @@ func SearchIssues(t translations.TranslationHelperFunc, opts ...ToolOption) inve ) WithPagination(schema) - return NewTool( + return NewTool[SearchIssuesInput, SearchIssuesOutput]( ToolsetMetadataIssues, mcp.Tool{ Name: "search_issues", @@ -1982,16 +2034,14 @@ func SearchIssues(t translations.TranslationHelperFunc, opts ...ToolOption) inve InputSchema: schema, }, scopes.PublicRead(scopes.Repo), - func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, args map[string]any) (*mcp.CallToolResult, any, error) { + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, input SearchIssuesInput) (*mcp.CallToolResult, SearchIssuesOutput, error) { options := []searchOption{ifcSearchPostProcessOption(ctx, deps)} - fields, err := OptionalStringArrayParam(args, "fields") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - options = append(options, withFieldsFiltering(deps, "search_issues", fields)) - result, err := searchIssuesHandler(ctx, deps, args, mode, options...) - return result, nil, err - }) + options = append(options, withFieldsFiltering(deps, "search_issues", input.Fields)) + result, response, err := searchIssuesHandler(ctx, deps, input, mode, options...) + return result, structuredSearchIssuesOutput(response, input.Fields), err + }, + normalizeTypedReadArguments(nil, false), + ) } // searchIssuesIFCPostProcess returns a searchPostProcessFn that attaches the @@ -2065,11 +2115,11 @@ func parseRepositoryURL(repoURL string) (string, string, bool) { return "", "", false } const marker = "/repos/" - idx := strings.LastIndex(repoURL, marker) - if idx < 0 { + _, after, ok := strings.CutLast(repoURL, marker) + if !ok { return "", "", false } - parts := strings.Split(strings.Trim(repoURL[idx+len(marker):], "/"), "/") + parts := strings.Split(strings.Trim(after, "/"), "/") if len(parts) < 2 || parts[0] == "" || parts[1] == "" { return "", "", false } @@ -2092,10 +2142,10 @@ func sanitizeIssueTitleAndBody(issue *github.Issue) { return } if issue.Title != nil { - issue.Title = github.Ptr(sanitize.PlainText(*issue.Title)) + issue.Title = new(sanitize.PlainText(*issue.Title)) } if issue.Body != nil { - issue.Body = github.Ptr(sanitize.Content(*issue.Body)) + issue.Body = new(sanitize.Content(*issue.Body)) } } @@ -2104,10 +2154,10 @@ func sanitizeSubIssueTitleAndBody(issue *github.SubIssue) { return } if issue.Title != nil { - issue.Title = github.Ptr(sanitize.PlainText(*issue.Title)) + issue.Title = new(sanitize.PlainText(*issue.Title)) } if issue.Body != nil { - issue.Body = github.Ptr(sanitize.Content(*issue.Body)) + issue.Body = new(sanitize.Content(*issue.Body)) } } @@ -2146,6 +2196,150 @@ type SearchIssuesResponse struct { Items []SearchIssueResult `json:"items"` } +type SearchIssuesOutput struct { + Total *int `json:"total_count,omitempty"` + IncompleteResults *bool `json:"incomplete_results,omitempty"` + Items []SearchIssueOutputItem `json:"items"` +} + +type SearchIssueOutputItem struct { + Number *int `json:"number,omitempty"` + Title *string `json:"title,omitempty"` + Body *string `json:"body,omitempty"` + State *string `json:"state,omitempty"` + StateReason *string `json:"state_reason,omitempty"` + Draft *bool `json:"draft,omitempty"` + Locked *bool `json:"locked,omitempty"` + HTMLURL *string `json:"html_url,omitempty"` + User *MinimalUser `json:"user,omitempty"` + AuthorAssociation *string `json:"author_association,omitempty"` + Labels []string `json:"labels,omitempty"` + Assignee *string `json:"assignee,omitempty"` + Assignees []string `json:"assignees,omitempty"` + Milestone *string `json:"milestone,omitempty"` + Comments *int `json:"comments,omitempty"` + Reactions *MinimalReactions `json:"reactions,omitempty"` + CreatedAt *string `json:"created_at,omitempty"` + UpdatedAt *string `json:"updated_at,omitempty"` + ClosedAt *string `json:"closed_at,omitempty"` + ClosedBy *string `json:"closed_by,omitempty"` + Type *string `json:"type,omitempty"` + RepositoryURL *string `json:"repository_url,omitempty"` + PullRequest *SearchIssuePullRequest `json:"pull_request,omitempty"` + FieldValues *[]MinimalFieldValue `json:"field_values,omitempty"` +} + +type SearchIssuePullRequest struct { + URL *string `json:"url,omitempty"` + HTMLURL *string `json:"html_url,omitempty"` + DiffURL *string `json:"diff_url,omitempty"` + PatchURL *string `json:"patch_url,omitempty"` +} + +func structuredSearchIssuesOutput(response SearchIssuesResponse, fields []string) SearchIssuesOutput { + output := SearchIssuesOutput{ + Total: response.Total, + IncompleteResults: response.IncompleteResults, + Items: make([]SearchIssueOutputItem, 0, len(response.Items)), + } + for _, item := range response.Items { + output.Items = append(output.Items, searchIssueOutputItem(item, fields)) + } + return output +} + +func searchIssueOutputItem(result SearchIssueResult, fields []string) SearchIssueOutputItem { + var output SearchIssueOutputItem + issue := result.Issue + if issue == nil { + return output + } + selected := func(field string) bool { + return len(fields) == 0 || slices.Contains(fields, field) + } + minimal := convertToMinimalIssue(issue) + if selected("number") && issue.Number != nil { + output.Number = new(minimal.Number) + } + if selected("title") && issue.Title != nil { + output.Title = new(minimal.Title) + } + if selected("body") && issue.Body != nil { + output.Body = new(minimal.Body) + } + if selected("state") && issue.State != nil { + output.State = new(minimal.State) + } + if selected("state_reason") && issue.StateReason != nil { + output.StateReason = new(minimal.StateReason) + } + if selected("draft") && issue.Draft != nil { + output.Draft = new(minimal.Draft) + } + if selected("locked") && issue.Locked != nil { + output.Locked = new(minimal.Locked) + } + if selected("html_url") && issue.HTMLURL != nil { + output.HTMLURL = new(minimal.HTMLURL) + } + if selected("user") && issue.User != nil { + output.User = minimal.User + } + if selected("author_association") && issue.AuthorAssociation != nil { //nolint:staticcheck // Keep the legacy search projection available. + output.AuthorAssociation = new(minimal.AuthorAssociation) + } + if selected("labels") && issue.Labels != nil { + output.Labels = minimal.Labels + } + if selected("assignee") && issue.Assignee != nil { //nolint:staticcheck // Keep the legacy search projection available. + login := issue.Assignee.GetLogin() //nolint:staticcheck // Keep the legacy search projection available. + output.Assignee = &login + } + if selected("assignees") && issue.Assignees != nil { + output.Assignees = minimal.Assignees + } + if selected("milestone") && issue.Milestone != nil { + output.Milestone = new(minimal.Milestone) + } + if selected("comments") && issue.Comments != nil { + output.Comments = new(minimal.Comments) + } + if selected("reactions") && issue.Reactions != nil { + output.Reactions = minimal.Reactions + } + if selected("created_at") && issue.CreatedAt != nil { + output.CreatedAt = new(minimal.CreatedAt) + } + if selected("updated_at") && issue.UpdatedAt != nil { + output.UpdatedAt = new(minimal.UpdatedAt) + } + if selected("closed_at") && issue.ClosedAt != nil { + output.ClosedAt = new(minimal.ClosedAt) + } + if selected("closed_by") && issue.ClosedBy != nil { + output.ClosedBy = new(minimal.ClosedBy) + } + if selected("type") && issue.Type != nil { + output.Type = new(issue.Type.GetName()) + } + if selected("repository_url") && issue.RepositoryURL != nil { + output.RepositoryURL = new(issue.GetRepositoryURL()) + } + if selected("pull_request") && issue.PullRequestLinks != nil { + links := issue.PullRequestLinks + output.PullRequest = &SearchIssuePullRequest{ + URL: links.URL, + HTMLURL: links.HTMLURL, + DiffURL: links.DiffURL, + PatchURL: links.PatchURL, + } + } + if selected("field_values") && result.FieldValues != nil { + output.FieldValues = &result.FieldValues + } + return output +} + // searchIssuesNodesQuery batches a nodes(ids:) lookup over the REST search results to retrieve // each issue's custom field values in a single GraphQL request. type searchIssuesNodesQuery struct { @@ -2337,43 +2531,44 @@ func fetchIssueReadEnrichment(ctx context.Context, gqlClient *githubv4.Client, n // searchIssuesHandler runs the REST issues search, enriches each hit with custom field values // fetched via a single follow-up GraphQL nodes() query, and applies any post-process options // (e.g. IFC labelling). -func searchIssuesHandler(ctx context.Context, deps ToolDependencies, args map[string]any, mode searchMode, options ...searchOption) (*mcp.CallToolResult, error) { +func searchIssuesHandler(ctx context.Context, deps ToolDependencies, input SearchIssuesInput, mode searchMode, options ...searchOption) (*mcp.CallToolResult, SearchIssuesResponse, error) { const errorPrefix = "failed to search issues" - query, opts, err := prepareSearchArgs(args, "issue", mode) + var output SearchIssuesResponse + query, opts, err := prepareSearchArgs(input, "issue", mode) if err != nil { - return utils.NewToolResultError(err.Error()), nil + return utils.NewToolResultError(err.Error()), output, nil } client, err := deps.GetClient(ctx) if err != nil { - return utils.NewToolResultErrorFromErr(errorPrefix+": failed to get GitHub client", err), nil + return utils.NewToolResultErrorFromErr(errorPrefix+": failed to get GitHub client", err), output, nil } result, resp, err := client.Search.Issues(ctx, query, opts) if err != nil { - return utils.NewToolResultErrorFromErr(errorPrefix, err), nil + return utils.NewToolResultErrorFromErr(errorPrefix, err), output, nil } defer func() { _ = resp.Body.Close() }() if resp.StatusCode != http.StatusOK { body, err := io.ReadAll(resp.Body) if err != nil { - return utils.NewToolResultErrorFromErr(errorPrefix+": failed to read response body", err), nil + return utils.NewToolResultErrorFromErr(errorPrefix+": failed to read response body", err), output, nil } - return ghErrors.NewGitHubAPIStatusErrorResponse(ctx, errorPrefix, resp, body), nil + return ghErrors.NewGitHubAPIStatusErrorResponse(ctx, errorPrefix, resp, body), output, nil } var fieldValuesByID map[string][]MinimalFieldValue if len(result.Issues) > 0 { gqlClient, err := deps.GetGQLClient(ctx) if err != nil { - return utils.NewToolResultErrorFromErr(errorPrefix+": failed to get GitHub GraphQL client", err), nil + return utils.NewToolResultErrorFromErr(errorPrefix+": failed to get GitHub GraphQL client", err), output, nil } fieldValuesByID, err = fetchIssueFieldValuesByNodeID(ctx, gqlClient, result.Issues) if err != nil { const enrichmentError = errorPrefix + ": failed to fetch issue field values" if !isUnsupportedIssueFieldValuesSchemaError(err) { - return ghErrors.NewGitHubGraphQLErrorResponse(ctx, enrichmentError, err), nil + return ghErrors.NewGitHubGraphQLErrorResponse(ctx, enrichmentError, err), output, nil } // Older GHES schemas can lack this optional enrichment. Preserve the REST // search results while retaining the compatibility failure for observability. @@ -2401,12 +2596,13 @@ func searchIssuesHandler(ctx context.Context, deps ToolDependencies, args map[st opt(&cfg) } + output = response filtered := false var payload any = response if len(cfg.fields) > 0 { filteredItems, err := filterEachField(response.Items, cfg.fields) if err != nil { - return utils.NewToolResultErrorFromErr(errorPrefix+": failed to filter results", err), nil + return utils.NewToolResultErrorFromErr(errorPrefix+": failed to filter results", err), SearchIssuesResponse{}, nil } payload = map[string]any{ "total_count": response.Total, @@ -2418,7 +2614,7 @@ func searchIssuesHandler(ctx context.Context, deps ToolDependencies, args map[st r, err := json.Marshal(payload) if err != nil { - return utils.NewToolResultErrorFromErr(errorPrefix+": failed to marshal response", err), nil + return utils.NewToolResultErrorFromErr(errorPrefix+": failed to marshal response", err), SearchIssuesResponse{}, nil } if cfg.fieldsTool != "" { @@ -2429,7 +2625,7 @@ func searchIssuesHandler(ctx context.Context, deps ToolDependencies, args map[st if cfg.postProcess != nil { cfg.postProcess(ctx, result, callResult) } - return callResult, nil + return callResult, output, nil } // IssueWriteUIResourceURI is the URI for the issue_write tool's MCP App UI resource. @@ -2495,11 +2691,12 @@ func issueWriteAwaitingFormResult(method, owner, repo string, issueNumber int) * // flag is removed, delete LegacyIssueWrite outright and drop the feature-flag // fields on IssueWrite. func IssueWrite(t translations.TranslationHelperFunc) inventory.ServerTool { - st := NewTool( + st := NewTool[IssueWriteInput, *IssueWriteOutput]( ToolsetMetadataIssues, mcp.Tool{ - Name: "issue_write", - Description: t("TOOL_ISSUE_WRITE_DESCRIPTION", "Create a new or update an existing issue in a GitHub repository."), + Name: "issue_write", + OutputSchema: issueWriteOutputSchema(), + Description: t("TOOL_ISSUE_WRITE_DESCRIPTION", "Create a new or update an existing issue in a GitHub repository."), Annotations: &mcp.ToolAnnotations{ Title: t("TOOL_ISSUE_WRITE_USER_TITLE", "Create or update issue/pull request"), ReadOnlyHint: false, @@ -2537,7 +2734,7 @@ Options are: "parent_issue_number": { Type: "number", Description: "Issue number of the parent issue. Only used when method is 'create' and cannot be combined with issue_fields. The new issue is created and attached to this parent in the same operation.", - Minimum: jsonschema.Ptr(1.0), + Minimum: new(1.0), }, "parent_owner": { Type: "string", @@ -2575,7 +2772,7 @@ Options are: }, "type": { AnyOf: []*jsonschema.Schema{ - {Type: "string", MinLength: jsonschema.Ptr(1)}, + {Type: "string", MinLength: new(1)}, {Type: "null"}, }, Description: "Type of this issue. For updates, pass null to remove the current type. Only use if issue types are enabled for this repository. Use list_issue_types to get valid type values for this repository or its owner organization. If the repository doesn't support issue types, omit this parameter.", @@ -2634,7 +2831,14 @@ Options are: }, }, publicRepositoryWriteScopeAccess(), - func(ctx context.Context, deps ToolDependencies, req *mcp.CallToolRequest, args map[string]any) (*mcp.CallToolResult, any, error) { + func(ctx context.Context, deps ToolDependencies, req *mcp.CallToolRequest, input IssueWriteInput) (*mcp.CallToolResult, *IssueWriteOutput, error) { + args, err := discussionNotificationArguments(input) + if err != nil { + return nil, nil, err + } + if input.TypeProvided && input.Type == nil { + args["type"] = nil + } method, err := RequiredParam[string](args, "method") if err != nil { return utils.NewToolResultError(err.Error()), nil, nil @@ -2651,7 +2855,13 @@ Options are: // Hand off to the interactive MCP App form unless this call must // execute now (see shouldDeferToForm). - if shouldDeferToForm(ctx, deps, req, args, issueWriteFormParams) { + formArgs := args + if req != nil && req.Params != nil && len(req.Params.Arguments) > 0 { + if err := json.Unmarshal(req.Params.Arguments, &formArgs); err != nil { + return nil, nil, err + } + } + if shouldDeferToForm(ctx, deps, req, formArgs, issueWriteFormParams) { issueNumber := 0 if method == "update" { n, numErr := RequiredInt(args, "issue_number") @@ -2660,7 +2870,13 @@ Options are: } issueNumber = n } - return issueWriteAwaitingFormResult(method, owner, repo, issueNumber), nil, nil + result := issueWriteAwaitingFormResult(method, owner, repo, issueNumber) + output := &IssueWriteAwaitingOutput{ + Status: "awaiting_user_submission", + Reason: "An interactive form is being shown to the user. The operation has not been performed.", + } + result.StructuredContent = output + return result, &IssueWriteOutput{Method: method, Awaiting: output}, nil } title, err := OptionalParam[string](args, "title") @@ -2788,27 +3004,24 @@ Options are: switch method { case "create": if parentProvided { - result, err := CreateIssueWithParent(ctx, client, gqlClient, owner, repo, title, body, assignees, labels, milestoneNum, issueType, parentIssueNumber, parentOwner, parentRepo) - return result, nil, err + return issueWriteResult(method)(createIssueWithParent(ctx, client, gqlClient, owner, repo, title, body, assignees, labels, milestoneNum, issueType, parentIssueNumber, parentOwner, parentRepo)) } - result, err := CreateIssue(ctx, client, owner, repo, title, body, assignees, labels, milestoneNum, issueType, issueFieldValues) - return result, nil, err + return issueWriteResult(method)(createIssue(ctx, client, owner, repo, title, body, assignees, labels, milestoneNum, issueType, issueFieldValues)) case "update": issueNumber, err := RequiredInt(args, "issue_number") if err != nil { return utils.NewToolResultError(err.Error()), nil, nil } - result, err := UpdateIssue(ctx, client, gqlClient, owner, repo, issueNumber, title, body, assignees, labels, milestoneNum, issueType, issueFieldValues, fieldIDsToDelete, state, stateReason, duplicateOf, UpdateIssueOptions{ + return issueWriteResult(method)(updateIssue(ctx, client, gqlClient, owner, repo, issueNumber, title, body, assignees, labels, milestoneNum, issueType, issueFieldValues, fieldIDsToDelete, state, stateReason, duplicateOf, UpdateIssueOptions{ AssigneesProvided: assigneesProvided, LabelsProvided: labelsProvided, IssueTypeProvided: issueTypeProvided, - }) - return result, nil, err + })) default: return utils.NewToolResultError("invalid method, must be either 'create' or 'update'"), nil, nil } - }) + }, normalizeConsolidatedIssueArguments("write")) st.FeatureRule = issuesConsolidatedFeatureRule return st } @@ -2864,17 +3077,22 @@ func CreateIssueWithParent( parentOwner string, parentRepo string, ) (*mcp.CallToolResult, error) { + result, _, err := createIssueWithParent(ctx, client, gqlClient, owner, repo, title, body, assignees, labels, milestoneNumber, issueType, parentIssueNumber, parentOwner, parentRepo) + return result, err +} + +func createIssueWithParent(ctx context.Context, client *github.Client, gqlClient *githubv4.Client, owner, repo, title, body string, assignees, labels []string, milestoneNumber int, issueType string, parentIssueNumber int, parentOwner, parentRepo string) (*mcp.CallToolResult, *MinimalResponse, error) { if title == "" { - return utils.NewToolResultError("missing required parameter: title"), nil + return utils.NewToolResultError("missing required parameter: title"), nil, nil } if parentIssueNumber < 1 { - return utils.NewToolResultError("parent_issue_number must be greater than 0"), nil + return utils.NewToolResultError("parent_issue_number must be greater than 0"), nil, nil } parentOwner, parentRepo = parentRepository(owner, repo, parentOwner, parentRepo) repositoryID, parentIssueID, err := resolveCreateIssueParent(ctx, gqlClient, owner, repo, parentOwner, parentRepo, parentIssueNumber) if err != nil { - return ghErrors.NewGitHubGraphQLErrorResponse(ctx, "failed to resolve parent issue", err), nil + return ghErrors.NewGitHubGraphQLErrorResponse(ctx, "failed to resolve parent issue", err), nil, nil } input := CreateIssueInput{ @@ -2891,7 +3109,7 @@ func CreateIssueWithParent( for _, label := range labels { labelID, err := getLabelID(ctx, gqlClient, owner, repo, label) if err != nil { - return ghErrors.NewGitHubGraphQLErrorResponse(ctx, fmt.Sprintf("failed to resolve label %q", label), err), nil + return ghErrors.NewGitHubGraphQLErrorResponse(ctx, fmt.Sprintf("failed to resolve label %q", label), err), nil, nil } labelIDs = append(labelIDs, labelID) } @@ -2903,7 +3121,7 @@ func CreateIssueWithParent( for _, assignee := range assignees { assigneeID, err := resolveUserID(ctx, gqlClient, assignee) if err != nil { - return ghErrors.NewGitHubGraphQLErrorResponse(ctx, fmt.Sprintf("failed to resolve assignee %q", assignee), err), nil + return ghErrors.NewGitHubGraphQLErrorResponse(ctx, fmt.Sprintf("failed to resolve assignee %q", assignee), err), nil, nil } assigneeIDs = append(assigneeIDs, assigneeID) } @@ -2913,7 +3131,7 @@ func CreateIssueWithParent( if milestoneNumber != 0 { milestoneID, err := resolveMilestoneID(ctx, gqlClient, owner, repo, milestoneNumber) if err != nil { - return ghErrors.NewGitHubGraphQLErrorResponse(ctx, "failed to resolve milestone", err), nil + return ghErrors.NewGitHubGraphQLErrorResponse(ctx, "failed to resolve milestone", err), nil, nil } input.MilestoneID = &milestoneID } @@ -2921,17 +3139,17 @@ func CreateIssueWithParent( if issueType != "" { issueTypeID, resp, err := resolveIssueTypeID(ctx, client, owner, repo, issueType) if err != nil { - return ghErrors.NewGitHubAPIErrorResponse(ctx, fmt.Sprintf("failed to resolve issue type %q", issueType), resp, err), nil + return ghErrors.NewGitHubAPIErrorResponse(ctx, fmt.Sprintf("failed to resolve issue type %q", issueType), resp, err), nil, nil } input.IssueTypeID = &issueTypeID } var mutation createIssueMutation if err := gqlClient.Mutate(ctx, &mutation, input, nil); err != nil { - return ghErrors.NewGitHubGraphQLErrorResponse(ctx, "failed to create issue", err), nil + return ghErrors.NewGitHubGraphQLErrorResponse(ctx, "failed to create issue", err), nil, nil } if mutation.CreateIssue.Issue.FullDatabaseID == "" || mutation.CreateIssue.Issue.URL.URL == nil { - return utils.NewToolResultError("failed to create issue: response did not include the created issue"), nil + return utils.NewToolResultError("failed to create issue: response did not include the created issue"), nil, nil } response := MinimalResponse{ @@ -2940,9 +3158,9 @@ func CreateIssueWithParent( } encoded, err := json.Marshal(response) if err != nil { - return utils.NewToolResultErrorFromErr("failed to marshal response", err), nil + return utils.NewToolResultErrorFromErr("failed to marshal response", err), nil, nil } - return utils.NewToolResultText(string(encoded)), nil + return utils.NewToolResultText(string(encoded)), &response, nil } func parentRepository(owner, repo, parentOwner, parentRepo string) (string, string) { @@ -3095,14 +3313,19 @@ func containsIssueLabel(labels []string, target string) bool { } func CreateIssue(ctx context.Context, client *github.Client, owner string, repo string, title string, body string, assignees []string, labels []string, milestoneNum int, issueType string, issueFieldValues []*github.IssueRequestFieldValue) (*mcp.CallToolResult, error) { + result, _, err := createIssue(ctx, client, owner, repo, title, body, assignees, labels, milestoneNum, issueType, issueFieldValues) + return result, err +} + +func createIssue(ctx context.Context, client *github.Client, owner string, repo string, title string, body string, assignees []string, labels []string, milestoneNum int, issueType string, issueFieldValues []*github.IssueRequestFieldValue) (*mcp.CallToolResult, *MinimalResponse, error) { if title == "" { - return utils.NewToolResultError("missing required parameter: title"), nil + return utils.NewToolResultError("missing required parameter: title"), nil, nil } // Create the issue request issueRequest := github.CreateIssueRequest{ Title: title, - Body: github.Ptr(body), + Body: new(body), Assignees: assignees, Labels: labels, IssueFieldValues: issueFieldValues, @@ -3113,7 +3336,7 @@ func CreateIssue(ctx context.Context, client *github.Client, owner string, repo } if issueType != "" { - issueRequest.Type = github.Ptr(issueType) + issueRequest.Type = new(issueType) } issue, resp, err := client.Issues.Create(ctx, owner, repo, issueRequest) @@ -3122,21 +3345,21 @@ func CreateIssue(ctx context.Context, client *github.Client, owner string, repo "failed to create issue", resp, err, - ), nil + ), nil, nil } defer func() { _ = resp.Body.Close() }() if resp.StatusCode != http.StatusCreated { body, err := io.ReadAll(resp.Body) if err != nil { - return utils.NewToolResultErrorFromErr("failed to read response body", err), nil + return utils.NewToolResultErrorFromErr("failed to read response body", err), nil, nil } - return ghErrors.NewGitHubAPIStatusErrorResponse(ctx, "failed to create issue", resp, body), nil + return ghErrors.NewGitHubAPIStatusErrorResponse(ctx, "failed to create issue", resp, body), nil, nil } if len(labels) > 0 { if err := unappliedIssueLabelsError(labels, issue); err != nil { - return ghErrors.NewGitHubAPIErrorResponse(ctx, "issue created but requested labels were not fully applied", resp, err), nil + return ghErrors.NewGitHubAPIErrorResponse(ctx, "issue created but requested labels were not fully applied", resp, err), nil, nil } } @@ -3148,10 +3371,10 @@ func CreateIssue(ctx context.Context, client *github.Client, owner string, repo r, err := json.Marshal(minimalResponse) if err != nil { - return utils.NewToolResultErrorFromErr("failed to marshal response", err), nil + return utils.NewToolResultErrorFromErr("failed to marshal response", err), nil, nil } - return utils.NewToolResultText(string(r)), nil + return utils.NewToolResultText(string(r)), &minimalResponse, nil } // UpdateIssueOptions controls which optional fields are included in an issue update request. @@ -3165,9 +3388,14 @@ type UpdateIssueOptions struct { } func UpdateIssue(ctx context.Context, client *github.Client, gqlClient *githubv4.Client, owner string, repo string, issueNumber int, title string, body string, assignees []string, labels []string, milestoneNum int, issueType string, issueFieldValues []*github.IssueRequestFieldValue, fieldIDsToDelete []int64, state string, stateReason string, duplicateOf int, opts ...UpdateIssueOptions) (*mcp.CallToolResult, error) { + result, _, err := updateIssue(ctx, client, gqlClient, owner, repo, issueNumber, title, body, assignees, labels, milestoneNum, issueType, issueFieldValues, fieldIDsToDelete, state, stateReason, duplicateOf, opts...) + return result, err +} + +func updateIssue(ctx context.Context, client *github.Client, gqlClient *githubv4.Client, owner string, repo string, issueNumber int, title string, body string, assignees []string, labels []string, milestoneNum int, issueType string, issueFieldValues []*github.IssueRequestFieldValue, fieldIDsToDelete []int64, state string, stateReason string, duplicateOf int, opts ...UpdateIssueOptions) (*mcp.CallToolResult, *MinimalResponse, error) { // UpdateIssue is exported and may be called without the tool handler. if err := validateDuplicateState(state, stateReason, duplicateOf); err != nil { - return utils.NewToolResultError(err.Error()), nil + return utils.NewToolResultError(err.Error()), nil, nil } updateOptions := UpdateIssueOptions{ @@ -3185,11 +3413,11 @@ func UpdateIssue(ctx context.Context, client *github.Client, gqlClient *githubv4 // Set optional parameters if provided if title != "" { - issueRequest.Title = github.Ptr(title) + issueRequest.Title = new(title) } if body != "" { - issueRequest.Body = github.Ptr(body) + issueRequest.Body = new(body) } if updateOptions.LabelsProvided { @@ -3205,7 +3433,7 @@ func UpdateIssue(ctx context.Context, client *github.Client, gqlClient *githubv4 } if issueType != "" { - issueRequest.Type = github.Ptr(issueType) + issueRequest.Type = new(issueType) } // Field IDs to clear via DELETE after the PATCH. See the post-PATCH loop @@ -3217,7 +3445,7 @@ func UpdateIssue(ctx context.Context, client *github.Client, gqlClient *githubv4 // the new ones, then drop anything explicitly deleted. existing, err := fetchExistingIssueFieldValues(ctx, gqlClient, owner, repo, issueNumber) if err != nil { - return ghErrors.NewGitHubGraphQLErrorResponse(ctx, "failed to fetch existing issue field values", err), nil + return ghErrors.NewGitHubGraphQLErrorResponse(ctx, "failed to fetch existing issue field values", err), nil, nil } merged := mergeIssueFieldValues(existing, issueFieldValues) if len(fieldIDsToDelete) > 0 { @@ -3257,16 +3485,16 @@ func UpdateIssue(ctx context.Context, client *github.Client, gqlClient *githubv4 "failed to update issue", resp, err, - ), nil + ), nil, nil } defer func() { _ = resp.Body.Close() }() if resp.StatusCode != http.StatusOK { body, err := io.ReadAll(resp.Body) if err != nil { - return nil, fmt.Errorf("failed to read response body: %w", err) + return nil, nil, fmt.Errorf("failed to read response body: %w", err) } - return ghErrors.NewGitHubAPIStatusErrorResponse(ctx, "failed to update issue", resp, body), nil + return ghErrors.NewGitHubAPIStatusErrorResponse(ctx, "failed to update issue", resp, body), nil, nil } // Per-field DELETE fallback. The PATCH can't clear field values when the @@ -3302,7 +3530,7 @@ func UpdateIssue(ctx context.Context, client *github.Client, gqlClient *githubv4 } if len(failedIDs) > 0 { msg := fmt.Sprintf("failed to clear issue field values: failed=%v, cleared=%v", failedIDs, succeededIDs) - return ghErrors.NewGitHubAPIErrorResponse(ctx, msg, firstFailureResp, firstFailureErr), nil + return ghErrors.NewGitHubAPIErrorResponse(ctx, msg, firstFailureResp, firstFailureErr), nil, nil } } @@ -3311,7 +3539,7 @@ func UpdateIssue(ctx context.Context, client *github.Client, gqlClient *githubv4 // Get target issue ID (and duplicate issue ID if needed) issueID, duplicateIssueID, err := fetchIssueIDs(ctx, gqlClient, owner, repo, issueNumber, duplicateOf) if err != nil { - return ghErrors.NewGitHubGraphQLErrorResponse(ctx, "Failed to find issues", err), nil + return ghErrors.NewGitHubGraphQLErrorResponse(ctx, "Failed to find issues", err), nil, nil } switch state { @@ -3332,7 +3560,7 @@ func UpdateIssue(ctx context.Context, client *github.Client, gqlClient *githubv4 IssueID: issueID, }, nil) if err != nil { - return ghErrors.NewGitHubGraphQLErrorResponse(ctx, "Failed to reopen issue", err), nil + return ghErrors.NewGitHubGraphQLErrorResponse(ctx, "Failed to reopen issue", err), nil, nil } case "closed": // Use CloseIssue mutation for closing @@ -3360,14 +3588,14 @@ func UpdateIssue(ctx context.Context, client *github.Client, gqlClient *githubv4 err = gqlClient.Mutate(ctx, &mutation, closeInput, nil) if err != nil { - return ghErrors.NewGitHubGraphQLErrorResponse(ctx, "Failed to close issue", err), nil + return ghErrors.NewGitHubGraphQLErrorResponse(ctx, "Failed to close issue", err), nil, nil } } } if updateOptions.LabelsProvided { if err := unappliedIssueLabelsError(labels, updatedIssue); err != nil { - return ghErrors.NewGitHubAPIErrorResponse(ctx, "issue updated but requested labels were not fully applied", resp, err), nil + return ghErrors.NewGitHubAPIErrorResponse(ctx, "issue updated but requested labels were not fully applied", resp, err), nil, nil } } @@ -3379,10 +3607,10 @@ func UpdateIssue(ctx context.Context, client *github.Client, gqlClient *githubv4 r, err := json.Marshal(minimalResponse) if err != nil { - return nil, fmt.Errorf("failed to marshal response: %w", err) + return nil, nil, fmt.Errorf("failed to marshal response: %w", err) } - return utils.NewToolResultText(string(r)), nil + return utils.NewToolResultText(string(r)), &minimalResponse, nil } func validateDuplicateState(state, stateReason string, duplicateOf int) error { @@ -3415,6 +3643,95 @@ func patchIssue(ctx context.Context, client *github.Client, owner, repo string, } // ListIssues creates a tool to list issues in a GitHub repository. +type ListIssuesInput struct { + Owner string `json:"owner"` + Repo string `json:"repo"` + State string `json:"state,omitempty"` + Labels []string `json:"labels,omitempty"` + OrderBy string `json:"orderBy,omitempty"` + Direction string `json:"direction,omitempty"` + Since string `json:"since,omitempty"` + FieldFilters []IssueFieldFilterInput `json:"field_filters,omitempty"` + Fields []string `json:"fields,omitempty"` + After string `json:"after,omitempty"` + PerPage *int `json:"perPage,omitempty"` + Page json.RawMessage `json:"page,omitempty"` +} + +type IssueFieldFilterInput struct { + FieldName string `json:"field_name"` + Value string `json:"value"` +} + +type ListIssuesOutput struct { + Issues []ListIssueOutput `json:"issues"` + TotalCount int `json:"totalCount"` + PageInfo MinimalPageInfo `json:"pageInfo"` +} + +type ListIssueOutput struct { + Number *int `json:"number,omitempty"` + Title *string `json:"title,omitempty"` + Body *string `json:"body,omitempty"` + State *string `json:"state,omitempty"` + User *MinimalUser `json:"user,omitempty"` + Labels *[]string `json:"labels,omitempty"` + Assignees *[]string `json:"assignees,omitempty"` + Comments *int `json:"comments,omitempty"` + CreatedAt *string `json:"created_at,omitempty"` + UpdatedAt *string `json:"updated_at,omitempty"` + FieldValues *[]MinimalFieldValue `json:"field_values,omitempty"` +} + +func structuredListIssuesOutput(response MinimalIssuesResponse, fields []string) ListIssuesOutput { + output := ListIssuesOutput{ + Issues: make([]ListIssueOutput, 0, len(response.Issues)), + TotalCount: response.TotalCount, + PageInfo: response.PageInfo, + } + selected := func(field string) bool { + return len(fields) == 0 || slices.Contains(fields, field) + } + for _, issue := range response.Issues { + item := ListIssueOutput{} + if selected("number") { + item.Number = new(issue.Number) + } + if selected("title") { + item.Title = new(issue.Title) + } + if selected("body") && issue.Body != "" { + item.Body = new(issue.Body) + } + if selected("state") { + item.State = new(issue.State) + } + if selected("user") && issue.User != nil { + item.User = issue.User + } + if selected("labels") && len(issue.Labels) > 0 { + item.Labels = &issue.Labels + } + if selected("assignees") { + item.Assignees = &issue.Assignees + } + if selected("comments") && issue.Comments != 0 { + item.Comments = new(issue.Comments) + } + if selected("created_at") && issue.CreatedAt != "" { + item.CreatedAt = new(issue.CreatedAt) + } + if selected("updated_at") && issue.UpdatedAt != "" { + item.UpdatedAt = new(issue.UpdatedAt) + } + if selected("field_values") && len(issue.FieldValues) > 0 { + item.FieldValues = &issue.FieldValues + } + output.Issues = append(output.Issues, item) + } + return output +} + func ListIssues(t translations.TranslationHelperFunc) inventory.ServerTool { schema := &jsonschema.Schema{ Type: "object", @@ -3480,7 +3797,7 @@ func ListIssues(t translations.TranslationHelperFunc) inventory.ServerTool { ) WithCursorPagination(schema) - st := NewTool( + st := NewTool[ListIssuesInput, ListIssuesOutput]( ToolsetMetadataIssues, mcp.Tool{ Name: "list_issues", @@ -3492,26 +3809,19 @@ func ListIssues(t translations.TranslationHelperFunc) inventory.ServerTool { InputSchema: schema, }, scopes.PublicRead(scopes.Repo), - func(ctx context.Context, deps ToolDependencies, _ *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 + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, input ListIssuesInput) (*mcp.CallToolResult, ListIssuesOutput, error) { + var output ListIssuesOutput + var err error + if input.Owner == "" { + return utils.NewToolResultError("missing required parameter: owner"), output, nil } - repo, err := RequiredParam[string](args, "repo") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - - fields, err := OptionalStringArrayParam(args, "fields") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil + if input.Repo == "" { + return utils.NewToolResultError("missing required parameter: repo"), output, nil } + owner, repo := input.Owner, input.Repo // Set optional parameters if provided - state, err := OptionalParam[string](args, "state") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } + state := input.State // Normalize and filter by state state = strings.ToUpper(state) @@ -3525,20 +3835,9 @@ func ListIssues(t translations.TranslationHelperFunc) inventory.ServerTool { } // Get labels - labels, err := OptionalStringArrayParam(args, "labels") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - - orderBy, err := OptionalParam[string](args, "orderBy") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - - direction, err := OptionalParam[string](args, "direction") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } + labels := input.Labels + orderBy := input.OrderBy + direction := input.Direction // Normalize and validate orderBy orderBy = strings.ToUpper(orderBy) @@ -3558,10 +3857,7 @@ func ListIssues(t translations.TranslationHelperFunc) inventory.ServerTool { direction = "DESC" } - since, err := OptionalParam[string](args, "since") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } + since := input.Since // There are two optional parameters: since and labels. var sinceTime time.Time @@ -3569,35 +3865,40 @@ func ListIssues(t translations.TranslationHelperFunc) inventory.ServerTool { if since != "" { sinceTime, err = parseISOTimestamp(since) if err != nil { - return utils.NewToolResultError(fmt.Sprintf("failed to list issues: %s", err.Error())), nil, nil + return utils.NewToolResultError(fmt.Sprintf("failed to list issues: %s", err.Error())), output, nil } hasSince = true } hasLabels := len(labels) > 0 - rawFilters, err := parseRawFieldFilters(args) - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil + rawFilters := make([]rawFieldFilter, 0, len(input.FieldFilters)) + for _, filter := range input.FieldFilters { + if filter.FieldName == "" { + return utils.NewToolResultError("field_filters entry: missing required parameter: field_name"), output, nil + } + if filter.Value == "" { + return utils.NewToolResultError(fmt.Sprintf("field_filters entry %q: missing required parameter: value", filter.FieldName)), output, nil + } + rawFilters = append(rawFilters, rawFieldFilter{Name: filter.FieldName, Value: filter.Value}) } // Get pagination parameters and convert to GraphQL format - pagination, err := OptionalCursorPaginationParams(args) - if err != nil { - return nil, nil, err + pagination := CursorPaginationParams{PerPage: 30, After: input.After} + if input.PerPage != nil { + pagination.PerPage = *input.PerPage } // Check if someone tried to use page-based pagination instead of cursor-based - if _, pageProvided := args["page"]; pageProvided { - return utils.NewToolResultError("This tool uses cursor-based pagination. Use the 'after' parameter with the 'endCursor' value from the previous response instead of 'page'."), nil, nil + if len(input.Page) > 0 { + return utils.NewToolResultError("This tool uses cursor-based pagination. Use the 'after' parameter with the 'endCursor' value from the previous response instead of 'page'."), output, nil } // Check if pagination parameters were explicitly provided - _, perPageProvided := args["perPage"] - paginationExplicit := perPageProvided + paginationExplicit := input.PerPage != nil paginationParams, err := pagination.ToGraphQLParams() if err != nil { - return nil, nil, err + return nil, output, err } // Use default of 30 if pagination was not explicitly provided @@ -3608,7 +3909,7 @@ func ListIssues(t translations.TranslationHelperFunc) inventory.ServerTool { client, err := deps.GetGQLClient(ctx) if err != nil { - return utils.NewToolResultError(fmt.Sprintf("failed to get GitHub GQL client: %v", err)), nil, nil + return utils.NewToolResultError(fmt.Sprintf("failed to get GitHub GQL client: %v", err)), output, nil } // Resolve field filters by looking up the repo's issue fields so we can @@ -3617,11 +3918,11 @@ func ListIssues(t translations.TranslationHelperFunc) inventory.ServerTool { if len(rawFilters) > 0 { fields, err := fetchIssueFields(ctx, client, owner, repo) if err != nil { - return ghErrors.NewGitHubGraphQLErrorResponse(ctx, "failed to look up issue fields for field_filters", err), nil, nil + return ghErrors.NewGitHubGraphQLErrorResponse(ctx, "failed to look up issue fields for field_filters", err), output, nil } fieldFilters, err = resolveFieldFilters(rawFilters, fields) if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil + return utils.NewToolResultError(err.Error()), output, nil } } @@ -3674,7 +3975,7 @@ func ListIssues(t translations.TranslationHelperFunc) inventory.ServerTool { ctx, "failed to list issues", issueFieldsErr, - ), nil, nil + ), output, nil } issueQueryWithoutFieldValues := getIssueQueryTypeWithoutFieldValues(hasLabels, hasSince) @@ -3689,7 +3990,7 @@ func ListIssues(t translations.TranslationHelperFunc) inventory.ServerTool { ctx, "failed to list issues", fmt.Errorf("issue-fields query failed: %w; fallback query failed: %w", issueFieldsErr, fallbackErr), - ), nil, nil + ), output, nil } resp = convertToMinimalIssuesResponseWithoutFieldValues(issueQueryWithoutFieldValues.getIssueFragmentWithoutFieldValues()) @@ -3698,10 +3999,10 @@ func ListIssues(t translations.TranslationHelperFunc) inventory.ServerTool { filtered := false var payload any = resp - if len(fields) > 0 { - filteredIssues, err := filterEachField(resp.Issues, fields) + if len(input.Fields) > 0 { + filteredIssues, err := filterEachField(resp.Issues, input.Fields) if err != nil { - return utils.NewToolResultErrorFromErr("failed to filter issues", err), nil, nil + return utils.NewToolResultErrorFromErr("failed to filter issues", err), output, nil } payload = map[string]any{ "issues": filteredIssues, @@ -3713,15 +4014,17 @@ func ListIssues(t translations.TranslationHelperFunc) inventory.ServerTool { r, err := json.Marshal(payload) if err != nil { - return utils.NewToolResultErrorFromErr("failed to marshal response", err), nil, nil + return utils.NewToolResultErrorFromErr("failed to marshal response", err), output, nil } recordFieldsUsageFor(ctx, deps, "list_issues", resp, filtered, len(r)) result := utils.NewToolResultText(string(r)) result = attachStaticIFCLabel(ctx, deps, result, ifc.LabelListIssues(isPrivate)) - return result, nil, nil - }) + return result, structuredListIssuesOutput(resp, input.Fields), nil + }, + normalizeTypedReadArguments([]string{"state", "orderBy", "direction"}, true), + ) return st } @@ -3731,46 +4034,6 @@ type rawFieldFilter struct { Value string } -// parseRawFieldFilters extracts the optional field_filters parameter into a list of -// {name, value} pairs. The value is always a string here; type-aware coercion happens -// later in resolveFieldFilters once we know each field's data_type. -func parseRawFieldFilters(args map[string]any) ([]rawFieldFilter, error) { - raw, ok := args["field_filters"] - if !ok { - return nil, nil - } - - var entries []map[string]any - switch v := raw.(type) { - case []any: - for _, f := range v { - entry, ok := f.(map[string]any) - if !ok { - return nil, fmt.Errorf("each field_filters entry must be an object") - } - entries = append(entries, entry) - } - case []map[string]any: - entries = v - default: - return nil, fmt.Errorf("field_filters must be an array") - } - - filters := make([]rawFieldFilter, 0, len(entries)) - for _, entry := range entries { - fieldName, err := RequiredParam[string](entry, "field_name") - if err != nil { - return nil, fmt.Errorf("field_filters entry: %s", err.Error()) - } - value, err := RequiredParam[string](entry, "value") - if err != nil { - return nil, fmt.Errorf("field_filters entry %q: %s", fieldName, err.Error()) - } - filters = append(filters, rawFieldFilter{Name: fieldName, Value: value}) - } - return filters, nil -} - // resolveFieldFilters matches each raw filter against a known field definition and // coerces the value into the right typed slot on IssueFieldValueFilter. Matching is // case-insensitive on field name; option names are also matched case-insensitively for diff --git a/pkg/github/issues_delete_test.go b/pkg/github/issues_delete_test.go index 11239e3a99..a8e403af32 100644 --- a/pkg/github/issues_delete_test.go +++ b/pkg/github/issues_delete_test.go @@ -9,8 +9,8 @@ import ( "sync" "testing" - "github.com/github/github-mcp-server/internal/githubv4mock" - gogithub "github.com/google/go-github/v89/github" + "github.com/github/github-mcp-server/v2/internal/githubv4mock" + gogithub "github.com/google/go-github/v92/github" "github.com/shurcooL/githubv4" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -24,7 +24,7 @@ func Test_IssueRequest_EmptyFieldValues_OmittedByJSON(t *testing.T) { t.Parallel() req := &gogithub.UpdateIssueRequest{ - Title: gogithub.Ptr("still here"), + Title: new("still here"), IssueFieldValues: []*gogithub.IssueRequestFieldValue{}, } body, err := json.Marshal(req) @@ -44,10 +44,10 @@ func Test_UpdateIssue_DeleteLastFieldValueCallsDeleteEndpoint(t *testing.T) { t.Parallel() mockIssue := &gogithub.Issue{ - Number: gogithub.Ptr(42), - Title: gogithub.Ptr("Test issue"), - State: gogithub.Ptr("open"), - HTMLURL: gogithub.Ptr("https://github.com/owner/repo/issues/42"), + Number: new(42), + Title: new("Test issue"), + State: new("open"), + HTMLURL: new("https://github.com/owner/repo/issues/42"), } var ( @@ -145,10 +145,10 @@ func Test_UpdateIssue_DeleteOneOfManyUsesSetSemantics(t *testing.T) { t.Parallel() mockIssue := &gogithub.Issue{ - Number: gogithub.Ptr(42), - Title: gogithub.Ptr("Test issue"), - State: gogithub.Ptr("open"), - HTMLURL: gogithub.Ptr("https://github.com/owner/repo/issues/42"), + Number: new(42), + Title: new("Test issue"), + State: new("open"), + HTMLURL: new("https://github.com/owner/repo/issues/42"), } var ( @@ -242,10 +242,10 @@ func Test_UpdateIssue_DeleteAbsentFieldIsNoOp(t *testing.T) { t.Parallel() mockIssue := &gogithub.Issue{ - Number: gogithub.Ptr(42), - Title: gogithub.Ptr("Test issue"), - State: gogithub.Ptr("open"), - HTMLURL: gogithub.Ptr("https://github.com/owner/repo/issues/42"), + Number: new(42), + Title: new("Test issue"), + State: new("open"), + HTMLURL: new("https://github.com/owner/repo/issues/42"), } var ( @@ -334,10 +334,10 @@ func Test_UpdateIssue_DeleteFallbackContinuesOnPartialFailure(t *testing.T) { t.Parallel() mockIssue := &gogithub.Issue{ - Number: gogithub.Ptr(42), - Title: gogithub.Ptr("Test issue"), - State: gogithub.Ptr("open"), - HTMLURL: gogithub.Ptr("https://github.com/owner/repo/issues/42"), + Number: new(42), + Title: new("Test issue"), + State: new("open"), + HTMLURL: new("https://github.com/owner/repo/issues/42"), } var ( diff --git a/pkg/github/issues_granular.go b/pkg/github/issues_granular.go index f22a8a1536..eab4a204cd 100644 --- a/pkg/github/issues_granular.go +++ b/pkg/github/issues_granular.go @@ -2,18 +2,17 @@ package github import ( "context" - "encoding/json" "fmt" "maps" "strings" - ghcontext "github.com/github/github-mcp-server/pkg/context" - ghErrors "github.com/github/github-mcp-server/pkg/errors" - "github.com/github/github-mcp-server/pkg/inventory" - "github.com/github/github-mcp-server/pkg/scopes" - "github.com/github/github-mcp-server/pkg/translations" - "github.com/github/github-mcp-server/pkg/utils" - "github.com/google/go-github/v89/github" + ghcontext "github.com/github/github-mcp-server/v2/pkg/context" + ghErrors "github.com/github/github-mcp-server/v2/pkg/errors" + "github.com/github/github-mcp-server/v2/pkg/inventory" + "github.com/github/github-mcp-server/v2/pkg/scopes" + "github.com/github/github-mcp-server/v2/pkg/translations" + "github.com/github/github-mcp-server/v2/pkg/utils" + "github.com/google/go-github/v92/github" "github.com/google/jsonschema-go/jsonschema" "github.com/modelcontextprotocol/go-sdk/mcp" "github.com/shurcooL/githubv4" @@ -24,12 +23,15 @@ func normalizeConfidence(confidence string) string { } // issueUpdateTool is a helper to create single-field issue update tools. -func issueUpdateTool( +func issueUpdateTool[In interface { + issueCoordinate() GranularIssueCoordinate +}]( t translations.TranslationHelperFunc, name, description, title string, extraProps map[string]*jsonschema.Schema, extraRequired []string, - buildRequest func(args map[string]any) (github.UpdateIssueRequest, error), + buildRequest func(args In) github.UpdateIssueRequest, + normalizer inventory.InputNormalizer, ) inventory.ServerTool { props := map[string]*jsonschema.Schema{ "owner": { @@ -43,14 +45,14 @@ func issueUpdateTool( "issue_number": { Type: "number", Description: "The issue number to update", - Minimum: jsonschema.Ptr(1.0), + Minimum: new(1.0), }, } maps.Copy(props, extraProps) required := append([]string{"owner", "repo", "issue_number"}, extraRequired...) - st := NewTool( + st := NewTool[In, *MinimalResponse]( ToolsetMetadataIssues, mcp.Tool{ Name: name, @@ -58,8 +60,8 @@ func issueUpdateTool( Annotations: &mcp.ToolAnnotations{ Title: t("TOOL_"+strings.ToUpper(name)+"_USER_TITLE", title), ReadOnlyHint: false, - DestructiveHint: jsonschema.Ptr(false), - OpenWorldHint: jsonschema.Ptr(true), + DestructiveHint: new(false), + OpenWorldHint: new(true), }, InputSchema: &jsonschema.Schema{ Type: "object", @@ -68,24 +70,10 @@ func issueUpdateTool( }, }, scopes.RequireAll(scopes.Repo), - func(ctx context.Context, deps ToolDependencies, _ *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 - } - repo, err := RequiredParam[string](args, "repo") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - issueNumber, err := RequiredInt(args, "issue_number") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - - issueReq, err := buildRequest(args) - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, args In) (*mcp.CallToolResult, *MinimalResponse, error) { + coordinate := args.issueCoordinate() + owner, repo, issueNumber := coordinate.Owner, coordinate.Repo, coordinate.IssueNumber + issueReq := buildRequest(args) client, err := deps.GetClient(ctx) if err != nil { @@ -98,15 +86,12 @@ func issueUpdateTool( } defer func() { _ = resp.Body.Close() }() - r, err := json.Marshal(MinimalResponse{ + return granularIssueMinimalResult(&MinimalResponse{ ID: fmt.Sprintf("%d", issue.GetID()), URL: issue.GetHTMLURL(), }) - if err != nil { - return utils.NewToolResultErrorFromErr("failed to marshal response", err), nil, nil - } - return utils.NewToolResultText(string(r)), nil, nil }, + normalizer, ) st.FeatureRule = issuesGranularFeatureRule return st @@ -114,7 +99,7 @@ func issueUpdateTool( // GranularCreateIssue creates a tool to create a new issue. func GranularCreateIssue(t translations.TranslationHelperFunc) inventory.ServerTool { - st := NewTool( + st := NewTool[GranularCreateIssueInput, *MinimalResponse]( ToolsetMetadataIssues, mcp.Tool{ Name: "create_issue", @@ -122,8 +107,8 @@ func GranularCreateIssue(t translations.TranslationHelperFunc) inventory.ServerT Annotations: &mcp.ToolAnnotations{ Title: t("TOOL_CREATE_ISSUE_USER_TITLE", "Create Issue"), ReadOnlyHint: false, - DestructiveHint: jsonschema.Ptr(false), - OpenWorldHint: jsonschema.Ptr(true), + DestructiveHint: new(false), + OpenWorldHint: new(true), }, InputSchema: &jsonschema.Schema{ Type: "object", @@ -147,7 +132,7 @@ func GranularCreateIssue(t translations.TranslationHelperFunc) inventory.ServerT "parent_issue_number": { Type: "number", Description: "Issue number of the parent issue. The new issue is created and attached to this parent in the same operation.", - Minimum: jsonschema.Ptr(1.0), + Minimum: new(1.0), }, "parent_owner": { Type: "string", @@ -162,44 +147,15 @@ func GranularCreateIssue(t translations.TranslationHelperFunc) inventory.ServerT }, }, scopes.RequireAll(scopes.Repo), - func(ctx context.Context, deps ToolDependencies, _ *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 - } - repo, err := RequiredParam[string](args, "repo") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - title, err := RequiredParam[string](args, "title") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - body, _ := OptionalParam[string](args, "body") - parentIssueNumber, err := OptionalIntParam(args, "parent_issue_number") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - parentValue, parentProvided := args["parent_issue_number"] - parentProvided = parentProvided && parentValue != nil - if parentProvided && parentIssueNumber < 1 { - return utils.NewToolResultError("parent_issue_number must be greater than 0"), nil, nil - } - parentOwner, err := OptionalParam[string](args, "parent_owner") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - parentRepo, err := OptionalParam[string](args, "parent_repo") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - if err := validateParentRepository(parentProvided, parentOwner, parentRepo); err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - - issueReq := github.CreateIssueRequest{ - Title: title, + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, args GranularCreateIssueInput) (*mcp.CallToolResult, *MinimalResponse, error) { + owner, repo, title, body := args.Owner, args.Repo, args.Title, args.Body + parentProvided := args.ParentIssueNumber != nil + parentIssueNumber := 0 + if parentProvided { + parentIssueNumber = *args.ParentIssueNumber } + parentOwner, parentRepo := args.ParentOwner, args.ParentRepo + issueReq := github.CreateIssueRequest{Title: title} if body != "" { issueReq.Body = &body } @@ -214,8 +170,8 @@ func GranularCreateIssue(t translations.TranslationHelperFunc) inventory.ServerT if err != nil { return utils.NewToolResultErrorFromErr("failed to get GitHub GraphQL client", err), nil, nil } - result, err := CreateIssueWithParent(ctx, client, gqlClient, owner, repo, title, body, nil, nil, 0, "", parentIssueNumber, parentOwner, parentRepo) - return result, nil, err + result, output, err := createIssueWithParent(ctx, client, gqlClient, owner, repo, title, body, nil, nil, 0, "", parentIssueNumber, parentOwner, parentRepo) + return result, output, err } issue, resp, err := client.Issues.Create(ctx, owner, repo, issueReq) @@ -224,15 +180,12 @@ func GranularCreateIssue(t translations.TranslationHelperFunc) inventory.ServerT } defer func() { _ = resp.Body.Close() }() - r, err := json.Marshal(MinimalResponse{ + return granularIssueMinimalResult(&MinimalResponse{ ID: fmt.Sprintf("%d", issue.GetID()), URL: issue.GetHTMLURL(), }) - if err != nil { - return utils.NewToolResultErrorFromErr("failed to marshal response", err), nil, nil - } - return utils.NewToolResultText(string(r)), nil, nil }, + granularIssueInputNormalizer(normalizeGranularCreateIssueArguments), ) st.FeatureRule = issuesGranularFeatureRule return st @@ -248,13 +201,10 @@ func GranularUpdateIssueTitle(t translations.TranslationHelperFunc) inventory.Se "title": {Type: "string", Description: "The new title for the issue"}, }, []string{"title"}, - func(args map[string]any) (github.UpdateIssueRequest, error) { - title, err := RequiredParam[string](args, "title") - if err != nil { - return github.UpdateIssueRequest{}, err - } - return github.UpdateIssueRequest{Title: &title}, nil + func(args GranularIssueTitleInput) github.UpdateIssueRequest { + return github.UpdateIssueRequest{Title: &args.Title} }, + granularIssueInputNormalizer(normalizeGranularIssueUpdateArguments("title")), ) } @@ -268,19 +218,16 @@ func GranularUpdateIssueBody(t translations.TranslationHelperFunc) inventory.Ser "body": {Type: "string", Description: "The new body content for the issue"}, }, []string{"body"}, - func(args map[string]any) (github.UpdateIssueRequest, error) { - body, err := RequiredParam[string](args, "body") - if err != nil { - return github.UpdateIssueRequest{}, err - } - return github.UpdateIssueRequest{Body: &body}, nil + func(args GranularIssueBodyInput) github.UpdateIssueRequest { + return github.UpdateIssueRequest{Body: &args.Body} }, + granularIssueInputNormalizer(normalizeGranularIssueUpdateArguments("body")), ) } // GranularUpdateIssueAssignees creates a tool to update an issue's assignees. func GranularUpdateIssueAssignees(t translations.TranslationHelperFunc) inventory.ServerTool { - st := NewTool( + st := NewTool[GranularIssueAssigneesInput, *MinimalResponse]( ToolsetMetadataIssues, mcp.Tool{ Name: "update_issue_assignees", @@ -288,8 +235,8 @@ func GranularUpdateIssueAssignees(t translations.TranslationHelperFunc) inventor Annotations: &mcp.ToolAnnotations{ Title: t("TOOL_UPDATE_ISSUE_ASSIGNEES_USER_TITLE", "Update Issue Assignees"), ReadOnlyHint: false, - DestructiveHint: jsonschema.Ptr(false), - OpenWorldHint: jsonschema.Ptr(true), + DestructiveHint: new(false), + OpenWorldHint: new(true), }, InputSchema: &jsonschema.Schema{ Type: "object", @@ -305,7 +252,7 @@ func GranularUpdateIssueAssignees(t translations.TranslationHelperFunc) inventor "issue_number": { Type: "number", Description: "The issue number to update", - Minimum: jsonschema.Ptr(1.0), + Minimum: new(1.0), }, "assignees": { Type: "array", @@ -324,7 +271,7 @@ func GranularUpdateIssueAssignees(t translations.TranslationHelperFunc) inventor Type: "string", Description: "One concise sentence explaining what specifically about the issue led you to choose this assignee. " + "State the concrete signal (e.g. 'Authored the file the crash originates in').", - MaxLength: jsonschema.Ptr(280), + MaxLength: new(280), }, "confidence": { Type: "string", @@ -347,95 +294,15 @@ func GranularUpdateIssueAssignees(t translations.TranslationHelperFunc) inventor }, }, scopes.RequireAll(scopes.Repo), - func(ctx context.Context, deps ToolDependencies, _ *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 - } - repo, err := RequiredParam[string](args, "repo") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - issueNumber, err := RequiredInt(args, "issue_number") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - - assigneesRaw, ok := args["assignees"] - if !ok { - return utils.NewToolResultError("missing required parameter: assignees"), nil, nil - } - assigneesSlice, ok := assigneesRaw.([]any) - if !ok { - // Also accept []string for callers that pre-typed the array. - if strs, ok := assigneesRaw.([]string); ok { - assigneesSlice = make([]any, len(strs)) - for i, s := range strs { - assigneesSlice[i] = s - } - } else { - return utils.NewToolResultError("parameter assignees must be an array"), nil, nil - } - } - - useObjectForm := false - payload := make([]any, 0, len(assigneesSlice)) - for _, item := range assigneesSlice { - switch v := item.(type) { - case string: - payload = append(payload, v) - case map[string]any: - login, err := RequiredParam[string](v, "login") - if err != nil { - return utils.NewToolResultError("each assignee object must have a 'login' string"), nil, nil - } - rationale, err := OptionalParam[string](v, "rationale") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - rationale = strings.TrimSpace(rationale) - if len([]rune(rationale)) > 280 { - return utils.NewToolResultError("assignee rationale must be 280 characters or less"), nil, nil - } - confidence, err := OptionalParam[string](v, "confidence") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - confidence = normalizeConfidence(confidence) - if confidence != "" && confidence != "LOW" && confidence != "MEDIUM" && confidence != "HIGH" { - return utils.NewToolResultError("confidence must be one of: LOW, MEDIUM, HIGH"), nil, nil - } - isSuggestion, err := OptionalParam[bool](v, "is_suggestion") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - if rationale == "" && !isSuggestion && confidence == "" { - payload = append(payload, login) - } else { - useObjectForm = true - payload = append(payload, assigneeWithIntent{Login: login, Rationale: rationale, Confidence: confidence, Suggest: isSuggestion}) - } - default: - return utils.NewToolResultError("each assignee must be a string or an object with 'login' and optional 'rationale', 'confidence', and/or 'is_suggestion'"), nil, nil - } - } + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, args GranularIssueAssigneesInput) (*mcp.CallToolResult, *MinimalResponse, error) { + owner, repo, issueNumber := args.Owner, args.Repo, args.IssueNumber client, err := deps.GetClient(ctx) if err != nil { return utils.NewToolResultErrorFromErr("failed to get GitHub client", err), nil, nil } - var body any - if useObjectForm { - body = &assigneesUpdateRequest{Assignees: payload} - } else { - // Preserve the standard wire format when no rationale or suggest is supplied. - logins := make([]string, len(payload)) - for i, p := range payload { - logins[i] = p.(string) - } - body = &github.UpdateIssueRequest{Assignees: logins} - } + body := granularIssueAssigneesPayload(args.Assignees) apiURL := fmt.Sprintf("repos/%s/%s/issues/%d", owner, repo, issueNumber) req, err := client.NewRequest(ctx, "PATCH", apiURL, body) @@ -450,15 +317,12 @@ func GranularUpdateIssueAssignees(t translations.TranslationHelperFunc) inventor } defer func() { _ = resp.Body.Close() }() - r, err := json.Marshal(MinimalResponse{ + return granularIssueMinimalResult(&MinimalResponse{ ID: fmt.Sprintf("%d", issue.GetID()), URL: issue.GetHTMLURL(), }) - if err != nil { - return utils.NewToolResultErrorFromErr("failed to marshal response", err), nil, nil - } - return utils.NewToolResultText(string(r)), nil, nil }, + granularIssueInputNormalizer(normalizeGranularUpdateIssueAssigneesArguments), ) st.FeatureRule = issuesGranularFeatureRule return st @@ -498,7 +362,7 @@ type assigneesUpdateRequest struct { // GranularUpdateIssueLabels creates a tool to update an issue's labels. func GranularUpdateIssueLabels(t translations.TranslationHelperFunc) inventory.ServerTool { - st := NewTool( + st := NewTool[GranularIssueLabelsInput, *MinimalResponse]( ToolsetMetadataIssues, mcp.Tool{ Name: "update_issue_labels", @@ -506,8 +370,8 @@ func GranularUpdateIssueLabels(t translations.TranslationHelperFunc) inventory.S Annotations: &mcp.ToolAnnotations{ Title: t("TOOL_UPDATE_ISSUE_LABELS_USER_TITLE", "Update Issue Labels"), ReadOnlyHint: false, - DestructiveHint: jsonschema.Ptr(false), - OpenWorldHint: jsonschema.Ptr(true), + DestructiveHint: new(false), + OpenWorldHint: new(true), }, InputSchema: &jsonschema.Schema{ Type: "object", @@ -523,7 +387,7 @@ func GranularUpdateIssueLabels(t translations.TranslationHelperFunc) inventory.S "issue_number": { Type: "number", Description: "The issue number to update", - Minimum: jsonschema.Ptr(1.0), + Minimum: new(1.0), }, "labels": { Type: "array", @@ -542,7 +406,7 @@ func GranularUpdateIssueLabels(t translations.TranslationHelperFunc) inventory.S Type: "string", Description: "One concise sentence explaining what specifically about the issue led you to choose this label. " + "State the concrete signal (e.g. 'Reports a crash when saving' → bug).", - MaxLength: jsonschema.Ptr(280), + MaxLength: new(280), }, "confidence": { Type: "string", @@ -565,95 +429,15 @@ func GranularUpdateIssueLabels(t translations.TranslationHelperFunc) inventory.S }, }, scopes.RequireAll(scopes.Repo), - func(ctx context.Context, deps ToolDependencies, _ *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 - } - repo, err := RequiredParam[string](args, "repo") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - issueNumber, err := RequiredInt(args, "issue_number") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - - labelsRaw, ok := args["labels"] - if !ok { - return utils.NewToolResultError("missing required parameter: labels"), nil, nil - } - labelsSlice, ok := labelsRaw.([]any) - if !ok { - // Also accept []string for callers that pre-typed the array. - if strs, ok := labelsRaw.([]string); ok { - labelsSlice = make([]any, len(strs)) - for i, s := range strs { - labelsSlice[i] = s - } - } else { - return utils.NewToolResultError("parameter labels must be an array"), nil, nil - } - } - - useObjectForm := false - payload := make([]any, 0, len(labelsSlice)) - for _, item := range labelsSlice { - switch v := item.(type) { - case string: - payload = append(payload, v) - case map[string]any: - name, err := RequiredParam[string](v, "name") - if err != nil { - return utils.NewToolResultError("each label object must have a 'name' string"), nil, nil - } - rationale, err := OptionalParam[string](v, "rationale") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - rationale = strings.TrimSpace(rationale) - if len([]rune(rationale)) > 280 { - return utils.NewToolResultError("label rationale must be 280 characters or less"), nil, nil - } - confidence, err := OptionalParam[string](v, "confidence") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - confidence = normalizeConfidence(confidence) - if confidence != "" && confidence != "LOW" && confidence != "MEDIUM" && confidence != "HIGH" { - return utils.NewToolResultError("confidence must be one of: LOW, MEDIUM, HIGH"), nil, nil - } - isSuggestion, err := OptionalParam[bool](v, "is_suggestion") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - if rationale == "" && !isSuggestion && confidence == "" { - payload = append(payload, name) - } else { - useObjectForm = true - payload = append(payload, labelWithIntent{Name: name, Rationale: rationale, Confidence: confidence, Suggest: isSuggestion}) - } - default: - return utils.NewToolResultError("each label must be a string or an object with 'name' and optional 'rationale', 'confidence', and/or 'is_suggestion'"), nil, nil - } - } + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, args GranularIssueLabelsInput) (*mcp.CallToolResult, *MinimalResponse, error) { + owner, repo, issueNumber := args.Owner, args.Repo, args.IssueNumber client, err := deps.GetClient(ctx) if err != nil { return utils.NewToolResultErrorFromErr("failed to get GitHub client", err), nil, nil } - var body any - if useObjectForm { - body = &labelsUpdateRequest{Labels: payload} - } else { - // Preserve the standard wire format when no rationale or suggest is supplied. - names := make([]string, len(payload)) - for i, p := range payload { - names[i] = p.(string) - } - body = &github.UpdateIssueRequest{Labels: names} - } + body := granularIssueLabelsPayload(args.Labels) apiURL := fmt.Sprintf("repos/%s/%s/issues/%d", owner, repo, issueNumber) req, err := client.NewRequest(ctx, "PATCH", apiURL, body) @@ -668,15 +452,12 @@ func GranularUpdateIssueLabels(t translations.TranslationHelperFunc) inventory.S } defer func() { _ = resp.Body.Close() }() - r, err := json.Marshal(MinimalResponse{ + return granularIssueMinimalResult(&MinimalResponse{ ID: fmt.Sprintf("%d", issue.GetID()), URL: issue.GetHTMLURL(), }) - if err != nil { - return utils.NewToolResultErrorFromErr("failed to marshal response", err), nil, nil - } - return utils.NewToolResultText(string(r)), nil, nil }, + granularIssueInputNormalizer(normalizeGranularUpdateIssueLabelsArguments), ) st.FeatureRule = issuesGranularFeatureRule return st @@ -692,17 +473,14 @@ func GranularUpdateIssueMilestone(t translations.TranslationHelperFunc) inventor "milestone": { Type: "integer", Description: "The milestone number to set on the issue", - Minimum: jsonschema.Ptr(1.0), + Minimum: new(1.0), }, }, []string{"milestone"}, - func(args map[string]any) (github.UpdateIssueRequest, error) { - milestone, err := RequiredInt(args, "milestone") - if err != nil { - return github.UpdateIssueRequest{}, err - } - return github.UpdateIssueRequest{Milestone: &milestone}, nil + func(args GranularIssueMilestoneInput) github.UpdateIssueRequest { + return github.UpdateIssueRequest{Milestone: &args.Milestone} }, + granularIssueInputNormalizer(normalizeGranularIssueUpdateArguments("milestone")), ) } @@ -723,7 +501,7 @@ type issueTypeUpdateRequest struct { // GranularUpdateIssueType creates a tool to set or clear an issue's type. func GranularUpdateIssueType(t translations.TranslationHelperFunc) inventory.ServerTool { - st := NewTool( + st := NewTool[GranularIssueTypeInput, *MinimalResponse]( ToolsetMetadataIssues, mcp.Tool{ Name: "update_issue_type", @@ -731,8 +509,8 @@ func GranularUpdateIssueType(t translations.TranslationHelperFunc) inventory.Ser Annotations: &mcp.ToolAnnotations{ Title: t("TOOL_UPDATE_ISSUE_TYPE_USER_TITLE", "Update Issue Type"), ReadOnlyHint: false, - DestructiveHint: jsonschema.Ptr(false), - OpenWorldHint: jsonschema.Ptr(true), + DestructiveHint: new(false), + OpenWorldHint: new(true), }, InputSchema: &jsonschema.Schema{ Type: "object", @@ -748,11 +526,11 @@ func GranularUpdateIssueType(t translations.TranslationHelperFunc) inventory.Ser "issue_number": { Type: "number", Description: "The issue number to update", - Minimum: jsonschema.Ptr(1.0), + Minimum: new(1.0), }, "issue_type": { AnyOf: []*jsonschema.Schema{ - {Type: "string", MinLength: jsonschema.Ptr(1)}, + {Type: "string", MinLength: new(1)}, {Type: "null"}, }, Description: "The issue type to set, or null to remove the current type", @@ -761,7 +539,7 @@ func GranularUpdateIssueType(t translations.TranslationHelperFunc) inventory.Ser Type: "string", Description: "One concise sentence explaining what specifically about the issue led you to choose this type. " + "State the concrete signal (e.g. 'Reports a crash when saving' → bug, 'Asks for dark mode support' → feature).", - MaxLength: jsonschema.Ptr(280), + MaxLength: new(280), }, "confidence": { Type: "string", @@ -778,49 +556,10 @@ func GranularUpdateIssueType(t translations.TranslationHelperFunc) inventory.Ser }, }, scopes.RequireAll(scopes.Repo), - func(ctx context.Context, deps ToolDependencies, _ *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 - } - repo, err := RequiredParam[string](args, "repo") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - issueNumber, err := RequiredInt(args, "issue_number") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - issueType, issueTypeProvided, err := OptionalNullableStringParam(args, "issue_type") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - if !issueTypeProvided { - return utils.NewToolResultError("missing required parameter: issue_type"), nil, nil - } - rationale, err := OptionalParam[string](args, "rationale") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - rationale = strings.TrimSpace(rationale) - if len([]rune(rationale)) > 280 { - return utils.NewToolResultError("parameter rationale must be 280 characters or less"), nil, nil - } - confidence, err := OptionalParam[string](args, "confidence") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - confidence = normalizeConfidence(confidence) - if confidence != "" && confidence != "LOW" && confidence != "MEDIUM" && confidence != "HIGH" { - return utils.NewToolResultError("confidence must be one of: LOW, MEDIUM, HIGH"), nil, nil - } - isSuggestion, err := OptionalParam[bool](args, "is_suggestion") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - if issueType == nil && (rationale != "" || confidence != "" || isSuggestion) { - return utils.NewToolResultError("suggestion metadata is not supported when removing an issue type; omit rationale, confidence, and is_suggestion"), nil, nil - } + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, args GranularIssueTypeInput) (*mcp.CallToolResult, *MinimalResponse, error) { + owner, repo, issueNumber := args.Owner, args.Repo, args.IssueNumber + issueType, rationale, confidence, isSuggestion := args.IssueType, args.Rationale, args.Confidence, args.IsSuggestion + client, err := deps.GetClient(ctx) if err != nil { return utils.NewToolResultErrorFromErr("failed to get GitHub client", err), nil, nil @@ -856,15 +595,12 @@ func GranularUpdateIssueType(t translations.TranslationHelperFunc) inventory.Ser } defer func() { _ = resp.Body.Close() }() - r, err := json.Marshal(MinimalResponse{ + return granularIssueMinimalResult(&MinimalResponse{ ID: fmt.Sprintf("%d", issue.GetID()), URL: issue.GetHTMLURL(), }) - if err != nil { - return utils.NewToolResultErrorFromErr("failed to marshal response", err), nil, nil - } - return utils.NewToolResultText(string(r)), nil, nil }, + granularIssueInputNormalizer(normalizeGranularUpdateIssueTypeArguments), ) st.FeatureRule = issuesGranularFeatureRule return st @@ -889,7 +625,7 @@ type stateUpdateRequest struct { // GranularUpdateIssueState creates a tool to update an issue's state. func GranularUpdateIssueState(t translations.TranslationHelperFunc) inventory.ServerTool { - st := NewTool( + st := NewTool[GranularIssueStateInput, *MinimalResponse]( ToolsetMetadataIssues, mcp.Tool{ Name: "update_issue_state", @@ -897,8 +633,8 @@ func GranularUpdateIssueState(t translations.TranslationHelperFunc) inventory.Se Annotations: &mcp.ToolAnnotations{ Title: t("TOOL_UPDATE_ISSUE_STATE_USER_TITLE", "Update Issue State"), ReadOnlyHint: false, - DestructiveHint: jsonschema.Ptr(false), - OpenWorldHint: jsonschema.Ptr(true), + DestructiveHint: new(false), + OpenWorldHint: new(true), }, InputSchema: &jsonschema.Schema{ Type: "object", @@ -914,7 +650,7 @@ func GranularUpdateIssueState(t translations.TranslationHelperFunc) inventory.Se "issue_number": { Type: "number", Description: "The issue number to update", - Minimum: jsonschema.Ptr(1.0), + Minimum: new(1.0), }, "state": { Type: "string", @@ -930,7 +666,7 @@ func GranularUpdateIssueState(t translations.TranslationHelperFunc) inventory.Se Type: "string", Description: "One concise sentence explaining what specifically about the issue led you to choose this state. " + "State the concrete signal (e.g. 'The reported crash is fixed in v2.1' → completed).", - MaxLength: jsonschema.Ptr(280), + MaxLength: new(280), }, "confidence": { Type: "string", @@ -945,67 +681,17 @@ func GranularUpdateIssueState(t translations.TranslationHelperFunc) inventory.Se "duplicate_of": { Type: "number", Description: "The issue number of the canonical issue this issue duplicates. Only valid when state_reason is 'duplicate'. Required when is_suggestion is true and state_reason is 'duplicate'. The issue number is resolved to a database ID before being sent to the API.", - Minimum: jsonschema.Ptr(1.0), + Minimum: new(1.0), }, }, Required: []string{"owner", "repo", "issue_number", "state"}, }, }, scopes.RequireAll(scopes.Repo), - func(ctx context.Context, deps ToolDependencies, _ *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 - } - repo, err := RequiredParam[string](args, "repo") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - issueNumber, err := RequiredInt(args, "issue_number") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - state, err := RequiredParam[string](args, "state") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - stateReason, err := OptionalParam[string](args, "state_reason") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - rationale, err := OptionalParam[string](args, "rationale") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - rationale = strings.TrimSpace(rationale) - if len([]rune(rationale)) > 280 { - return utils.NewToolResultError("parameter rationale must be 280 characters or less"), nil, nil - } - confidence, err := OptionalParam[string](args, "confidence") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - confidence = normalizeConfidence(confidence) - if confidence != "" && confidence != "LOW" && confidence != "MEDIUM" && confidence != "HIGH" { - return utils.NewToolResultError("confidence must be one of: LOW, MEDIUM, HIGH"), nil, nil - } - isSuggestion, err := OptionalParam[bool](args, "is_suggestion") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - duplicateOf, err := OptionalIntParam(args, "duplicate_of") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - if stateReason != "" && state != "closed" { - return utils.NewToolResultError("state_reason can only be used when state is 'closed'"), nil, nil - } - if duplicateOf != 0 && stateReason != "duplicate" { - return utils.NewToolResultError("duplicate_of can only be used when state_reason is 'duplicate'"), nil, nil - } - if isSuggestion && stateReason == "duplicate" && duplicateOf == 0 { - return utils.NewToolResultError("duplicate_of is required when suggesting a close as duplicate"), nil, nil - } + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, args GranularIssueStateInput) (*mcp.CallToolResult, *MinimalResponse, error) { + owner, repo, issueNumber := args.Owner, args.Repo, args.IssueNumber + state, stateReason := args.State, args.StateReason + rationale, confidence, isSuggestion, duplicateOf := args.Rationale, args.Confidence, args.IsSuggestion, args.DuplicateOf client, err := deps.GetClient(ctx) if err != nil { @@ -1054,15 +740,12 @@ func GranularUpdateIssueState(t translations.TranslationHelperFunc) inventory.Se } defer func() { _ = resp.Body.Close() }() - r, err := json.Marshal(MinimalResponse{ + return granularIssueMinimalResult(&MinimalResponse{ ID: fmt.Sprintf("%d", issue.GetID()), URL: issue.GetHTMLURL(), }) - if err != nil { - return utils.NewToolResultErrorFromErr("failed to marshal response", err), nil, nil - } - return utils.NewToolResultText(string(r)), nil, nil }, + granularIssueInputNormalizer(normalizeGranularUpdateIssueStateArguments), ) st.FeatureRule = issuesGranularFeatureRule return st @@ -1070,16 +753,17 @@ func GranularUpdateIssueState(t translations.TranslationHelperFunc) inventory.Se // GranularAddSubIssue creates a tool to add a sub-issue. func GranularAddSubIssue(t translations.TranslationHelperFunc) inventory.ServerTool { - st := NewTool( + st := NewTool[GranularAddSubIssueInput, *SubIssueWriteOutput]( ToolsetMetadataIssues, mcp.Tool{ - Name: "add_sub_issue", - Description: t("TOOL_ADD_SUB_ISSUE_DESCRIPTION", "Add a sub-issue to a parent issue."), + OutputSchema: subIssueWriteOutputSchema(), + Name: "add_sub_issue", + Description: t("TOOL_ADD_SUB_ISSUE_DESCRIPTION", "Add a sub-issue to a parent issue."), Annotations: &mcp.ToolAnnotations{ Title: t("TOOL_ADD_SUB_ISSUE_USER_TITLE", "Add Sub-Issue"), ReadOnlyHint: false, - DestructiveHint: jsonschema.Ptr(false), - OpenWorldHint: jsonschema.Ptr(true), + DestructiveHint: new(false), + OpenWorldHint: new(true), }, InputSchema: &jsonschema.Schema{ Type: "object", @@ -1095,7 +779,7 @@ func GranularAddSubIssue(t translations.TranslationHelperFunc) inventory.ServerT "issue_number": { Type: "number", Description: "The parent issue number", - Minimum: jsonschema.Ptr(1.0), + Minimum: new(1.0), }, "sub_issue_id": { Type: "number", @@ -1110,33 +794,18 @@ func GranularAddSubIssue(t translations.TranslationHelperFunc) inventory.ServerT }, }, scopes.RequireAll(scopes.Repo), - func(ctx context.Context, deps ToolDependencies, _ *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 - } - repo, err := RequiredParam[string](args, "repo") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - issueNumber, err := RequiredInt(args, "issue_number") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - subIssueID, err := RequiredInt(args, "sub_issue_id") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - replaceParent, _ := OptionalParam[bool](args, "replace_parent") + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, args GranularAddSubIssueInput) (*mcp.CallToolResult, *SubIssueWriteOutput, error) { + owner, repo, issueNumber, subIssueID, replaceParent := args.Owner, args.Repo, args.IssueNumber, args.SubIssueID, args.ReplaceParent client, err := deps.GetClient(ctx) if err != nil { return utils.NewToolResultErrorFromErr("failed to get GitHub client", err), nil, nil } - result, err := AddSubIssue(ctx, client, owner, repo, issueNumber, subIssueID, replaceParent) - return result, nil, err + result, output, err := addSubIssue(ctx, client, owner, repo, issueNumber, subIssueID, replaceParent) + return subIssueWriteResult("add")(result, output, err) }, + granularIssueInputNormalizer(normalizeGranularAddSubIssueArguments), ) st.FeatureRule = issuesGranularFeatureRule return st @@ -1144,16 +813,17 @@ func GranularAddSubIssue(t translations.TranslationHelperFunc) inventory.ServerT // GranularRemoveSubIssue creates a tool to remove a sub-issue. func GranularRemoveSubIssue(t translations.TranslationHelperFunc) inventory.ServerTool { - st := NewTool( + st := NewTool[GranularRemoveSubIssueInput, *SubIssueWriteOutput]( ToolsetMetadataIssues, mcp.Tool{ - Name: "remove_sub_issue", - Description: t("TOOL_REMOVE_SUB_ISSUE_DESCRIPTION", "Remove a sub-issue from a parent issue."), + OutputSchema: subIssueWriteOutputSchema(), + Name: "remove_sub_issue", + Description: t("TOOL_REMOVE_SUB_ISSUE_DESCRIPTION", "Remove a sub-issue from a parent issue."), Annotations: &mcp.ToolAnnotations{ Title: t("TOOL_REMOVE_SUB_ISSUE_USER_TITLE", "Remove Sub-Issue"), ReadOnlyHint: false, - DestructiveHint: jsonschema.Ptr(true), - OpenWorldHint: jsonschema.Ptr(true), + DestructiveHint: new(true), + OpenWorldHint: new(true), }, InputSchema: &jsonschema.Schema{ Type: "object", @@ -1169,7 +839,7 @@ func GranularRemoveSubIssue(t translations.TranslationHelperFunc) inventory.Serv "issue_number": { Type: "number", Description: "The parent issue number", - Minimum: jsonschema.Ptr(1.0), + Minimum: new(1.0), }, "sub_issue_id": { Type: "number", @@ -1180,32 +850,18 @@ func GranularRemoveSubIssue(t translations.TranslationHelperFunc) inventory.Serv }, }, scopes.RequireAll(scopes.Repo), - func(ctx context.Context, deps ToolDependencies, _ *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 - } - repo, err := RequiredParam[string](args, "repo") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - issueNumber, err := RequiredInt(args, "issue_number") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - subIssueID, err := RequiredInt(args, "sub_issue_id") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, args GranularRemoveSubIssueInput) (*mcp.CallToolResult, *SubIssueWriteOutput, error) { + owner, repo, issueNumber, subIssueID := args.Owner, args.Repo, args.IssueNumber, args.SubIssueID client, err := deps.GetClient(ctx) if err != nil { return utils.NewToolResultErrorFromErr("failed to get GitHub client", err), nil, nil } - result, err := RemoveSubIssue(ctx, client, owner, repo, issueNumber, subIssueID) - return result, nil, err + result, output, err := removeSubIssue(ctx, client, owner, repo, issueNumber, subIssueID) + return subIssueWriteResult("remove")(result, output, err) }, + granularIssueInputNormalizer(normalizeGranularRemoveSubIssueArguments), ) st.FeatureRule = issuesGranularFeatureRule return st @@ -1213,16 +869,17 @@ func GranularRemoveSubIssue(t translations.TranslationHelperFunc) inventory.Serv // GranularReprioritizeSubIssue creates a tool to reorder a sub-issue. func GranularReprioritizeSubIssue(t translations.TranslationHelperFunc) inventory.ServerTool { - st := NewTool( + st := NewTool[GranularReprioritizeSubIssueInput, *SubIssueWriteOutput]( ToolsetMetadataIssues, mcp.Tool{ - Name: "reprioritize_sub_issue", - Description: t("TOOL_REPRIORITIZE_SUB_ISSUE_DESCRIPTION", "Reprioritize (reorder) a sub-issue relative to other sub-issues."), + OutputSchema: subIssueWriteOutputSchema(), + Name: "reprioritize_sub_issue", + Description: t("TOOL_REPRIORITIZE_SUB_ISSUE_DESCRIPTION", "Reprioritize (reorder) a sub-issue relative to other sub-issues."), Annotations: &mcp.ToolAnnotations{ Title: t("TOOL_REPRIORITIZE_SUB_ISSUE_USER_TITLE", "Reprioritize Sub-Issue"), ReadOnlyHint: false, - DestructiveHint: jsonschema.Ptr(false), - OpenWorldHint: jsonschema.Ptr(true), + DestructiveHint: new(false), + OpenWorldHint: new(true), }, InputSchema: &jsonschema.Schema{ Type: "object", @@ -1238,7 +895,7 @@ func GranularReprioritizeSubIssue(t translations.TranslationHelperFunc) inventor "issue_number": { Type: "number", Description: "The parent issue number", - Minimum: jsonschema.Ptr(1.0), + Minimum: new(1.0), }, "sub_issue_id": { Type: "number", @@ -1257,40 +914,18 @@ func GranularReprioritizeSubIssue(t translations.TranslationHelperFunc) inventor }, }, scopes.RequireAll(scopes.Repo), - func(ctx context.Context, deps ToolDependencies, _ *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 - } - repo, err := RequiredParam[string](args, "repo") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - issueNumber, err := RequiredInt(args, "issue_number") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - subIssueID, err := RequiredInt(args, "sub_issue_id") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - afterID, err := OptionalIntParam(args, "after_id") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - beforeID, err := OptionalIntParam(args, "before_id") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, args GranularReprioritizeSubIssueInput) (*mcp.CallToolResult, *SubIssueWriteOutput, error) { + owner, repo, issueNumber, subIssueID, afterID, beforeID := args.Owner, args.Repo, args.IssueNumber, args.SubIssueID, args.AfterID, args.BeforeID client, err := deps.GetClient(ctx) if err != nil { return utils.NewToolResultErrorFromErr("failed to get GitHub client", err), nil, nil } - result, err := ReprioritizeSubIssue(ctx, client, owner, repo, issueNumber, subIssueID, afterID, beforeID) - return result, nil, err + result, output, err := reprioritizeSubIssue(ctx, client, owner, repo, issueNumber, subIssueID, afterID, beforeID) + return subIssueWriteResult("reprioritize")(result, output, err) }, + granularIssueInputNormalizer(normalizeGranularReprioritizeSubIssueArguments), ) st.FeatureRule = issuesGranularFeatureRule return st @@ -1339,7 +974,7 @@ func SetIssueFieldValues(ctx context.Context, gqlClient *githubv4.Client, input // GranularSetIssueFields creates a tool to set issue field values on an issue using GraphQL. func GranularSetIssueFields(t translations.TranslationHelperFunc) inventory.ServerTool { - st := NewTool( + st := NewTool[GranularSetIssueFieldsInput, *MinimalResponse]( ToolsetMetadataIssues, mcp.Tool{ Name: "set_issue_fields", @@ -1347,8 +982,8 @@ func GranularSetIssueFields(t translations.TranslationHelperFunc) inventory.Serv Annotations: &mcp.ToolAnnotations{ Title: t("TOOL_SET_ISSUE_FIELDS_USER_TITLE", "Set Issue Fields"), ReadOnlyHint: false, - DestructiveHint: jsonschema.Ptr(false), - OpenWorldHint: jsonschema.Ptr(true), + DestructiveHint: new(false), + OpenWorldHint: new(true), }, InputSchema: &jsonschema.Schema{ Type: "object", @@ -1364,12 +999,12 @@ func GranularSetIssueFields(t translations.TranslationHelperFunc) inventory.Serv "issue_number": { Type: "number", Description: "The issue number to update", - Minimum: jsonschema.Ptr(1.0), + Minimum: new(1.0), }, "fields": { Type: "array", Description: "Array of issue field values to set. Each element must have a 'field_id' (string, the GraphQL node ID of the field) and exactly one value field: 'text_value' for text fields, 'number_value' for number fields, 'date_value' (ISO 8601 date string) for date fields, or 'single_select_option_id' (the GraphQL node ID of the option) for single select fields. Set 'delete' to true to remove a field value.", - MinItems: jsonschema.Ptr(1), + MinItems: new(1), Items: &jsonschema.Schema{ Type: "object", Properties: map[string]*jsonschema.Schema{ @@ -1401,7 +1036,7 @@ func GranularSetIssueFields(t translations.TranslationHelperFunc) inventory.Serv Type: "string", Description: "One concise sentence explaining what specifically about the issue led you to choose this field value. " + "State the concrete signal (e.g. 'Reports a crash when saving' → high priority).", - MaxLength: jsonschema.Ptr(280), + MaxLength: new(280), }, "confidence": { Type: "string", @@ -1422,132 +1057,9 @@ func GranularSetIssueFields(t translations.TranslationHelperFunc) inventory.Serv }, }, scopes.RequireAll(scopes.Repo), - func(ctx context.Context, deps ToolDependencies, _ *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 - } - repo, err := RequiredParam[string](args, "repo") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - issueNumber, err := RequiredInt(args, "issue_number") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - - fieldsRaw, ok := args["fields"] - if !ok { - return utils.NewToolResultError("missing required parameter: fields"), nil, nil - } - - // Accept both []any and []map[string]any input forms - var fieldMaps []map[string]any - switch v := fieldsRaw.(type) { - case []any: - for _, f := range v { - fieldMap, ok := f.(map[string]any) - if !ok { - return utils.NewToolResultError("each field must be an object with 'field_id' and a value"), nil, nil - } - fieldMaps = append(fieldMaps, fieldMap) - } - case []map[string]any: - fieldMaps = v - default: - return utils.NewToolResultError("invalid parameter: fields must be an array"), nil, nil - } - if len(fieldMaps) == 0 { - return utils.NewToolResultError("fields array must not be empty"), nil, nil - } - - issueFields := make([]IssueFieldCreateOrUpdateInput, 0, len(fieldMaps)) - for _, fieldMap := range fieldMaps { - fieldID, err := RequiredParam[string](fieldMap, "field_id") - if err != nil { - return utils.NewToolResultError("field_id is required and must be a string"), nil, nil - } - - input := IssueFieldCreateOrUpdateInput{ - FieldID: githubv4.ID(fieldID), - } - - // Count how many value keys are present; exactly one is required. - valueCount := 0 - - if v, err := OptionalParam[string](fieldMap, "text_value"); err == nil && v != "" { - input.TextValue = githubv4.NewString(githubv4.String(v)) - valueCount++ - } - if v, err := OptionalParam[float64](fieldMap, "number_value"); err == nil { - if _, exists := fieldMap["number_value"]; exists { - gqlFloat := githubv4.Float(v) - input.NumberValue = &gqlFloat - valueCount++ - } - } - if v, err := OptionalParam[string](fieldMap, "date_value"); err == nil && v != "" { - input.DateValue = githubv4.NewString(githubv4.String(v)) - valueCount++ - } - if v, err := OptionalParam[string](fieldMap, "single_select_option_id"); err == nil && v != "" { - optionID := githubv4.ID(v) - input.SingleSelectOptionID = &optionID - valueCount++ - } - if _, exists := fieldMap["delete"]; exists { - del, err := OptionalParam[bool](fieldMap, "delete") - if err == nil && del { - deleteVal := githubv4.Boolean(true) - input.Delete = &deleteVal - valueCount++ - } - } - - if valueCount == 0 { - return utils.NewToolResultError("each field must have a value (text_value, number_value, date_value, single_select_option_id) or delete: true"), nil, nil - } - if valueCount > 1 { - return utils.NewToolResultError("each field must have exactly one value (text_value, number_value, date_value, single_select_option_id) or delete: true, but multiple were provided"), nil, nil - } - - if _, exists := fieldMap["rationale"]; exists { - rationale, err := OptionalParam[string](fieldMap, "rationale") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - rationale = strings.TrimSpace(rationale) - if len([]rune(rationale)) > 280 { - return utils.NewToolResultError("field rationale must be 280 characters or less"), nil, nil - } - if rationale != "" { - input.Rationale = githubv4.NewString(githubv4.String(rationale)) - } - } - - confidence, err := OptionalParam[string](fieldMap, "confidence") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - confidence = normalizeConfidence(confidence) - if confidence != "" && confidence != "LOW" && confidence != "MEDIUM" && confidence != "HIGH" { - return utils.NewToolResultError("confidence must be one of: LOW, MEDIUM, HIGH"), nil, nil - } - if confidence != "" { - input.Confidence = &confidence - } - - isSuggestion, err := OptionalParam[bool](fieldMap, "is_suggestion") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - if isSuggestion { - suggestVal := githubv4.Boolean(true) - input.Suggest = &suggestVal - } - - issueFields = append(issueFields, input) - } + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, args GranularSetIssueFieldsInput) (*mcp.CallToolResult, *MinimalResponse, error) { + owner, repo, issueNumber := args.Owner, args.Repo, args.IssueNumber + issueFields := granularIssueFieldMutation(args.Fields) gqlClient, err := deps.GetGQLClient(ctx) if err != nil { @@ -1573,12 +1085,9 @@ func GranularSetIssueFields(t translations.TranslationHelperFunc) inventory.Serv return ghErrors.NewGitHubGraphQLErrorResponse(ctx, "failed to set issue field values", err), nil, nil } - r, err := json.Marshal(response) - if err != nil { - return utils.NewToolResultErrorFromErr("failed to marshal response", err), nil, nil - } - return utils.NewToolResultText(string(r)), nil, nil + return granularIssueMinimalResult(&response) }, + granularIssueInputNormalizer(normalizeGranularSetIssueFieldsArguments), ) st.FeatureRule = issuesGranularFeatureRule return st @@ -1586,7 +1095,7 @@ func GranularSetIssueFields(t translations.TranslationHelperFunc) inventory.Serv // GranularAddIssueReaction adds a reaction to an issue or pull request. func GranularAddIssueReaction(t translations.TranslationHelperFunc) inventory.ServerTool { - st := NewTool( + st := NewTool[GranularAddIssueReactionInput, *MinimalResponse]( ToolsetMetadataIssues, mcp.Tool{ Name: "add_issue_reaction", @@ -1594,8 +1103,8 @@ func GranularAddIssueReaction(t translations.TranslationHelperFunc) inventory.Se Annotations: &mcp.ToolAnnotations{ Title: t("TOOL_ADD_ISSUE_REACTION_USER_TITLE", "Add Reaction to Issue or Pull Request"), ReadOnlyHint: false, - DestructiveHint: jsonschema.Ptr(false), - OpenWorldHint: jsonschema.Ptr(true), + DestructiveHint: new(false), + OpenWorldHint: new(true), }, InputSchema: &jsonschema.Schema{ Type: "object", @@ -1611,7 +1120,7 @@ func GranularAddIssueReaction(t translations.TranslationHelperFunc) inventory.Se "issue_number": { Type: "number", Description: "The issue number", - Minimum: jsonschema.Ptr(1.0), + Minimum: new(1.0), }, "content": { Type: "string", @@ -1623,23 +1132,8 @@ func GranularAddIssueReaction(t translations.TranslationHelperFunc) inventory.Se }, }, scopes.RequireAll(scopes.Repo), - func(ctx context.Context, deps ToolDependencies, _ *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 - } - repo, err := RequiredParam[string](args, "repo") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - issueNumber, err := RequiredInt(args, "issue_number") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - content, err := RequiredParam[string](args, "content") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, args GranularAddIssueReactionInput) (*mcp.CallToolResult, *MinimalResponse, error) { + owner, repo, issueNumber, content := args.Owner, args.Repo, args.IssueNumber, args.Content client, err := deps.GetClient(ctx) if err != nil { @@ -1652,15 +1146,12 @@ func GranularAddIssueReaction(t translations.TranslationHelperFunc) inventory.Se } defer func() { _ = resp.Body.Close() }() - r, err := json.Marshal(MinimalResponse{ + return granularIssueMinimalResult(&MinimalResponse{ ID: fmt.Sprintf("%d", reaction.GetID()), URL: fmt.Sprintf("%srepos/%s/%s/issues/%d/reactions/%d", client.BaseURL(), owner, repo, issueNumber, reaction.GetID()), }) - if err != nil { - return utils.NewToolResultErrorFromErr("failed to marshal response", err), nil, nil - } - return utils.NewToolResultText(string(r)), nil, nil }, + granularIssueInputNormalizer(normalizeGranularAddIssueReactionArguments), ) st.FeatureRule = issuesGranularFeatureRule return st @@ -1668,7 +1159,7 @@ func GranularAddIssueReaction(t translations.TranslationHelperFunc) inventory.Se // GranularRemoveIssueReaction removes a reaction from an issue or pull request. func GranularRemoveIssueReaction(t translations.TranslationHelperFunc) inventory.ServerTool { - st := NewTool( + st := NewTool[GranularRemoveIssueReactionInput, *GranularIssueReactionMessage]( ToolsetMetadataIssues, mcp.Tool{ Name: "remove_issue_reaction", @@ -1676,8 +1167,8 @@ func GranularRemoveIssueReaction(t translations.TranslationHelperFunc) inventory Annotations: &mcp.ToolAnnotations{ Title: t("TOOL_REMOVE_ISSUE_REACTION_USER_TITLE", "Remove Reaction from Issue or Pull Request"), ReadOnlyHint: false, - DestructiveHint: jsonschema.Ptr(true), - OpenWorldHint: jsonschema.Ptr(true), + DestructiveHint: new(true), + OpenWorldHint: new(true), }, InputSchema: &jsonschema.Schema{ Type: "object", @@ -1693,35 +1184,20 @@ func GranularRemoveIssueReaction(t translations.TranslationHelperFunc) inventory "issue_number": { Type: "number", Description: "The issue number", - Minimum: jsonschema.Ptr(1.0), + Minimum: new(1.0), }, "reaction_id": { Type: "number", Description: "The reaction ID to remove", - Minimum: jsonschema.Ptr(1.0), + Minimum: new(1.0), }, }, Required: []string{"owner", "repo", "issue_number", "reaction_id"}, }, }, scopes.RequireAll(scopes.Repo), - func(ctx context.Context, deps ToolDependencies, _ *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 - } - repo, err := RequiredParam[string](args, "repo") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - issueNumber, err := RequiredInt(args, "issue_number") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - reactionID, err := RequiredBigInt(args, "reaction_id") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, args GranularRemoveIssueReactionInput) (*mcp.CallToolResult, *GranularIssueReactionMessage, error) { + owner, repo, issueNumber, reactionID := args.Owner, args.Repo, args.IssueNumber, args.ReactionID client, err := deps.GetClient(ctx) if err != nil { @@ -1736,8 +1212,9 @@ func GranularRemoveIssueReaction(t translations.TranslationHelperFunc) inventory return ghErrors.NewGitHubAPIErrorResponse(ctx, "failed to remove reaction from issue", resp, err), nil, nil } - return utils.NewToolResultText("reaction successfully removed from issue"), nil, nil + return utils.NewToolResultText("reaction successfully removed from issue"), &GranularIssueReactionMessage{Message: "reaction successfully removed from issue"}, nil }, + granularIssueInputNormalizer(normalizeGranularRemoveIssueReactionArguments), ) st.FeatureRule = issuesGranularFeatureRule return st @@ -1745,7 +1222,7 @@ func GranularRemoveIssueReaction(t translations.TranslationHelperFunc) inventory // GranularAddIssueCommentReaction adds a reaction to an issue or pull request comment. func GranularAddIssueCommentReaction(t translations.TranslationHelperFunc) inventory.ServerTool { - st := NewTool( + st := NewTool[GranularAddIssueCommentReactionInput, *MinimalResponse]( ToolsetMetadataIssues, mcp.Tool{ Name: "add_issue_comment_reaction", @@ -1753,8 +1230,8 @@ func GranularAddIssueCommentReaction(t translations.TranslationHelperFunc) inven Annotations: &mcp.ToolAnnotations{ Title: t("TOOL_ADD_ISSUE_COMMENT_REACTION_USER_TITLE", "Add Reaction to Issue or Pull Request Comment"), ReadOnlyHint: false, - DestructiveHint: jsonschema.Ptr(false), - OpenWorldHint: jsonschema.Ptr(true), + DestructiveHint: new(false), + OpenWorldHint: new(true), }, InputSchema: &jsonschema.Schema{ Type: "object", @@ -1770,7 +1247,7 @@ func GranularAddIssueCommentReaction(t translations.TranslationHelperFunc) inven "comment_id": { Type: "number", Description: "The issue or pull request comment ID", - Minimum: jsonschema.Ptr(1.0), + Minimum: new(1.0), }, "content": { Type: "string", @@ -1782,23 +1259,8 @@ func GranularAddIssueCommentReaction(t translations.TranslationHelperFunc) inven }, }, scopes.RequireAll(scopes.Repo), - func(ctx context.Context, deps ToolDependencies, _ *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 - } - repo, err := RequiredParam[string](args, "repo") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - commentID, err := RequiredBigInt(args, "comment_id") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - content, err := RequiredParam[string](args, "content") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, args GranularAddIssueCommentReactionInput) (*mcp.CallToolResult, *MinimalResponse, error) { + owner, repo, commentID, content := args.Owner, args.Repo, args.CommentID, args.Content client, err := deps.GetClient(ctx) if err != nil { @@ -1811,15 +1273,12 @@ func GranularAddIssueCommentReaction(t translations.TranslationHelperFunc) inven } defer func() { _ = resp.Body.Close() }() - r, err := json.Marshal(MinimalResponse{ + return granularIssueMinimalResult(&MinimalResponse{ ID: fmt.Sprintf("%d", reaction.GetID()), URL: fmt.Sprintf("%srepos/%s/%s/issues/comments/%d/reactions/%d", client.BaseURL(), owner, repo, commentID, reaction.GetID()), }) - if err != nil { - return utils.NewToolResultErrorFromErr("failed to marshal response", err), nil, nil - } - return utils.NewToolResultText(string(r)), nil, nil }, + granularIssueInputNormalizer(normalizeGranularAddIssueCommentReactionArguments), ) st.FeatureRule = issuesGranularFeatureRule return st @@ -1827,7 +1286,7 @@ func GranularAddIssueCommentReaction(t translations.TranslationHelperFunc) inven // GranularRemoveIssueCommentReaction removes a reaction from an issue or pull request comment. func GranularRemoveIssueCommentReaction(t translations.TranslationHelperFunc) inventory.ServerTool { - st := NewTool( + st := NewTool[GranularRemoveIssueCommentReactionInput, *GranularIssueReactionMessage]( ToolsetMetadataIssues, mcp.Tool{ Name: "remove_issue_comment_reaction", @@ -1835,8 +1294,8 @@ func GranularRemoveIssueCommentReaction(t translations.TranslationHelperFunc) in Annotations: &mcp.ToolAnnotations{ Title: t("TOOL_REMOVE_ISSUE_COMMENT_REACTION_USER_TITLE", "Remove Reaction from Issue or Pull Request Comment"), ReadOnlyHint: false, - DestructiveHint: jsonschema.Ptr(true), - OpenWorldHint: jsonschema.Ptr(true), + DestructiveHint: new(true), + OpenWorldHint: new(true), }, InputSchema: &jsonschema.Schema{ Type: "object", @@ -1852,35 +1311,20 @@ func GranularRemoveIssueCommentReaction(t translations.TranslationHelperFunc) in "comment_id": { Type: "number", Description: "The issue or pull request comment ID", - Minimum: jsonschema.Ptr(1.0), + Minimum: new(1.0), }, "reaction_id": { Type: "number", Description: "The reaction ID to remove", - Minimum: jsonschema.Ptr(1.0), + Minimum: new(1.0), }, }, Required: []string{"owner", "repo", "comment_id", "reaction_id"}, }, }, scopes.RequireAll(scopes.Repo), - func(ctx context.Context, deps ToolDependencies, _ *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 - } - repo, err := RequiredParam[string](args, "repo") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - commentID, err := RequiredBigInt(args, "comment_id") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - reactionID, err := RequiredBigInt(args, "reaction_id") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, args GranularRemoveIssueCommentReactionInput) (*mcp.CallToolResult, *GranularIssueReactionMessage, error) { + owner, repo, commentID, reactionID := args.Owner, args.Repo, args.CommentID, args.ReactionID client, err := deps.GetClient(ctx) if err != nil { @@ -1895,9 +1339,20 @@ func GranularRemoveIssueCommentReaction(t translations.TranslationHelperFunc) in return ghErrors.NewGitHubAPIErrorResponse(ctx, "failed to remove reaction from issue comment", resp, err), nil, nil } - return utils.NewToolResultText("reaction successfully removed from issue comment"), nil, nil + return utils.NewToolResultText("reaction successfully removed from issue comment"), &GranularIssueReactionMessage{Message: "reaction successfully removed from issue comment"}, nil }, + granularIssueInputNormalizer(normalizeGranularRemoveIssueCommentReactionArguments), ) st.FeatureRule = issuesGranularFeatureRule return st } + +// GranularHideIssueComment hides (minimizes) an issue or pull request conversation comment. +func GranularHideIssueComment(t translations.TranslationHelperFunc) inventory.ServerTool { + return commentVisibilityTool(t, issueCommentVisibilityTarget, true) +} + +// GranularUnhideIssueComment unhides (unminimizes) an issue or pull request conversation comment. +func GranularUnhideIssueComment(t translations.TranslationHelperFunc) inventory.ServerTool { + return commentVisibilityTool(t, issueCommentVisibilityTarget, false) +} diff --git a/pkg/github/issues_test.go b/pkg/github/issues_test.go index 7138148c21..79eeb22100 100644 --- a/pkg/github/issues_test.go +++ b/pkg/github/issues_test.go @@ -13,14 +13,14 @@ import ( "testing" "time" - "github.com/github/github-mcp-server/internal/githubv4mock" - "github.com/github/github-mcp-server/internal/toolsnaps" - ghErrors "github.com/github/github-mcp-server/pkg/errors" - "github.com/github/github-mcp-server/pkg/http/headers" - transportpkg "github.com/github/github-mcp-server/pkg/http/transport" - "github.com/github/github-mcp-server/pkg/inventory" - "github.com/github/github-mcp-server/pkg/translations" - "github.com/google/go-github/v89/github" + "github.com/github/github-mcp-server/v2/internal/githubv4mock" + "github.com/github/github-mcp-server/v2/internal/toolsnaps" + ghErrors "github.com/github/github-mcp-server/v2/pkg/errors" + "github.com/github/github-mcp-server/v2/pkg/http/headers" + transportpkg "github.com/github/github-mcp-server/v2/pkg/http/transport" + "github.com/github/github-mcp-server/v2/pkg/inventory" + "github.com/github/github-mcp-server/v2/pkg/translations" + "github.com/google/go-github/v92/github" "github.com/google/jsonschema-go/jsonschema" "github.com/modelcontextprotocol/go-sdk/mcp" "github.com/shurcooL/githubv4" @@ -140,38 +140,38 @@ func Test_GetIssue(t *testing.T) { // Setup mock issue for success case mockIssue := &github.Issue{ - Number: github.Ptr(42), - Title: github.Ptr("Test Issue"), - Body: github.Ptr("This is a test issue"), - State: github.Ptr("open"), - HTMLURL: github.Ptr("https://github.com/owner/repo/issues/42"), + Number: new(42), + Title: new("Test Issue"), + Body: new("This is a test issue"), + State: new("open"), + HTMLURL: new("https://github.com/owner/repo/issues/42"), User: &github.User{ - Login: github.Ptr("testuser"), + Login: new("testuser"), }, Assignees: []*github.User{ - {Login: github.Ptr("octocat")}, - {Login: github.Ptr("mona")}, + {Login: new("octocat")}, + {Login: new("mona")}, }, Repository: &github.Repository{ - Name: github.Ptr("repo"), + Name: new("repo"), Owner: &github.User{ - Login: github.Ptr("owner"), + Login: new("owner"), }, }, } mockIssue2 := &github.Issue{ - Number: github.Ptr(422), - Title: github.Ptr("Test Issue 2"), - Body: github.Ptr("This is a test issue 2"), - State: github.Ptr("open"), - HTMLURL: github.Ptr("https://github.com/owner/repo/issues/42"), + Number: new(422), + Title: new("Test Issue 2"), + Body: new("This is a test issue 2"), + State: new("open"), + HTMLURL: new("https://github.com/owner/repo/issues/42"), User: &github.User{ - Login: github.Ptr("testuser2"), + Login: new("testuser2"), }, Repository: &github.Repository{ - Name: github.Ptr("repo2"), + Name: new("repo2"), Owner: &github.User{ - Login: github.Ptr("owner2"), + Login: new("owner2"), }, }, } @@ -318,16 +318,16 @@ func Test_IssueRead_IFC_InsidersMode(t *testing.T) { serverTool := IssueRead(translations.NullTranslationHelper) mockIssue := &github.Issue{ - Number: github.Ptr(1), - Title: github.Ptr("Test"), - Body: github.Ptr("body"), - State: github.Ptr("open"), - HTMLURL: github.Ptr("https://github.com/octocat/repo/issues/1"), - User: &github.User{Login: github.Ptr("u")}, + Number: new(1), + Title: new("Test"), + Body: new("body"), + State: new("open"), + HTMLURL: new("https://github.com/octocat/repo/issues/1"), + User: &github.User{Login: new("u")}, } mockComments := []*github.IssueComment{ - {Body: github.Ptr("hello"), User: &github.User{Login: github.Ptr("u")}}, + {Body: new("hello"), User: &github.User{Login: new("u")}}, } makeMockClient := func(isPrivate bool, repoStatus int) *http.Client { @@ -435,13 +435,13 @@ func Test_GetIssue_FieldValues(t *testing.T) { serverTool := IssueRead(translations.NullTranslationHelper) mockIssueWithFields := &github.Issue{ - Number: github.Ptr(99), - Title: github.Ptr("Issue with field values"), - Body: github.Ptr("body"), - State: github.Ptr("open"), - HTMLURL: github.Ptr("https://github.com/owner/repo/issues/99"), + Number: new(99), + Title: new("Issue with field values"), + Body: new("body"), + State: new("open"), + HTMLURL: new("https://github.com/owner/repo/issues/99"), User: &github.User{ - Login: github.Ptr("testuser"), + Login: new("testuser"), }, IssueFieldValues: []*github.IssueFieldValue{ { @@ -506,14 +506,14 @@ func Test_GetIssue_FieldValues_Enriched(t *testing.T) { serverTool := IssueRead(translations.NullTranslationHelper) mockIssueWithFields := &github.Issue{ - Number: github.Ptr(99), - NodeID: github.Ptr("I_node_99"), - Title: github.Ptr("Issue with field values"), - Body: github.Ptr("body"), - State: github.Ptr("open"), - HTMLURL: github.Ptr("https://github.com/owner/repo/issues/99"), + Number: new(99), + NodeID: new("I_node_99"), + Title: new("Issue with field values"), + Body: new("body"), + State: new("open"), + HTMLURL: new("https://github.com/owner/repo/issues/99"), User: &github.User{ - Login: github.Ptr("testuser"), + Login: new("testuser"), }, IssueFieldValues: []*github.IssueFieldValue{ { @@ -593,20 +593,20 @@ func Test_GetIssue_FieldValues_Enriched(t *testing.T) { // With no parent and no sub-issues, the routing booleans are explicit false and the // optional relationship payloads are omitted. - assert.Equal(t, github.Ptr(false), returnedIssue.HasParent, "has_parent should be false without a parent") - assert.Equal(t, github.Ptr(false), returnedIssue.HasChildren, "has_children should be false without sub-issues") + assert.Equal(t, new(false), returnedIssue.HasParent, "has_parent should be false without a parent") + assert.Equal(t, new(false), returnedIssue.HasChildren, "has_children should be false without sub-issues") assert.Nil(t, returnedIssue.Parent, "parent should be omitted when there is no parent") assert.Nil(t, returnedIssue.SubIssuesSummary, "sub_issues_summary should be omitted with no sub-issues") } func Test_GetIssue_HierarchyEnrichment(t *testing.T) { mockIssue := &github.Issue{ - Number: github.Ptr(2990), - NodeID: github.Ptr("I_node_2990"), - Title: github.Ptr("Child issue"), - State: github.Ptr("open"), - HTMLURL: github.Ptr("https://github.com/owner/repo/issues/2990"), - User: &github.User{Login: github.Ptr("author")}, + Number: new(2990), + NodeID: new("I_node_2990"), + Title: new("Child issue"), + State: new("open"), + HTMLURL: new("https://github.com/owner/repo/issues/2990"), + User: &github.User{Login: new("author")}, } parentNode := map[string]any{ @@ -632,8 +632,8 @@ func Test_GetIssue_HierarchyEnrichment(t *testing.T) { parent: parentNode, summary: map[string]any{"total": 4, "completed": 1, "percentCompleted": 25}, assertResponse: func(t *testing.T, issue MinimalIssue) { - assert.Equal(t, github.Ptr(true), issue.HasParent) - assert.Equal(t, github.Ptr(true), issue.HasChildren) + assert.Equal(t, new(true), issue.HasParent) + assert.Equal(t, new(true), issue.HasChildren) require.NotNil(t, issue.Parent) assert.Equal(t, 2820, issue.Parent.Number) assert.Equal(t, "Parent issue", issue.Parent.Title) @@ -650,7 +650,7 @@ func Test_GetIssue_HierarchyEnrichment(t *testing.T) { parent: nil, summary: map[string]any{"total": 0, "completed": 0, "percentCompleted": 0}, assertResponse: func(t *testing.T, issue MinimalIssue) { - assert.Equal(t, github.Ptr(false), issue.HasParent) + assert.Equal(t, new(false), issue.HasParent) assert.Nil(t, issue.Parent) }, }, @@ -659,7 +659,7 @@ func Test_GetIssue_HierarchyEnrichment(t *testing.T) { parent: nil, summary: map[string]any{"total": 0, "completed": 1, "percentCompleted": 0}, assertResponse: func(t *testing.T, issue MinimalIssue) { - assert.Equal(t, github.Ptr(false), issue.HasChildren) + assert.Equal(t, new(false), issue.HasChildren) assert.Nil(t, issue.SubIssuesSummary) }, }, @@ -713,12 +713,12 @@ func Test_GetIssue_HierarchyEnrichment(t *testing.T) { func Test_GetIssue_HierarchyEnrichment_Lockdown(t *testing.T) { mockIssue := &github.Issue{ - Number: github.Ptr(2990), - NodeID: github.Ptr("I_node_2990"), - Title: github.Ptr("Child issue"), - State: github.Ptr("open"), - HTMLURL: github.Ptr("https://github.com/owner/repo/issues/2990"), - User: &github.User{Login: github.Ptr("author")}, + Number: new(2990), + NodeID: new("I_node_2990"), + Title: new("Child issue"), + State: new("open"), + HTMLURL: new("https://github.com/owner/repo/issues/2990"), + User: &github.User{Login: new("author")}, } parentNode := map[string]any{ @@ -780,17 +780,17 @@ func Test_GetIssue_HierarchyEnrichment_Lockdown(t *testing.T) { require.NoError(t, json.Unmarshal([]byte(getTextResult(t, result).Text), &returnedIssue)) require.Nil(t, returnedIssue.Parent, "parent reference should be omitted under lockdown when it cannot be verified safe") - assert.Equal(t, github.Ptr(true), returnedIssue.HasParent, "has_parent should still be true so agents can route to get_parent") + assert.Equal(t, new(true), returnedIssue.HasParent, "has_parent should still be true so agents can route to get_parent") } func Test_GetIssue_HierarchyEnrichment_QueryFailureReturnsBaseIssue(t *testing.T) { mockIssue := &github.Issue{ - Number: github.Ptr(2990), - NodeID: github.Ptr("I_node_2990"), - Title: github.Ptr("Child issue"), - State: github.Ptr("open"), - HTMLURL: github.Ptr("https://github.com/owner/repo/issues/2990"), - User: &github.User{Login: github.Ptr("author")}, + Number: new(2990), + NodeID: new("I_node_2990"), + Title: new("Child issue"), + State: new("open"), + HTMLURL: new("https://github.com/owner/repo/issues/2990"), + User: &github.User{Login: new("author")}, } restClient := MockHTTPClientWithHandlers(map[string]http.HandlerFunc{ @@ -833,12 +833,12 @@ func Test_GetIssue_HierarchyEnrichment_QueryFailureReturnsBaseIssue(t *testing.T func Test_GetIssue_ClosedByPullRequests(t *testing.T) { mockIssue := &github.Issue{ - Number: github.Ptr(2990), - NodeID: github.Ptr("I_node_2990"), - Title: github.Ptr("Broken thing"), - State: github.Ptr("open"), - HTMLURL: github.Ptr("https://github.com/owner/repo/issues/2990"), - User: &github.User{Login: github.Ptr("author")}, + Number: new(2990), + NodeID: new("I_node_2990"), + Title: new("Broken thing"), + State: new("open"), + HTMLURL: new("https://github.com/owner/repo/issues/2990"), + User: &github.User{Login: new("author")}, } tests := []struct { @@ -994,12 +994,12 @@ func closingPullRequestFixtures(n int) []map[string]any { func Test_GetIssue_ClosedByPullRequests_Lockdown(t *testing.T) { mockIssue := &github.Issue{ - Number: github.Ptr(2990), - NodeID: github.Ptr("I_node_2990"), - Title: github.Ptr("Broken thing"), - State: github.Ptr("open"), - HTMLURL: github.Ptr("https://github.com/owner/repo/issues/2990"), - User: &github.User{Login: github.Ptr("author")}, + Number: new(2990), + NodeID: new("I_node_2990"), + Title: new("Broken thing"), + State: new("open"), + HTMLURL: new("https://github.com/owner/repo/issues/2990"), + User: &github.User{Login: new("author")}, } restClient := MockHTTPClientWithHandlers(map[string]http.HandlerFunc{ @@ -1093,29 +1093,29 @@ func Test_SearchIssues(t *testing.T) { // Setup mock search results mockSearchResult := &github.IssuesSearchResult{ - Total: github.Ptr(2), - IncompleteResults: github.Ptr(false), + Total: new(2), + IncompleteResults: new(false), Issues: []*github.Issue{ { - Number: github.Ptr(42), - Title: github.Ptr("Bug: Something is broken"), - Body: github.Ptr("This is a bug report"), - State: github.Ptr("open"), - HTMLURL: github.Ptr("https://github.com/owner/repo/issues/42"), - Comments: github.Ptr(5), + Number: new(42), + Title: new("Bug: Something is broken"), + Body: new("This is a bug report"), + State: new("open"), + HTMLURL: new("https://github.com/owner/repo/issues/42"), + Comments: new(5), User: &github.User{ - Login: github.Ptr("user1"), + Login: new("user1"), }, }, { - Number: github.Ptr(43), - Title: github.Ptr("Feature: Add new functionality"), - Body: github.Ptr("This is a feature request"), - State: github.Ptr("open"), - HTMLURL: github.Ptr("https://github.com/owner/repo/issues/43"), - Comments: github.Ptr(3), + Number: new(43), + Title: new("Feature: Add new functionality"), + Body: new("This is a feature request"), + State: new("open"), + HTMLURL: new("https://github.com/owner/repo/issues/43"), + Comments: new(3), User: &github.User{ - Login: github.Ptr("user2"), + Login: new("user2"), }, }, }, @@ -1439,11 +1439,11 @@ func Test_SearchIssues_IFC_InsidersMode(t *testing.T) { makeIssue := func(owner, repo string, number int) *github.Issue { return &github.Issue{ - Number: github.Ptr(number), - Title: github.Ptr("issue"), - State: github.Ptr("open"), - RepositoryURL: github.Ptr("https://api.github.com/repos/" + owner + "/" + repo), - User: &github.User{Login: github.Ptr("u")}, + Number: new(number), + Title: new("issue"), + State: new("open"), + RepositoryURL: new("https://api.github.com/repos/" + owner + "/" + repo), + User: &github.User{Login: new("u")}, } } @@ -1720,17 +1720,17 @@ func Test_SearchIssues_FieldValuesEnrichment(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { mockSearchResult := &github.IssuesSearchResult{ - Total: github.Ptr(1), - IncompleteResults: github.Ptr(false), + Total: new(1), + IncompleteResults: new(false), Issues: []*github.Issue{ { - Number: github.Ptr(42), - Title: github.Ptr("Bug: Something is broken"), - Body: github.Ptr("Details"), - State: github.Ptr("open"), - HTMLURL: github.Ptr("https://github.com/owner/repo/issues/42"), - NodeID: github.Ptr("I_node_42"), - User: &github.User{Login: github.Ptr("user1")}, + Number: new(42), + Title: new("Bug: Something is broken"), + Body: new("Details"), + State: new("open"), + HTMLURL: new("https://github.com/owner/repo/issues/42"), + NodeID: new("I_node_42"), + User: &github.User{Login: new("user1")}, IssueFieldValues: []*github.IssueFieldValue{ {IssueFieldID: 99, DataType: "text", Value: "raw REST value"}, }, @@ -1851,15 +1851,15 @@ func Test_CreateIssue(t *testing.T) { // Setup mock issue for success case mockIssue := &github.Issue{ - Number: github.Ptr(123), - Title: github.Ptr("Test Issue"), - Body: github.Ptr("This is a test issue"), - State: github.Ptr("open"), - HTMLURL: github.Ptr("https://github.com/owner/repo/issues/123"), - Assignees: []*github.User{{Login: github.Ptr("user1")}, {Login: github.Ptr("user2")}}, + Number: new(123), + Title: new("Test Issue"), + Body: new("This is a test issue"), + State: new("open"), + HTMLURL: new("https://github.com/owner/repo/issues/123"), + Assignees: []*github.User{{Login: new("user1")}, {Login: new("user2")}}, Labels: []*github.Label{{Name: "bug"}, {Name: "help wanted"}}, - Milestone: &github.Milestone{Number: github.Ptr(5)}, - Type: &github.IssueType{Name: github.Ptr("Bug")}, + Milestone: &github.Milestone{Number: new(5)}, + Type: &github.IssueType{Name: new("Bug")}, } tests := []struct { @@ -1903,10 +1903,10 @@ func Test_CreateIssue(t *testing.T) { name: "successful issue creation with minimal fields", mockedClient: MockHTTPClientWithHandlers(map[string]http.HandlerFunc{ PostReposIssuesByOwnerByRepo: mockResponse(t, http.StatusCreated, &github.Issue{ - Number: github.Ptr(124), - Title: github.Ptr("Minimal Issue"), - HTMLURL: github.Ptr("https://github.com/owner/repo/issues/124"), - State: github.Ptr("open"), + Number: new(124), + Title: new("Minimal Issue"), + HTMLURL: new("https://github.com/owner/repo/issues/124"), + State: new("open"), }), }), requestArgs: map[string]any{ @@ -1918,10 +1918,10 @@ func Test_CreateIssue(t *testing.T) { }, expectError: false, expectedIssue: &github.Issue{ - Number: github.Ptr(124), - Title: github.Ptr("Minimal Issue"), - HTMLURL: github.Ptr("https://github.com/owner/repo/issues/124"), - State: github.Ptr("open"), + Number: new(124), + Title: new("Minimal Issue"), + HTMLURL: new("https://github.com/owner/repo/issues/124"), + State: new("open"), }, }, { @@ -1936,10 +1936,10 @@ func Test_CreateIssue(t *testing.T) { }, }).andThen( mockResponse(t, http.StatusCreated, &github.Issue{ - Number: github.Ptr(125), - Title: github.Ptr("Issue with fields"), - HTMLURL: github.Ptr("https://github.com/owner/repo/issues/125"), - State: github.Ptr("open"), + Number: new(125), + Title: new("Issue with fields"), + HTMLURL: new("https://github.com/owner/repo/issues/125"), + State: new("open"), }), ), }), @@ -1987,10 +1987,10 @@ func Test_CreateIssue(t *testing.T) { }, expectError: false, expectedIssue: &github.Issue{ - Number: github.Ptr(125), - Title: github.Ptr("Issue with fields"), - HTMLURL: github.Ptr("https://github.com/owner/repo/issues/125"), - State: github.Ptr("open"), + Number: new(125), + Title: new("Issue with fields"), + HTMLURL: new("https://github.com/owner/repo/issues/125"), + State: new("open"), }, }, { @@ -2132,9 +2132,9 @@ func TestIssueWriteReportsUnappliedLabels(t *testing.T) { responseLabels = append(responseLabels, &github.Label{Name: label}) } responseIssue := &github.Issue{ - ID: github.Ptr(int64(123)), - Number: github.Ptr(123), - HTMLURL: github.Ptr("https://github.com/owner/repo/issues/123"), + ID: new(int64(123)), + Number: new(123), + HTMLURL: new("https://github.com/owner/repo/issues/123"), Labels: responseLabels, } @@ -2202,9 +2202,9 @@ func Test_IssueWrite_MCPAppsFeature_UIGate(t *testing.T) { t.Parallel() mockIssue := &github.Issue{ - Number: github.Ptr(1), - Title: github.Ptr("Test"), - HTMLURL: github.Ptr("https://github.com/owner/repo/issues/1"), + Number: new(1), + Title: new("Test"), + HTMLURL: new("https://github.com/owner/repo/issues/1"), } serverTool := IssueWrite(translations.NullTranslationHelper) @@ -2216,7 +2216,7 @@ func Test_IssueWrite_MCPAppsFeature_UIGate(t *testing.T) { deps := BaseDeps{ Client: client, GQLClient: githubv4.NewClient(nil), - featureChecker: featureCheckerFor(MCPAppsFeatureFlag), + featureChecker: featureCheckerFor(), } handler := serverTool.Handler(deps) @@ -2568,7 +2568,7 @@ func TestIssueWriteCreateWithParentPreservesSupportedFields(t *testing.T) { ) restHTTPClient := MockHTTPClientWithHandlers(map[string]http.HandlerFunc{ "GET /repos/{owner}/{repo}/issue-types": mockResponse(t, http.StatusOK, []*github.IssueType{ - {Name: github.Ptr("Bug"), NodeID: github.Ptr("ISSUE_TYPE_bug")}, + {Name: new("Bug"), NodeID: new("ISSUE_TYPE_bug")}, }), }) restCounter := &countingRoundTripper{next: restHTTPClient.Transport} @@ -4629,36 +4629,36 @@ func Test_UpdateIssue(t *testing.T) { // Mock issues for reuse across test cases mockBaseIssue := &github.Issue{ - Number: github.Ptr(123), - Title: github.Ptr("Title"), - Body: github.Ptr("Description"), - State: github.Ptr("open"), - HTMLURL: github.Ptr("https://github.com/owner/repo/issues/123"), - Assignees: []*github.User{{Login: github.Ptr("assignee1")}, {Login: github.Ptr("assignee2")}}, + Number: new(123), + Title: new("Title"), + Body: new("Description"), + State: new("open"), + HTMLURL: new("https://github.com/owner/repo/issues/123"), + Assignees: []*github.User{{Login: new("assignee1")}, {Login: new("assignee2")}}, Labels: []*github.Label{{Name: "bug"}, {Name: "priority"}}, - Milestone: &github.Milestone{Number: github.Ptr(5)}, - Type: &github.IssueType{Name: github.Ptr("Bug")}, + Milestone: &github.Milestone{Number: new(5)}, + Type: &github.IssueType{Name: new("Bug")}, } mockUpdatedIssue := &github.Issue{ - Number: github.Ptr(123), - Title: github.Ptr("Updated Title"), - Body: github.Ptr("Updated Description"), - State: github.Ptr("closed"), - StateReason: github.Ptr("duplicate"), - HTMLURL: github.Ptr("https://github.com/owner/repo/issues/123"), - Assignees: []*github.User{{Login: github.Ptr("assignee1")}, {Login: github.Ptr("assignee2")}}, + Number: new(123), + Title: new("Updated Title"), + Body: new("Updated Description"), + State: new("closed"), + StateReason: new("duplicate"), + HTMLURL: new("https://github.com/owner/repo/issues/123"), + Assignees: []*github.User{{Login: new("assignee1")}, {Login: new("assignee2")}}, Labels: []*github.Label{{Name: "bug"}, {Name: "priority"}}, - Milestone: &github.Milestone{Number: github.Ptr(5)}, - Type: &github.IssueType{Name: github.Ptr("Bug")}, + Milestone: &github.Milestone{Number: new(5)}, + Type: &github.IssueType{Name: new("Bug")}, } mockReopenedIssue := &github.Issue{ - Number: github.Ptr(123), - Title: github.Ptr("Title"), - State: github.Ptr("open"), - StateReason: github.Ptr("reopened"), - HTMLURL: github.Ptr("https://github.com/owner/repo/issues/123"), + Number: new(123), + Title: new("Title"), + State: new("open"), + StateReason: new("reopened"), + HTMLURL: new("https://github.com/owner/repo/issues/123"), } // Mock GraphQL responses for reuse across test cases @@ -4745,8 +4745,8 @@ func Test_UpdateIssue(t *testing.T) { "assignees": []any{}, }).andThen( mockResponse(t, http.StatusOK, &github.Issue{ - Number: github.Ptr(123), - HTMLURL: github.Ptr("https://github.com/owner/repo/issues/123"), + Number: new(123), + HTMLURL: new("https://github.com/owner/repo/issues/123"), }), ), }), @@ -4761,7 +4761,7 @@ func Test_UpdateIssue(t *testing.T) { }, expectError: false, expectedIssue: &github.Issue{ - HTMLURL: github.Ptr("https://github.com/owner/repo/issues/123"), + HTMLURL: new("https://github.com/owner/repo/issues/123"), }, }, { @@ -5047,15 +5047,15 @@ func Test_UpdateIssue(t *testing.T) { "type": "Bug", }).andThen( mockResponse(t, http.StatusOK, &github.Issue{ - Number: github.Ptr(123), - Title: github.Ptr("Updated Title"), - Body: github.Ptr("Updated Description"), + Number: new(123), + Title: new("Updated Title"), + Body: new("Updated Description"), Labels: []*github.Label{{Name: "bug"}, {Name: "priority"}}, - Assignees: []*github.User{{Login: github.Ptr("assignee1")}, {Login: github.Ptr("assignee2")}}, - Milestone: &github.Milestone{Number: github.Ptr(5)}, - Type: &github.IssueType{Name: github.Ptr("Bug")}, - State: github.Ptr("open"), // Still open after REST update - HTMLURL: github.Ptr("https://github.com/owner/repo/issues/123"), + Assignees: []*github.User{{Login: new("assignee1")}, {Login: new("assignee2")}}, + Milestone: &github.Milestone{Number: new(5)}, + Type: &github.IssueType{Name: new("Bug")}, + State: new("open"), // Still open after REST update + HTMLURL: new("https://github.com/owner/repo/issues/123"), }), ), }), @@ -5214,8 +5214,8 @@ func Test_UpdateIssue(t *testing.T) { func Test_UpdateIssueClearsLabelsAndAssignees(t *testing.T) { serverTool := IssueWrite(translations.NullTranslationHelper) updatedIssue := &github.Issue{ - Number: github.Ptr(8), - HTMLURL: github.Ptr("https://github.com/owner/repo/issues/8"), + Number: new(8), + HTMLURL: new("https://github.com/owner/repo/issues/8"), } client := mustNewGHClient(t, MockHTTPClientWithHandlers(map[string]http.HandlerFunc{ @@ -5321,18 +5321,18 @@ func Test_GetIssueComments(t *testing.T) { // Setup mock comments for success case mockComments := []*github.IssueComment{ { - ID: github.Ptr(int64(123)), - Body: github.Ptr("This is the first comment"), + ID: new(int64(123)), + Body: new("This is the first comment"), User: &github.User{ - Login: github.Ptr("user1"), + Login: new("user1"), }, CreatedAt: &github.Timestamp{Time: time.Now().Add(-time.Hour * 24)}, }, { - ID: github.Ptr(int64(456)), - Body: github.Ptr("This is the second comment"), + ID: new(int64(456)), + Body: new("This is the second comment"), User: &github.User{ - Login: github.Ptr("user2"), + Login: new("user2"), }, CreatedAt: &github.Timestamp{Time: time.Now().Add(-time.Hour)}, }, @@ -5401,14 +5401,14 @@ func Test_GetIssueComments(t *testing.T) { mockedClient: MockHTTPClientWithHandlers(map[string]http.HandlerFunc{ GetReposIssuesCommentsByOwnerByRepoByIssueNumber: mockResponse(t, http.StatusOK, []*github.IssueComment{ { - ID: github.Ptr(int64(789)), - Body: github.Ptr("Maintainer comment"), - User: &github.User{Login: github.Ptr("maintainer")}, + ID: new(int64(789)), + Body: new("Maintainer comment"), + User: &github.User{Login: new("maintainer")}, }, { - ID: github.Ptr(int64(790)), - Body: github.Ptr("External user comment"), - User: &github.User{Login: github.Ptr("testuser")}, + ID: new(int64(790)), + Body: new("External user comment"), + User: &github.User{Login: new("testuser")}, }, }), }), @@ -5421,9 +5421,9 @@ func Test_GetIssueComments(t *testing.T) { expectError: false, expectedComments: []*github.IssueComment{ { - ID: github.Ptr(int64(789)), - Body: github.Ptr("Maintainer comment"), - User: &github.User{Login: github.Ptr("maintainer")}, + ID: new(int64(789)), + Body: new("Maintainer comment"), + User: &github.User{Login: new("maintainer")}, }, }, lockdownEnabled: true, @@ -5773,19 +5773,19 @@ func Test_AddSubIssue(t *testing.T) { // Setup mock issue for success case (matches GitHub API response format) mockIssue := &github.Issue{ - Number: github.Ptr(42), - Title: github.Ptr("can't \"quote\" AT&T\u200B"), - Body: github.Ptr("This is **Markdown**\u200B"), - State: github.Ptr("open"), - HTMLURL: github.Ptr("https://github.com/owner/repo/issues/42"), + Number: new(42), + Title: new("can't \"quote\" AT&T\u200B"), + Body: new("This is **Markdown**\u200B"), + State: new("open"), + HTMLURL: new("https://github.com/owner/repo/issues/42"), User: &github.User{ - Login: github.Ptr("testuser"), + Login: new("testuser"), }, Labels: []*github.Label{ { Name: "enhancement", Color: "84b6eb", - Description: github.Ptr("New feature or request"), + Description: new("New feature or request"), }, }, } @@ -5998,33 +5998,33 @@ func Test_GetSubIssues(t *testing.T) { // Setup mock sub-issues for success case mockSubIssues := []*github.Issue{ { - Number: github.Ptr(123), - Title: github.Ptr("can't \"quote\" AT&T\u200B"), - Body: github.Ptr("This is **Markdown**\u200B"), - State: github.Ptr("open"), - HTMLURL: github.Ptr("https://github.com/owner/repo/issues/123"), + Number: new(123), + Title: new("can't \"quote\" AT&T\u200B"), + Body: new("This is **Markdown**\u200B"), + State: new("open"), + HTMLURL: new("https://github.com/owner/repo/issues/123"), User: &github.User{ - Login: github.Ptr("user1"), + Login: new("user1"), }, Labels: []*github.Label{ { Name: "bug", Color: "d73a4a", - Description: github.Ptr("Something isn't working"), + Description: new("Something isn't working"), }, }, }, { - Number: github.Ptr(124), - Title: github.Ptr("Sub-issue 2"), - Body: github.Ptr("This is the second sub-issue"), - State: github.Ptr("closed"), - HTMLURL: github.Ptr("https://github.com/owner/repo/issues/124"), + Number: new(124), + Title: new("Sub-issue 2"), + Body: new("This is the second sub-issue"), + State: new("closed"), + HTMLURL: new("https://github.com/owner/repo/issues/124"), User: &github.User{ - Login: github.Ptr("user2"), + Login: new("user2"), }, Assignees: []*github.User{ - {Login: github.Ptr("assignee1")}, + {Login: new("assignee1")}, }, }, } @@ -6321,17 +6321,17 @@ func TestAddIssueCommentHandler(t *testing.T) { serverTool := AddIssueComment(translations.NullTranslationHelper) mockComment := &github.IssueComment{ - ID: github.Ptr(int64(456)), - Body: github.Ptr("This is a comment"), - HTMLURL: github.Ptr("https://github.com/owner/repo/issues/42#issuecomment-456"), + ID: new(int64(456)), + Body: new("This is a comment"), + HTMLURL: new("https://github.com/owner/repo/issues/42#issuecomment-456"), } mockReaction := &github.Reaction{ - ID: github.Ptr(int64(789)), - Content: github.Ptr("heart"), + ID: new(int64(789)), + Content: new("heart"), } mockIssueComment := &github.IssueComment{ - ID: github.Ptr(int64(999)), - IssueURL: github.Ptr("https://api.github.com/repos/owner/repo/issues/42"), + ID: new(int64(999)), + IssueURL: new("https://api.github.com/repos/owner/repo/issues/42"), } commentCreatedAfterReactionFailure := &atomic.Bool{} @@ -6346,7 +6346,9 @@ func TestAddIssueCommentHandler(t *testing.T) { { name: "successful comment on issue", mockedClient: MockHTTPClientWithHandlers(map[string]http.HandlerFunc{ - PostReposIssuesCommentsByOwnerByRepoByIssueNumber: mockResponse(t, http.StatusCreated, mockComment), + PostReposIssuesCommentsByOwnerByRepoByIssueNumber: expectRequestBody(t, map[string]any{ + "body": "This is a comment", + }).andThen(mockResponse(t, http.StatusCreated, mockComment)), }), requestArgs: map[string]any{ "owner": "owner", @@ -6385,8 +6387,8 @@ func TestAddIssueCommentHandler(t *testing.T) { name: "issue comment reaction requires matching issue_number", mockedClient: MockHTTPClientWithHandlers(map[string]http.HandlerFunc{ GetReposIssuesCommentByOwnerByRepoByCommentID: mockResponse(t, http.StatusOK, &github.IssueComment{ - ID: github.Ptr(int64(999)), - IssueURL: github.Ptr("https://api.github.com/repos/owner/repo/issues/43"), + ID: new(int64(999)), + IssueURL: new("https://api.github.com/repos/owner/repo/issues/43"), }), }), requestArgs: map[string]any{ @@ -6715,9 +6717,9 @@ func TestUpdateIssueCommentHandler(t *testing.T) { t.Parallel() updatedComment := &github.IssueComment{ - ID: github.Ptr(int64(456)), - Body: github.Ptr("Updated comment"), - HTMLURL: github.Ptr("https://github.com/owner/repo/issues/42#issuecomment-456"), + ID: new(int64(456)), + Body: new("Updated comment"), + HTMLURL: new("https://github.com/owner/repo/issues/42#issuecomment-456"), } tests := []struct { @@ -6845,19 +6847,19 @@ func Test_RemoveSubIssue(t *testing.T) { // Setup mock issue for success case (matches GitHub API response format - the updated parent issue) mockIssue := &github.Issue{ - Number: github.Ptr(42), - Title: github.Ptr("can't \"quote\" AT&T\u200B"), - Body: github.Ptr("This is **Markdown**\u200B"), - State: github.Ptr("open"), - HTMLURL: github.Ptr("https://github.com/owner/repo/issues/42"), + Number: new(42), + Title: new("can't \"quote\" AT&T\u200B"), + Body: new("This is **Markdown**\u200B"), + State: new("open"), + HTMLURL: new("https://github.com/owner/repo/issues/42"), User: &github.User{ - Login: github.Ptr("testuser"), + Login: new("testuser"), }, Labels: []*github.Label{ { Name: "enhancement", Color: "84b6eb", - Description: github.Ptr("New feature or request"), + Description: new("New feature or request"), }, }, } @@ -7053,19 +7055,19 @@ func Test_ReprioritizeSubIssue(t *testing.T) { // Setup mock issue for success case (matches GitHub API response format - the updated parent issue) mockIssue := &github.Issue{ - Number: github.Ptr(42), - Title: github.Ptr("can't \"quote\" AT&T\u200B"), - Body: github.Ptr("This is **Markdown**\u200B"), - State: github.Ptr("open"), - HTMLURL: github.Ptr("https://github.com/owner/repo/issues/42"), + Number: new(42), + Title: new("can't \"quote\" AT&T\u200B"), + Body: new("This is **Markdown**\u200B"), + State: new("open"), + HTMLURL: new("https://github.com/owner/repo/issues/42"), User: &github.User{ - Login: github.Ptr("testuser"), + Login: new("testuser"), }, Labels: []*github.Label{ { Name: "enhancement", Color: "84b6eb", - Description: github.Ptr("New feature or request"), + Description: new("New feature or request"), }, }, } @@ -7308,16 +7310,16 @@ func Test_ListIssueTypes(t *testing.T) { // Setup mock issue types for success case mockIssueTypes := []*github.IssueType{ { - ID: github.Ptr(int64(1)), - Name: github.Ptr("bug"), - Description: github.Ptr("Something isn't working"), - Color: github.Ptr("d73a4a"), + ID: new(int64(1)), + Name: new("bug"), + Description: new("Something isn't working"), + Color: new("d73a4a"), }, { - ID: github.Ptr(int64(2)), - Name: github.Ptr("feature"), - Description: github.Ptr("New feature or enhancement"), - Color: github.Ptr("a2eeef"), + ID: new(int64(2)), + Name: new("feature"), + Description: new("New feature or enhancement"), + Color: new("a2eeef"), }, } diff --git a/pkg/github/labels.go b/pkg/github/labels.go index 4be66a7c7d..c9479e5062 100644 --- a/pkg/github/labels.go +++ b/pkg/github/labels.go @@ -6,12 +6,12 @@ import ( "fmt" "strings" - ghErrors "github.com/github/github-mcp-server/pkg/errors" - "github.com/github/github-mcp-server/pkg/ifc" - "github.com/github/github-mcp-server/pkg/inventory" - "github.com/github/github-mcp-server/pkg/scopes" - "github.com/github/github-mcp-server/pkg/translations" - "github.com/github/github-mcp-server/pkg/utils" + ghErrors "github.com/github/github-mcp-server/v2/pkg/errors" + "github.com/github/github-mcp-server/v2/pkg/ifc" + "github.com/github/github-mcp-server/v2/pkg/inventory" + "github.com/github/github-mcp-server/v2/pkg/scopes" + "github.com/github/github-mcp-server/v2/pkg/translations" + "github.com/github/github-mcp-server/v2/pkg/utils" "github.com/google/jsonschema-go/jsonschema" "github.com/modelcontextprotocol/go-sdk/mcp" "github.com/shurcooL/githubv4" @@ -24,6 +24,10 @@ const labelOrderFieldIssueCount githubv4.LabelOrderField = "ISSUE_COUNT" // GetLabel retrieves a specific label by name from a GitHub repository func GetLabel(t translations.TranslationHelperFunc) inventory.ServerTool { + return typedGovernanceTool(getLabelLegacy(t), labelOutputSchema(), decodeGovernanceJSON[MinimalLabel]) +} + +func getLabelLegacy(t translations.TranslationHelperFunc) inventory.ServerTool { return NewTool( ToolsetMetadataIssues, mcp.Tool{ @@ -128,18 +132,25 @@ func GetLabelForLabelsToolset(t translations.TranslationHelperFunc) inventory.Se return tool } +// listLabelsDefaultPerPage keeps the first page as large as GraphQL allows, so most repositories need one call. +const listLabelsDefaultPerPage = 100 + // ListLabels lists labels from a repository func ListLabels(t translations.TranslationHelperFunc) inventory.ServerTool { + return typedGovernanceTool(listLabelsLegacy(t), listLabelsOutputSchema(), decodeGovernanceJSON[ListLabelsOutput]) +} + +func listLabelsLegacy(t translations.TranslationHelperFunc) inventory.ServerTool { return NewTool( ToolsetLabels, mcp.Tool{ Name: "list_label", - Description: t("TOOL_LIST_LABEL_DESCRIPTION", "List labels from a repository, ordered by issue count (descending) so the most-used labels are returned first"), + Description: t("TOOL_LIST_LABEL_DESCRIPTION", "List labels from a repository, ordered by issue count (descending) so the most-used labels are returned first. For pagination, use the 'endCursor' from the previous response's 'pageInfo' in the 'after' parameter."), Annotations: &mcp.ToolAnnotations{ Title: t("TOOL_LIST_LABEL_TITLE", "List labels from a repository"), ReadOnlyHint: true, }, - InputSchema: &jsonschema.Schema{ + InputSchema: WithCursorPagination(&jsonschema.Schema{ Type: "object", Properties: map[string]*jsonschema.Schema{ "owner": { @@ -152,7 +163,7 @@ func ListLabels(t translations.TranslationHelperFunc) inventory.ServerTool { }, }, Required: []string{"owner", "repo"}, - }, + }), }, scopes.PublicRead(scopes.Repo), func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, args map[string]any) (*mcp.CallToolResult, any, error) { @@ -166,6 +177,19 @@ func ListLabels(t translations.TranslationHelperFunc) inventory.ServerTool { return utils.NewToolResultError(err.Error()), nil, nil } + perPage, err := OptionalIntParamWithDefault(args, "perPage", listLabelsDefaultPerPage) + if err != nil { + return utils.NewToolResultError(err.Error()), nil, nil + } + after, err := OptionalParam[string](args, "after") + if err != nil { + return utils.NewToolResultError(err.Error()), nil, nil + } + paginationParams, err := CursorPaginationParams{PerPage: perPage, After: after}.ToGraphQLParams() + if err != nil { + return utils.NewToolResultError(err.Error()), nil, nil + } + client, err := deps.GetGQLClient(ctx) if err != nil { return nil, nil, fmt.Errorf("failed to get GitHub client: %w", err) @@ -181,17 +205,29 @@ func ListLabels(t translations.TranslationHelperFunc) inventory.ServerTool { Description githubv4.String } TotalCount githubv4.Int - } `graphql:"labels(first: 100, orderBy: {field: $orderByField, direction: $orderByDirection})"` + PageInfo struct { + HasNextPage githubv4.Boolean + HasPreviousPage githubv4.Boolean + StartCursor githubv4.String + EndCursor githubv4.String + } + } `graphql:"labels(first: $first, after: $after, orderBy: {field: $orderByField, direction: $orderByDirection})"` } `graphql:"repository(owner: $owner, name: $repo)"` } vars := map[string]any{ "owner": githubv4.String(owner), "repo": githubv4.String(repo), + "first": githubv4.Int(*paginationParams.First), // Order labels by issue count (descending) so the most-used labels are returned first. "orderByField": labelOrderFieldIssueCount, "orderByDirection": githubv4.OrderDirectionDesc, } + if paginationParams.After != nil { + vars["after"] = githubv4.String(*paginationParams.After) + } else { + vars["after"] = (*githubv4.String)(nil) + } if err := client.Query(ctx, &query, vars); err != nil { return ghErrors.NewGitHubGraphQLErrorResponse(ctx, "Failed to list labels", err), nil, nil @@ -207,9 +243,16 @@ func ListLabels(t translations.TranslationHelperFunc) inventory.ServerTool { } } + labelsPage := query.Repository.Labels.PageInfo response := map[string]any{ "labels": labels, "totalCount": int(query.Repository.Labels.TotalCount), + "pageInfo": MinimalPageInfo{ + HasNextPage: bool(labelsPage.HasNextPage), + HasPreviousPage: bool(labelsPage.HasPreviousPage), + StartCursor: string(labelsPage.StartCursor), + EndCursor: string(labelsPage.EndCursor), + }, } out, err := json.Marshal(response) @@ -228,6 +271,12 @@ func ListLabels(t translations.TranslationHelperFunc) inventory.ServerTool { // LabelWrite handles create, update, and delete operations for GitHub labels func LabelWrite(t translations.TranslationHelperFunc) inventory.ServerTool { + return typedGovernanceTool(labelWriteLegacy(t), labelWriteOutputSchema(), func(raw []byte, args map[string]json.RawMessage) (LabelWriteOutput, error) { + return LabelWriteOutput{Method: strings.ToLower(governanceArgument(args, "method")), Message: string(raw)}, nil + }) +} + +func labelWriteLegacy(t translations.TranslationHelperFunc) inventory.ServerTool { return NewTool( ToolsetLabels, mcp.Tool{ @@ -236,7 +285,7 @@ func LabelWrite(t translations.TranslationHelperFunc) inventory.ServerTool { Annotations: &mcp.ToolAnnotations{ Title: t("TOOL_LABEL_WRITE_TITLE", "Write operations on repository labels"), ReadOnlyHint: false, - DestructiveHint: jsonschema.Ptr(true), + DestructiveHint: new(true), }, InputSchema: &jsonschema.Schema{ Type: "object", diff --git a/pkg/github/labels_test.go b/pkg/github/labels_test.go index b030c9cab7..43075659bc 100644 --- a/pkg/github/labels_test.go +++ b/pkg/github/labels_test.go @@ -2,12 +2,13 @@ package github import ( "context" + "encoding/json" "net/http" "testing" - "github.com/github/github-mcp-server/internal/githubv4mock" - "github.com/github/github-mcp-server/internal/toolsnaps" - "github.com/github/github-mcp-server/pkg/translations" + "github.com/github/github-mcp-server/v2/internal/githubv4mock" + "github.com/github/github-mcp-server/v2/internal/toolsnaps" + "github.com/github/github-mcp-server/v2/pkg/translations" "github.com/shurcooL/githubv4" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -156,6 +157,7 @@ func TestListLabels(t *testing.T) { mockedClient *http.Client expectToolError bool expectedToolErrMsg string + expectedPageInfo MinimalPageInfo }{ { name: "successful repository labels listing", @@ -163,51 +165,57 @@ func TestListLabels(t *testing.T) { "owner": "owner", "repo": "repo", }, - mockedClient: githubv4mock.NewMockedHTTPClient( - githubv4mock.NewQueryMatcher( - struct { - Repository struct { - Labels struct { - Nodes []struct { - ID githubv4.ID - Name githubv4.String - Color githubv4.String - Description githubv4.String - } - TotalCount githubv4.Int - } `graphql:"labels(first: 100, orderBy: {field: $orderByField, direction: $orderByDirection})"` - } `graphql:"repository(owner: $owner, name: $repo)"` - }{}, - map[string]any{ - "owner": githubv4.String("owner"), - "repo": githubv4.String("repo"), - "orderByField": labelOrderFieldIssueCount, - "orderByDirection": githubv4.OrderDirectionDesc, - }, - githubv4mock.DataResponse(map[string]any{ - "repository": map[string]any{ - "labels": map[string]any{ - "nodes": []any{ - map[string]any{ - "id": githubv4.ID("label-1"), - "name": githubv4.String("bug"), - "color": githubv4.String("d73a4a"), - "description": githubv4.String("Something isn't working"), - }, - map[string]any{ - "id": githubv4.ID("label-2"), - "name": githubv4.String("enhancement"), - "color": githubv4.String("a2eeef"), - "description": githubv4.String("New feature or request"), - }, - }, - "totalCount": githubv4.Int(2), - }, - }, - }), - ), - ), - expectToolError: false, + mockedClient: githubv4mock.NewMockedHTTPClient(listLabelsMatcher(100, (*githubv4.String)(nil), map[string]any{ + "hasNextPage": githubv4.Boolean(false), + "hasPreviousPage": githubv4.Boolean(false), + "startCursor": githubv4.String("c1"), + "endCursor": githubv4.String("c2"), + })), + expectToolError: false, + expectedPageInfo: MinimalPageInfo{StartCursor: "c1", EndCursor: "c2"}, + }, + { + name: "reports the next page when the repository has more labels", + requestArgs: map[string]any{ + "owner": "owner", + "repo": "repo", + "perPage": float64(2), + }, + mockedClient: githubv4mock.NewMockedHTTPClient(listLabelsMatcher(2, (*githubv4.String)(nil), map[string]any{ + "hasNextPage": githubv4.Boolean(true), + "hasPreviousPage": githubv4.Boolean(false), + "startCursor": githubv4.String("c1"), + "endCursor": githubv4.String("c2"), + })), + expectToolError: false, + expectedPageInfo: MinimalPageInfo{HasNextPage: true, StartCursor: "c1", EndCursor: "c2"}, + }, + { + name: "passes the after cursor to fetch the next page", + requestArgs: map[string]any{ + "owner": "owner", + "repo": "repo", + "after": "c2", + }, + mockedClient: githubv4mock.NewMockedHTTPClient(listLabelsMatcher(100, githubv4.String("c2"), map[string]any{ + "hasNextPage": githubv4.Boolean(false), + "hasPreviousPage": githubv4.Boolean(true), + "startCursor": githubv4.String("c3"), + "endCursor": githubv4.String("c4"), + })), + expectToolError: false, + expectedPageInfo: MinimalPageInfo{HasPreviousPage: true, StartCursor: "c3", EndCursor: "c4"}, + }, + { + name: "rejects a page size above 100", + requestArgs: map[string]any{ + "owner": "owner", + "repo": "repo", + "perPage": float64(101), + }, + mockedClient: githubv4mock.NewMockedHTTPClient(), + expectToolError: true, + expectedToolErrMsg: "perPage value 101 exceeds maximum of 100", }, } @@ -233,11 +241,61 @@ func TestListLabels(t *testing.T) { } } else { assert.False(t, result.IsError) + var response ListLabelsOutput + require.NoError(t, json.Unmarshal([]byte(getTextResult(t, result).Text), &response)) + assert.Len(t, response.Labels, 2) + assert.Equal(t, 5, response.TotalCount) + assert.Equal(t, tc.expectedPageInfo, response.PageInfo) } }) } } +// listLabelsMatcher matches one list_label page request and answers with two labels and the given page info. +func listLabelsMatcher(first int32, after any, pageInfo map[string]any) githubv4mock.Matcher { + return githubv4mock.NewQueryMatcher( + struct { + Repository struct { + Labels struct { + Nodes []struct { + ID githubv4.ID + Name githubv4.String + Color githubv4.String + Description githubv4.String + } + TotalCount githubv4.Int + PageInfo struct { + HasNextPage githubv4.Boolean + HasPreviousPage githubv4.Boolean + StartCursor githubv4.String + EndCursor githubv4.String + } + } `graphql:"labels(first: $first, after: $after, orderBy: {field: $orderByField, direction: $orderByDirection})"` + } `graphql:"repository(owner: $owner, name: $repo)"` + }{}, + map[string]any{ + "owner": githubv4.String("owner"), + "repo": githubv4.String("repo"), + "first": githubv4.Int(first), + "after": after, + "orderByField": labelOrderFieldIssueCount, + "orderByDirection": githubv4.OrderDirectionDesc, + }, + githubv4mock.DataResponse(map[string]any{ + "repository": map[string]any{ + "labels": map[string]any{ + "nodes": []any{ + map[string]any{"id": githubv4.ID("label-1"), "name": githubv4.String("bug"), "color": githubv4.String("d73a4a"), "description": githubv4.String("Something isn't working")}, + map[string]any{"id": githubv4.ID("label-2"), "name": githubv4.String("enhancement"), "color": githubv4.String("a2eeef"), "description": githubv4.String("New feature or request")}, + }, + "totalCount": githubv4.Int(5), + "pageInfo": pageInfo, + }, + }, + }), + ) +} + func TestWriteLabel(t *testing.T) { t.Parallel() diff --git a/pkg/github/lockdown.go b/pkg/github/lockdown.go index 1d3a687028..b1a1b006ea 100644 --- a/pkg/github/lockdown.go +++ b/pkg/github/lockdown.go @@ -6,8 +6,8 @@ import ( "github.com/modelcontextprotocol/go-sdk/mcp" - "github.com/github/github-mcp-server/pkg/lockdown" - "github.com/github/github-mcp-server/pkg/utils" + "github.com/github/github-mcp-server/v2/pkg/lockdown" + "github.com/github/github-mcp-server/v2/pkg/utils" ) // Restriction messages returned when lockdown mode withholds content from a read tool. diff --git a/pkg/github/method_output_schema.go b/pkg/github/method_output_schema.go new file mode 100644 index 0000000000..c6b99cc458 --- /dev/null +++ b/pkg/github/method_output_schema.go @@ -0,0 +1,26 @@ +package github + +import ( + "slices" + + "github.com/google/jsonschema-go/jsonschema" +) + +func constrainMethodOutput(schema *jsonschema.Schema, payloadByMethod map[string]string, optionalPayloads ...string) { + schema.Required = []string{"method"} + for _, method := range schema.Properties["method"].Enum { + payload := payloadByMethod[method.(string)] + variant := &jsonschema.Schema{Properties: map[string]*jsonschema.Schema{ + "method": {Enum: []any{method}}, + }} + if !slices.Contains(optionalPayloads, payload) { + variant.Required = []string{payload} + } + for _, other := range payloadByMethod { + if other != payload { + variant.Properties[other] = forbiddenIssueVariantProperty() + } + } + schema.OneOf = append(schema.OneOf, variant) + } +} diff --git a/pkg/github/minimal_types.go b/pkg/github/minimal_types.go index 2eba9a1628..d355eb1a2e 100644 --- a/pkg/github/minimal_types.go +++ b/pkg/github/minimal_types.go @@ -9,10 +9,10 @@ import ( "strings" "time" - "github.com/google/go-github/v89/github" + "github.com/google/go-github/v92/github" "github.com/google/jsonschema-go/jsonschema" - "github.com/github/github-mcp-server/pkg/sanitize" + "github.com/github/github-mcp-server/v2/pkg/sanitize" ) // codeSearchItemFieldEnum lists the selectable fields for search_code result @@ -1099,6 +1099,11 @@ func convertToMinimalPullRequest(pr *github.PullRequest) MinimalPullRequest { Comments: pr.GetComments(), } + // The list endpoint omits merged but includes merged_at. + if pr.Merged == nil && pr.MergedAt != nil { + m.Merged = !pr.MergedAt.IsZero() + } + if pr.CreatedAt != nil { m.CreatedAt = pr.CreatedAt.Format(time.RFC3339) } @@ -1211,19 +1216,19 @@ func convertToMinimalProject(fullProject *github.ProjectV2) *MinimalProject { } return &MinimalProject{ - ID: github.Ptr(fullProject.GetID()), - NodeID: github.Ptr(fullProject.GetNodeID()), + ID: new(fullProject.GetID()), + NodeID: new(fullProject.GetNodeID()), Owner: convertToMinimalUser(fullProject.GetOwner()), Creator: convertToMinimalUser(fullProject.GetCreator()), - Title: github.Ptr(fullProject.GetTitle()), - Description: github.Ptr(fullProject.GetDescription()), - Public: github.Ptr(fullProject.GetPublic()), - ClosedAt: github.Ptr(fullProject.GetClosedAt()), - CreatedAt: github.Ptr(fullProject.GetCreatedAt()), - UpdatedAt: github.Ptr(fullProject.GetUpdatedAt()), - DeletedAt: github.Ptr(fullProject.GetDeletedAt()), - Number: github.Ptr(fullProject.GetNumber()), - ShortDescription: github.Ptr(fullProject.GetShortDescription()), + Title: new(fullProject.GetTitle()), + Description: new(fullProject.GetDescription()), + Public: new(fullProject.GetPublic()), + ClosedAt: new(fullProject.GetClosedAt()), + CreatedAt: new(fullProject.GetCreatedAt()), + UpdatedAt: new(fullProject.GetUpdatedAt()), + DeletedAt: new(fullProject.GetDeletedAt()), + Number: new(fullProject.GetNumber()), + ShortDescription: new(fullProject.GetShortDescription()), DeletedBy: convertToMinimalUser(fullProject.GetDeletedBy()), } } diff --git a/pkg/github/notification_output_fidelity_test.go b/pkg/github/notification_output_fidelity_test.go new file mode 100644 index 0000000000..7fe969e876 --- /dev/null +++ b/pkg/github/notification_output_fidelity_test.go @@ -0,0 +1,77 @@ +package github + +import ( + "context" + "encoding/json" + "net/http" + "testing" + + "github.com/github/github-mcp-server/v2/pkg/inventory" + "github.com/github/github-mcp-server/v2/pkg/translations" + "github.com/google/go-github/v92/github" + "github.com/modelcontextprotocol/go-sdk/mcp" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestNotificationOutputFidelity(t *testing.T) { + for _, subjectType := range []string{"Issue", "PullRequest", "Discussion", "FutureSubject"} { + t.Run(subjectType, func(t *testing.T) { + notification := &github.Notification{ + ID: new("123"), Reason: new("agent_session_finished"), + Subject: &github.NotificationSubject{ + Type: new(subjectType), + URL: new("https://github.example/api/v3/repos/owner/repo/issues/42"), + LatestCommentURL: new("legacy-only-comment-url"), + }, + URL: new("legacy-only-thread-url"), + } + deps := BaseDeps{Client: mustNewGHClient(t, MockHTTPClientWithHandlers(map[string]http.HandlerFunc{ + GetNotifications: mockResponse(t, http.StatusOK, []*github.Notification{notification}), + GetReposNotificationsByOwnerByRepo: mockResponse(t, http.StatusOK, []*github.Notification{notification}), + GetNotificationsThreadsByThreadID: mockResponse(t, http.StatusOK, notification), + }))} + for _, protocol := range []string{"2025-11-25", inventory.ProtocolVersionMultiRoundTrip} { + server := mcp.NewServer(&mcp.Implementation{Name: "notification-fidelity", Version: "v1"}, nil) + server.AddReceivingMiddleware(InjectDepsMiddleware(deps)) + for _, tool := range []inventory.ServerTool{ + ListNotifications(translations.NullTranslationHelper), + GetNotificationDetails(translations.NullTranslationHelper), + } { + tool.RegisterFunc(server, deps) + } + client := connectCommentVisibilityClient(t, server, protocol) + for _, call := range []mcp.CallToolParams{ + {Name: "list_notifications", Arguments: map[string]any{}}, + {Name: "list_notifications", Arguments: map[string]any{"owner": "owner", "repo": "repo"}}, + {Name: "get_notification_details", Arguments: map[string]any{"notificationID": "123"}}, + } { + result, err := client.CallTool(context.Background(), &call) + require.NoError(t, err) + require.False(t, result.IsError, "%s", getTextResult(t, result).Text) + if protocol == "2025-11-25" { + var expected any = notification + if call.Name == "list_notifications" { + expected = []*github.Notification{notification} + } + assert.Equal(t, mustMarshalJSON(t, expected), getTextResult(t, result).Text) + assert.Nil(t, result.StructuredContent) + continue + } + require.NotNil(t, result.StructuredContent) + text := mustMarshalJSON(t, result.StructuredContent) + assert.JSONEq(t, text, getTextResult(t, result).Text) + assert.Contains(t, text, `"reason":"agent_session_finished"`) + assert.Contains(t, text, `"type":"`+subjectType+`"`) + assert.Contains(t, text, `"url":"`+notification.Subject.GetURL()+`"`) + assert.NotContains(t, text, "legacy-only") + resolved, err := notificationOutputSchema(call.Name == "list_notifications").Resolve(nil) + require.NoError(t, err) + var output any + require.NoError(t, json.Unmarshal([]byte(text), &output)) + require.NoError(t, resolved.Validate(output)) + } + } + }) + } +} diff --git a/pkg/github/notifications.go b/pkg/github/notifications.go index a637951f0a..332d2ffd3b 100644 --- a/pkg/github/notifications.go +++ b/pkg/github/notifications.go @@ -8,13 +8,13 @@ import ( "net/http" "time" - ghErrors "github.com/github/github-mcp-server/pkg/errors" - "github.com/github/github-mcp-server/pkg/ifc" - "github.com/github/github-mcp-server/pkg/inventory" - "github.com/github/github-mcp-server/pkg/scopes" - "github.com/github/github-mcp-server/pkg/translations" - "github.com/github/github-mcp-server/pkg/utils" - "github.com/google/go-github/v89/github" + ghErrors "github.com/github/github-mcp-server/v2/pkg/errors" + "github.com/github/github-mcp-server/v2/pkg/ifc" + "github.com/github/github-mcp-server/v2/pkg/inventory" + "github.com/github/github-mcp-server/v2/pkg/scopes" + "github.com/github/github-mcp-server/v2/pkg/translations" + "github.com/github/github-mcp-server/v2/pkg/utils" + "github.com/google/go-github/v92/github" "github.com/google/jsonschema-go/jsonschema" "github.com/modelcontextprotocol/go-sdk/mcp" ) @@ -27,11 +27,12 @@ const ( // ListNotifications creates a tool to list notifications for the current user. func ListNotifications(t translations.TranslationHelperFunc) inventory.ServerTool { - return NewTool( + return NewTool[ListNotificationsInput, []*NotificationOutput]( ToolsetMetadataNotifications, mcp.Tool{ - Name: "list_notifications", - Description: t("TOOL_LIST_NOTIFICATIONS_DESCRIPTION", "Lists all GitHub notifications for the authenticated user, including unread notifications, mentions, review requests, assignments, and updates on issues or pull requests. Use this tool whenever the user asks what to work on next, requests a summary of their GitHub activity, wants to see pending reviews, or needs to check for new updates or tasks. This tool is the primary way to discover actionable items, reminders, and outstanding work on GitHub. Always call this tool when asked what to work on next, what is pending, or what needs attention in GitHub."), + Name: "list_notifications", + OutputSchema: notificationOutputSchema(true), + Description: t("TOOL_LIST_NOTIFICATIONS_DESCRIPTION", "Lists all GitHub notifications for the authenticated user, including unread notifications, mentions, review requests, assignments, and updates on issues or pull requests. Use this tool whenever the user asks what to work on next, requests a summary of their GitHub activity, wants to see pending reviews, or needs to check for new updates or tasks. This tool is the primary way to discover actionable items, reminders, and outstanding work on GitHub. Always call this tool when asked what to work on next, what is pending, or what needs attention in GitHub."), Annotations: &mcp.ToolAnnotations{ Title: t("TOOL_LIST_NOTIFICATIONS_USER_TITLE", "List notifications"), ReadOnlyHint: true, @@ -64,7 +65,11 @@ func ListNotifications(t translations.TranslationHelperFunc) inventory.ServerToo }), }, scopes.RequireAll(scopes.Notifications), - func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, args map[string]any) (*mcp.CallToolResult, any, error) { + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, input ListNotificationsInput) (*mcp.CallToolResult, []*NotificationOutput, error) { + args, err := discussionNotificationArguments(input) + if err != nil { + return nil, nil, err + } client, err := deps.GetClient(ctx) if err != nil { return utils.NewToolResultErrorFromErr("failed to get GitHub client", err), nil, nil @@ -103,10 +108,8 @@ func ListNotifications(t translations.TranslationHelperFunc) inventory.ServerToo opts := &github.NotificationListOptions{ All: filter == FilterIncludeRead, Participating: filter == FilterOnlyParticipating, - ListOptions: github.ListOptions{ - Page: paginationParams.Page, - PerPage: paginationParams.PerPage, - }, + Page: paginationParams.Page, + PerPage: paginationParams.PerPage, } // Parse time parameters if provided @@ -157,18 +160,24 @@ func ListNotifications(t translations.TranslationHelperFunc) inventory.ServerToo return utils.NewToolResultErrorFromErr("failed to marshal response", err), nil, nil } - return utils.NewToolResultText(string(r)), nil, nil + output := make([]*NotificationOutput, 0, len(notifications)) + for _, notification := range notifications { + output = append(output, notificationOutput(notification)) + } + return utils.NewToolResultText(string(r)), output, nil }, + normalizeDiscussionNotificationIntegers("page", "perPage"), ) } // DismissNotification creates a tool to mark a notification as read/done. func DismissNotification(t translations.TranslationHelperFunc) inventory.ServerTool { - return NewTool( + return NewTool[DismissNotificationInput, *NotificationStatusOutput]( ToolsetMetadataNotifications, mcp.Tool{ - Name: "dismiss_notification", - Description: t("TOOL_DISMISS_NOTIFICATION_DESCRIPTION", "Dismiss a notification by marking it as read or done"), + Name: "dismiss_notification", + OutputSchema: discussionNotificationOutputSchema[NotificationStatusOutput](), + Description: t("TOOL_DISMISS_NOTIFICATION_DESCRIPTION", "Dismiss a notification by marking it as read or done"), Annotations: &mcp.ToolAnnotations{ Title: t("TOOL_DISMISS_NOTIFICATION_USER_TITLE", "Dismiss notification"), ReadOnlyHint: false, @@ -190,7 +199,11 @@ func DismissNotification(t translations.TranslationHelperFunc) inventory.ServerT }, }, scopes.RequireAll(scopes.Notifications), - func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, args map[string]any) (*mcp.CallToolResult, any, error) { + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, input DismissNotificationInput) (*mcp.CallToolResult, *NotificationStatusOutput, error) { + args, err := discussionNotificationArguments(input) + if err != nil { + return nil, nil, err + } client, err := deps.GetClient(ctx) if err != nil { return utils.NewToolResultErrorFromErr("failed to get GitHub client", err), nil, nil @@ -233,18 +246,21 @@ func DismissNotification(t translations.TranslationHelperFunc) inventory.ServerT return ghErrors.NewGitHubAPIStatusErrorResponse(ctx, fmt.Sprintf("failed to mark notification as %s", state), resp, body), nil, nil } - return utils.NewToolResultText(fmt.Sprintf("Notification marked as %s", state)), nil, nil + message := fmt.Sprintf("Notification marked as %s", state) + inventory.PreserveToolHandlerContent(ctx) + return utils.NewToolResultText(message), &NotificationStatusOutput{Message: message}, nil }, ) } // MarkAllNotificationsRead creates a tool to mark all notifications as read. func MarkAllNotificationsRead(t translations.TranslationHelperFunc) inventory.ServerTool { - return NewTool( + return NewTool[MarkAllNotificationsReadInput, *NotificationStatusOutput]( ToolsetMetadataNotifications, mcp.Tool{ - Name: "mark_all_notifications_read", - Description: t("TOOL_MARK_ALL_NOTIFICATIONS_READ_DESCRIPTION", "Mark all notifications as read"), + Name: "mark_all_notifications_read", + OutputSchema: discussionNotificationOutputSchema[NotificationStatusOutput](), + Description: t("TOOL_MARK_ALL_NOTIFICATIONS_READ_DESCRIPTION", "Mark all notifications as read"), Annotations: &mcp.ToolAnnotations{ Title: t("TOOL_MARK_ALL_NOTIFICATIONS_READ_USER_TITLE", "Mark all notifications as read"), ReadOnlyHint: false, @@ -268,7 +284,11 @@ func MarkAllNotificationsRead(t translations.TranslationHelperFunc) inventory.Se }, }, scopes.RequireAll(scopes.Notifications), - func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, args map[string]any) (*mcp.CallToolResult, any, error) { + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, input MarkAllNotificationsReadInput) (*mcp.CallToolResult, *NotificationStatusOutput, error) { + args, err := discussionNotificationArguments(input) + if err != nil { + return nil, nil, err + } client, err := deps.GetClient(ctx) if err != nil { return utils.NewToolResultErrorFromErr("failed to get GitHub client", err), nil, nil @@ -325,18 +345,20 @@ func MarkAllNotificationsRead(t translations.TranslationHelperFunc) inventory.Se return ghErrors.NewGitHubAPIStatusErrorResponse(ctx, "failed to mark all notifications as read", resp, body), nil, nil } - return utils.NewToolResultText("All notifications marked as read"), nil, nil + inventory.PreserveToolHandlerContent(ctx) + return utils.NewToolResultText("All notifications marked as read"), &NotificationStatusOutput{Message: "All notifications marked as read"}, nil }, ) } // GetNotificationDetails creates a tool to get details for a specific notification. func GetNotificationDetails(t translations.TranslationHelperFunc) inventory.ServerTool { - return NewTool( + return NewTool[GetNotificationDetailsInput, *NotificationOutput]( ToolsetMetadataNotifications, mcp.Tool{ - Name: "get_notification_details", - Description: t("TOOL_GET_NOTIFICATION_DETAILS_DESCRIPTION", "Get detailed information for a specific GitHub notification, always call this tool when the user asks for details about a specific notification, if you don't know the ID list notifications first."), + Name: "get_notification_details", + OutputSchema: notificationOutputSchema(false), + Description: t("TOOL_GET_NOTIFICATION_DETAILS_DESCRIPTION", "Get detailed information for a specific GitHub notification, always call this tool when the user asks for details about a specific notification, if you don't know the ID list notifications first."), Annotations: &mcp.ToolAnnotations{ Title: t("TOOL_GET_NOTIFICATION_DETAILS_USER_TITLE", "Get notification details"), ReadOnlyHint: true, @@ -353,7 +375,11 @@ func GetNotificationDetails(t translations.TranslationHelperFunc) inventory.Serv }, }, scopes.RequireAll(scopes.Notifications), - func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, args map[string]any) (*mcp.CallToolResult, any, error) { + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, input GetNotificationDetailsInput) (*mcp.CallToolResult, *NotificationOutput, error) { + args, err := discussionNotificationArguments(input) + if err != nil { + return nil, nil, err + } client, err := deps.GetClient(ctx) if err != nil { return utils.NewToolResultErrorFromErr("failed to get GitHub client", err), nil, nil @@ -393,7 +419,7 @@ func GetNotificationDetails(t translations.TranslationHelperFunc) inventory.Serv // delivered to a specific recipient and may reference private // repositories, so confidentiality is private. result = attachStaticIFCLabel(ctx, deps, result, ifc.LabelNotificationDetails()) - return result, nil, nil + return result, notificationOutput(thread), nil }, ) } @@ -407,15 +433,16 @@ const ( // ManageNotificationSubscription creates a tool to manage a notification subscription (ignore, watch, delete) func ManageNotificationSubscription(t translations.TranslationHelperFunc) inventory.ServerTool { - return NewTool( + return NewTool[ManageNotificationSubscriptionInput, *NotificationSubscriptionResult]( ToolsetMetadataNotifications, mcp.Tool{ - Name: "manage_notification_subscription", - Description: t("TOOL_MANAGE_NOTIFICATION_SUBSCRIPTION_DESCRIPTION", "Manage a notification subscription: ignore, watch, or delete a notification thread subscription."), + Name: "manage_notification_subscription", + OutputSchema: notificationSubscriptionResultSchema(), + Description: t("TOOL_MANAGE_NOTIFICATION_SUBSCRIPTION_DESCRIPTION", "Manage a notification subscription: ignore, watch, or delete a notification thread subscription."), Annotations: &mcp.ToolAnnotations{ Title: t("TOOL_MANAGE_NOTIFICATION_SUBSCRIPTION_USER_TITLE", "Manage notification subscription"), ReadOnlyHint: false, - DestructiveHint: jsonschema.Ptr(true), + DestructiveHint: new(true), }, InputSchema: &jsonschema.Schema{ Type: "object", @@ -434,7 +461,11 @@ func ManageNotificationSubscription(t translations.TranslationHelperFunc) invent }, }, scopes.RequireAll(scopes.Notifications), - func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, args map[string]any) (*mcp.CallToolResult, any, error) { + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, input ManageNotificationSubscriptionInput) (*mcp.CallToolResult, *NotificationSubscriptionResult, error) { + args, err := discussionNotificationArguments(input) + if err != nil { + return nil, nil, err + } client, err := deps.GetClient(ctx) if err != nil { return utils.NewToolResultErrorFromErr("failed to get GitHub client", err), nil, nil @@ -451,7 +482,7 @@ func ManageNotificationSubscription(t translations.TranslationHelperFunc) invent var ( resp *github.Response - result any + result *github.Subscription apiErr error ) @@ -484,14 +515,15 @@ func ManageNotificationSubscription(t translations.TranslationHelperFunc) invent if action == NotificationActionDelete { // Special case for delete as there is no response body - return utils.NewToolResultText("Notification subscription deleted"), nil, nil + inventory.PreserveToolHandlerContent(ctx) + return utils.NewToolResultText("Notification subscription deleted"), &NotificationSubscriptionResult{Message: "Notification subscription deleted"}, nil } r, err := json.Marshal(result) if err != nil { return utils.NewToolResultErrorFromErr("failed to marshal response", err), nil, nil } - return utils.NewToolResultText(string(r)), nil, nil + return utils.NewToolResultText(string(r)), notificationSubscriptionOutput(result), nil }, ) } @@ -504,15 +536,16 @@ const ( // ManageRepositoryNotificationSubscription creates a tool to manage a repository notification subscription (ignore, watch, delete) func ManageRepositoryNotificationSubscription(t translations.TranslationHelperFunc) inventory.ServerTool { - return NewTool( + return NewTool[ManageRepositoryNotificationSubscriptionInput, *NotificationSubscriptionResult]( ToolsetMetadataNotifications, mcp.Tool{ - Name: "manage_repository_notification_subscription", - Description: t("TOOL_MANAGE_REPOSITORY_NOTIFICATION_SUBSCRIPTION_DESCRIPTION", "Manage a repository notification subscription: ignore, watch, or delete repository notifications subscription for the provided repository."), + Name: "manage_repository_notification_subscription", + OutputSchema: notificationSubscriptionResultSchema(), + Description: t("TOOL_MANAGE_REPOSITORY_NOTIFICATION_SUBSCRIPTION_DESCRIPTION", "Manage a repository notification subscription: ignore, watch, or delete repository notifications subscription for the provided repository."), Annotations: &mcp.ToolAnnotations{ Title: t("TOOL_MANAGE_REPOSITORY_NOTIFICATION_SUBSCRIPTION_USER_TITLE", "Manage repository notification subscription"), ReadOnlyHint: false, - DestructiveHint: jsonschema.Ptr(true), + DestructiveHint: new(true), }, InputSchema: &jsonschema.Schema{ Type: "object", @@ -535,7 +568,11 @@ func ManageRepositoryNotificationSubscription(t translations.TranslationHelperFu }, }, scopes.RequireAll(scopes.Notifications), - func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, args map[string]any) (*mcp.CallToolResult, any, error) { + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, input ManageRepositoryNotificationSubscriptionInput) (*mcp.CallToolResult, *NotificationSubscriptionResult, error) { + args, err := discussionNotificationArguments(input) + if err != nil { + return nil, nil, err + } client, err := deps.GetClient(ctx) if err != nil { return utils.NewToolResultErrorFromErr("failed to get GitHub client", err), nil, nil @@ -556,7 +593,7 @@ func ManageRepositoryNotificationSubscription(t translations.TranslationHelperFu var ( resp *github.Response - result any + result *github.Subscription apiErr error ) @@ -592,14 +629,15 @@ func ManageRepositoryNotificationSubscription(t translations.TranslationHelperFu if action == RepositorySubscriptionActionDelete { // Special case for delete as there is no response body - return utils.NewToolResultText("Repository subscription deleted"), nil, nil + inventory.PreserveToolHandlerContent(ctx) + return utils.NewToolResultText("Repository subscription deleted"), &NotificationSubscriptionResult{Message: "Repository subscription deleted"}, nil } r, err := json.Marshal(result) if err != nil { return utils.NewToolResultErrorFromErr("failed to marshal response", err), nil, nil } - return utils.NewToolResultText(string(r)), nil, nil + return utils.NewToolResultText(string(r)), notificationSubscriptionOutput(result), nil }, ) } diff --git a/pkg/github/notifications_test.go b/pkg/github/notifications_test.go index f2cbaff9f4..0fb37eebc8 100644 --- a/pkg/github/notifications_test.go +++ b/pkg/github/notifications_test.go @@ -6,9 +6,9 @@ import ( "net/http" "testing" - "github.com/github/github-mcp-server/internal/toolsnaps" - "github.com/github/github-mcp-server/pkg/translations" - "github.com/google/go-github/v89/github" + "github.com/github/github-mcp-server/v2/internal/toolsnaps" + "github.com/github/github-mcp-server/v2/pkg/translations" + "github.com/google/go-github/v92/github" "github.com/google/jsonschema-go/jsonschema" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -35,8 +35,8 @@ func Test_ListNotifications(t *testing.T) { // All fields are optional, so Required should be empty assert.Empty(t, schema.Required) mockNotification := &github.Notification{ - ID: github.Ptr("123"), - Reason: github.Ptr("mention"), + ID: new("123"), + Reason: new("mention"), } tests := []struct { @@ -156,8 +156,8 @@ func Test_ManageNotificationSubscription(t *testing.T) { assert.Contains(t, schema.Properties, "action") assert.Equal(t, []string{"notificationID", "action"}, schema.Required) - mockSub := &github.Subscription{Ignored: github.Ptr(true)} - mockSubWatch := &github.Subscription{Ignored: github.Ptr(false), Subscribed: github.Ptr(true)} + mockSub := &github.Subscription{Ignored: new(true)} + mockSubWatch := &github.Subscription{Ignored: new(false), Subscribed: new(true)} tests := []struct { name string @@ -179,7 +179,7 @@ func Test_ManageNotificationSubscription(t *testing.T) { "action": "ignore", }, expectError: false, - expectIgnored: github.Ptr(true), + expectIgnored: new(true), }, { name: "watch subscription", @@ -191,7 +191,7 @@ func Test_ManageNotificationSubscription(t *testing.T) { "action": "watch", }, expectError: false, - expectIgnored: github.Ptr(false), + expectIgnored: new(false), }, { name: "delete subscription", @@ -296,8 +296,8 @@ func Test_ManageRepositoryNotificationSubscription(t *testing.T) { assert.Contains(t, schema.Properties, "action") assert.Equal(t, []string{"owner", "repo", "action"}, schema.Required) - mockSub := &github.Subscription{Ignored: github.Ptr(true)} - mockWatchSub := &github.Subscription{Ignored: github.Ptr(false), Subscribed: github.Ptr(true)} + mockSub := &github.Subscription{Ignored: new(true)} + mockWatchSub := &github.Subscription{Ignored: new(false), Subscribed: new(true)} tests := []struct { name string @@ -321,7 +321,7 @@ func Test_ManageRepositoryNotificationSubscription(t *testing.T) { "action": "ignore", }, expectError: false, - expectIgnored: github.Ptr(true), + expectIgnored: new(true), }, { name: "watch subscription", @@ -334,8 +334,8 @@ func Test_ManageRepositoryNotificationSubscription(t *testing.T) { "action": "watch", }, expectError: false, - expectIgnored: github.Ptr(false), - expectSubscribed: github.Ptr(true), + expectIgnored: new(false), + expectSubscribed: new(true), }, { name: "delete subscription", @@ -679,7 +679,7 @@ func Test_GetNotificationDetails(t *testing.T) { assert.Contains(t, schema.Properties, "notificationID") assert.Equal(t, []string{"notificationID"}, schema.Required) - mockThread := &github.Notification{ID: github.Ptr("123"), Reason: github.Ptr("mention")} + mockThread := &github.Notification{ID: new("123"), Reason: new("mention")} tests := []struct { name string diff --git a/pkg/github/params.go b/pkg/github/params.go index a03a6a1581..9e1b582714 100644 --- a/pkg/github/params.go +++ b/pkg/github/params.go @@ -6,7 +6,7 @@ import ( "math" "strconv" - "github.com/google/go-github/v89/github" + "github.com/google/go-github/v92/github" "github.com/google/jsonschema-go/jsonschema" ) @@ -60,6 +60,11 @@ func isAcceptedError(err error) bool { return errors.As(err, &acceptedError) } +func inSignedIntRange(f float64, bitSize int) bool { + limit := math.Ldexp(1, bitSize-1) + return f >= -limit && f < limit +} + // toInt converts a value to int, handling both float64 and string representations. // Some MCP clients send numeric values as strings. It rejects NaN, ±Inf, // fractional values, and values outside the int range. @@ -83,7 +88,7 @@ func toInt(val any) (int, error) { if f != math.Trunc(f) { return 0, fmt.Errorf("non-integer numeric value: %v", f) } - if f > math.MaxInt || f < math.MinInt { + if !inSignedIntRange(f, strconv.IntSize) { return 0, fmt.Errorf("numeric value out of int range: %v", f) } return int(f), nil @@ -91,7 +96,7 @@ func toInt(val any) (int, error) { // toInt64 converts a value to int64, handling both float64 and string representations. // Some MCP clients send numeric values as strings. It rejects NaN, ±Inf, -// fractional values, and values that lose precision in the float64→int64 conversion. +// fractional values, and values outside the int64 range. func toInt64(val any) (int64, error) { var f float64 switch v := val.(type) { @@ -112,12 +117,10 @@ func toInt64(val any) (int64, error) { if f != math.Trunc(f) { return 0, fmt.Errorf("non-integer numeric value: %v", f) } - result := int64(f) - // Check round-trip to detect precision loss for large int64 values - if float64(result) != f { + if !inSignedIntRange(f, 64) { return 0, fmt.Errorf("numeric value %v is too large to fit in int64", f) } - return result, nil + return int64(f), nil } // RequiredParam is a helper function that can be used to fetch a requested parameter from the request. @@ -348,14 +351,14 @@ func WithPagination(schema *jsonschema.Schema) *jsonschema.Schema { schema.Properties["page"] = &jsonschema.Schema{ Type: "number", Description: "Page number for pagination (min 1)", - Minimum: jsonschema.Ptr(1.0), + Minimum: new(1.0), } schema.Properties["perPage"] = &jsonschema.Schema{ Type: "number", Description: "Results per page for pagination (min 1, max 100)", - Minimum: jsonschema.Ptr(1.0), - Maximum: jsonschema.Ptr(100.0), + Minimum: new(1.0), + Maximum: new(100.0), } return schema @@ -367,14 +370,14 @@ func WithUnifiedPagination(schema *jsonschema.Schema) *jsonschema.Schema { schema.Properties["page"] = &jsonschema.Schema{ Type: "number", Description: "Page number for pagination (min 1)", - Minimum: jsonschema.Ptr(1.0), + Minimum: new(1.0), } schema.Properties["perPage"] = &jsonschema.Schema{ Type: "number", Description: "Results per page for pagination (min 1, max 100)", - Minimum: jsonschema.Ptr(1.0), - Maximum: jsonschema.Ptr(100.0), + Minimum: new(1.0), + Maximum: new(100.0), } schema.Properties["after"] = &jsonschema.Schema{ @@ -390,8 +393,8 @@ func WithCursorPagination(schema *jsonschema.Schema) *jsonschema.Schema { schema.Properties["perPage"] = &jsonschema.Schema{ Type: "number", Description: "Results per page for pagination (min 1, max 100)", - Minimum: jsonschema.Ptr(1.0), - Maximum: jsonschema.Ptr(100.0), + Minimum: new(1.0), + Maximum: new(100.0), } schema.Properties["after"] = &jsonschema.Schema{ diff --git a/pkg/github/params_test.go b/pkg/github/params_test.go index 55a5526f77..3527e910a6 100644 --- a/pkg/github/params_test.go +++ b/pkg/github/params_test.go @@ -5,7 +5,7 @@ import ( "math" "testing" - "github.com/google/go-github/v89/github" + "github.com/google/go-github/v92/github" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -184,6 +184,65 @@ func TestOptionalNullableStringParam(t *testing.T) { } } +func Test_inSignedIntRange(t *testing.T) { + tests := []struct { + name string + value float64 + bitSize int + want bool + }{ + {"int64 min", math.MinInt64, 64, true}, + {"largest float64 below 2^63", math.Nextafter(math.Ldexp(1, 63), 0), 64, true}, + {"2^63", math.Ldexp(1, 63), 64, false}, + {"MaxInt64 rounds up to 2^63", float64(math.MaxInt64), 64, false}, + {"below int64 min", math.Nextafter(math.MinInt64, math.Inf(-1)), 64, false}, + {"int32 max", math.MaxInt32, 32, true}, + {"2^31", math.MaxInt32 + 1, 32, false}, + {"int32 min", math.MinInt32, 32, true}, + {"below int32 min", math.MinInt32 - 1, 32, false}, + {"NaN", math.NaN(), 64, false}, + {"positive infinity", math.Inf(1), 64, false}, + {"negative infinity", math.Inf(-1), 64, false}, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + assert.Equal(t, tc.want, inSignedIntRange(tc.value, tc.bitSize)) + }) + } +} + +func Test_RequiredBigInt(t *testing.T) { + tests := []struct { + name string + value any + expected int64 + expectedErr string + }{ + {"valid number", float64(42), 42, ""}, + {"valid string", "42", 42, ""}, + {"MinInt64 string", "-9223372036854775808", math.MinInt64, ""}, + {"largest float64 below 2^63", math.Nextafter(math.Ldexp(1, 63), 0), 9223372036854774784, ""}, + {"2^63 string", "9223372036854775808", 0, "too large to fit in int64"}, + {"MaxInt64 string rounds up to 2^63", "9223372036854775807", 0, "too large to fit in int64"}, + {"2^63 float64", math.Ldexp(1, 63), 0, "too large to fit in int64"}, + {"below MinInt64", "-9223372036854777856", 0, "too large to fit in int64"}, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + result, err := RequiredBigInt(map[string]any{"id": tc.value}, "id") + + if tc.expectedErr != "" { + assert.ErrorContains(t, err, tc.expectedErr) + return + } + require.NoError(t, err) + assert.Equal(t, tc.expected, result) + }) + } +} + func Test_RequiredInt(t *testing.T) { tests := []struct { name string @@ -376,6 +435,34 @@ func Test_OptionalIntParam(t *testing.T) { expected: 0, expectError: true, }, + { + name: "2^63 string parameter", + params: map[string]any{"count": "9223372036854775808"}, + paramName: "count", + expected: 0, + expectError: true, + }, + { + name: "MaxInt64 string parameter rounds up to 2^63", + params: map[string]any{"count": "9223372036854775807"}, + paramName: "count", + expected: 0, + expectError: true, + }, + { + name: "2^63 float64 parameter", + params: map[string]any{"count": math.Ldexp(1, 63)}, + paramName: "count", + expected: 0, + expectError: true, + }, + { + name: "MinInt float64 parameter", + params: map[string]any{"count": float64(math.MinInt)}, + paramName: "count", + expected: math.MinInt, + expectError: false, + }, } for _, tc := range tests { diff --git a/pkg/github/projects.go b/pkg/github/projects.go index 28e15d3bd1..e55b2a29d6 100644 --- a/pkg/github/projects.go +++ b/pkg/github/projects.go @@ -11,15 +11,15 @@ import ( "strings" "time" - ghcontext "github.com/github/github-mcp-server/pkg/context" - ghErrors "github.com/github/github-mcp-server/pkg/errors" - "github.com/github/github-mcp-server/pkg/ifc" - "github.com/github/github-mcp-server/pkg/inventory" - "github.com/github/github-mcp-server/pkg/sanitize" - "github.com/github/github-mcp-server/pkg/scopes" - "github.com/github/github-mcp-server/pkg/translations" - "github.com/github/github-mcp-server/pkg/utils" - "github.com/google/go-github/v89/github" + ghcontext "github.com/github/github-mcp-server/v2/pkg/context" + ghErrors "github.com/github/github-mcp-server/v2/pkg/errors" + "github.com/github/github-mcp-server/v2/pkg/ifc" + "github.com/github/github-mcp-server/v2/pkg/inventory" + "github.com/github/github-mcp-server/v2/pkg/sanitize" + "github.com/github/github-mcp-server/v2/pkg/scopes" + "github.com/github/github-mcp-server/v2/pkg/translations" + "github.com/github/github-mcp-server/v2/pkg/utils" + "github.com/google/go-github/v92/github" "github.com/google/jsonschema-go/jsonschema" "github.com/modelcontextprotocol/go-sdk/mcp" "github.com/shurcooL/githubv4" @@ -284,10 +284,11 @@ func derefString(s *githubv4.String) string { // ProjectsList returns the tool and handler for listing GitHub Projects resources. func ProjectsList(t translations.TranslationHelperFunc) inventory.ServerTool { - tool := NewTool( + tool := NewToolWithSchemaOptions[ProjectsListInput, *ProjectsListOutput]( ToolsetMetadataProjects, mcp.Tool{ - Name: "projects_list", + Name: "projects_list", + OutputSchema: projectsListOutputSchema(), Description: t("TOOL_PROJECTS_LIST_DESCRIPTION", `Tools for listing GitHub Projects resources. Use this tool to list projects for a user or organization, or list project fields, items, views, and status updates for a specific project. @@ -358,7 +359,8 @@ Use this tool to list projects for a user or organization, or list project field }, }, scopes.RequireAll(scopes.ReadProject), - func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, args map[string]any) (*mcp.CallToolResult, any, error) { + projectsSchemaOptions(), + projectsTypedHandler[ProjectsListInput](func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, args map[string]any) (*mcp.CallToolResult, any, error) { method, err := RequiredParam[string](args, "method") if err != nil { return utils.NewToolResultError(err.Error()), nil, nil @@ -442,17 +444,19 @@ Use this tool to list projects for a user or organization, or list project field default: return utils.NewToolResultError(fmt.Sprintf("unknown method: %s", method)), nil, nil } - }, + }, decodeProjectsListOutput), + normalizeProjectsRouting("list"), ) return tool } // ProjectsGet returns the tool and handler for getting GitHub Projects resources. func ProjectsGet(t translations.TranslationHelperFunc) inventory.ServerTool { - tool := NewTool( + tool := NewToolWithSchemaOptions[ProjectsGetInput, *ProjectsGetOutput]( ToolsetMetadataProjects, mcp.Tool{ - Name: "projects_get", + Name: "projects_get", + OutputSchema: projectsGetOutputSchema(), Description: t("TOOL_PROJECTS_GET_DESCRIPTION", `Get details about specific GitHub Projects resources. Use this tool to get details about individual projects, project fields, project items, and project views by their unique IDs. `), @@ -522,7 +526,8 @@ Use this tool to get details about individual projects, project fields, project }, }, scopes.RequireAll(scopes.ReadProject), - func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, args map[string]any) (*mcp.CallToolResult, any, error) { + projectsSchemaOptions(), + projectsTypedHandler[ProjectsGetInput](func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, args map[string]any) (*mcp.CallToolResult, any, error) { method, err := RequiredParam[string](args, "method") if err != nil { return utils.NewToolResultError(err.Error()), nil, nil @@ -625,8 +630,7 @@ Use this tool to get details about individual projects, project fields, project } resolvedIDs, resolveErr := resolveFieldNamesToIDs(ctx, gqlClient, owner, ownerType, projectNumber, fieldNames, "fields") if resolveErr != nil { - var structured *ghErrors.StructuredResolutionError - if errors.As(resolveErr, &structured) { + if structured, ok := errors.AsType[*ghErrors.StructuredResolutionError](resolveErr); ok { return ghErrors.NewStructuredResolutionErrorResponse(structured), nil, nil } return utils.NewToolResultError(resolveErr.Error()), nil, nil @@ -644,7 +648,8 @@ Use this tool to get details about individual projects, project fields, project default: return utils.NewToolResultError(fmt.Sprintf("unknown method: %s", method)), nil, nil } - }, + }, decodeProjectsGetOutput), + normalizeProjectsRouting("get"), ) return tool } @@ -693,11 +698,10 @@ func updateProjectItemsItemSchema() *jsonschema.Schema { } func projectUpdatedFieldSchema() *jsonschema.Schema { - value := &jsonschema.Schema{ - Description: "The value to apply. Any JSON value is accepted; use null to clear the field.", - } variant := func(required []string, properties map[string]*jsonschema.Schema) *jsonschema.Schema { - properties["value"] = value + properties["value"] = &jsonschema.Schema{ + Description: "The value to apply. Any JSON value is accepted; use null to clear the field.", + } return &jsonschema.Schema{ Type: "object", AdditionalProperties: &jsonschema.Schema{Not: &jsonschema.Schema{}}, @@ -728,15 +732,16 @@ func projectUpdatedFieldSchema() *jsonschema.Schema { // ProjectsWrite returns the tool and handler for modifying GitHub Projects resources. func ProjectsWrite(t translations.TranslationHelperFunc) inventory.ServerTool { - tool := NewTool( + tool := NewToolWithSchemaOptions[ProjectsWriteInput, *ProjectsWriteOutput]( ToolsetMetadataProjects, mcp.Tool{ - Name: "projects_write", - Description: t("TOOL_PROJECTS_WRITE_DESCRIPTION", "Create and manage GitHub Projects: create projects, add/update/delete items, bulk-update many items at once, manage views, create status updates, and add iteration fields."), + Name: "projects_write", + OutputSchema: projectsWriteOutputSchema(), + Description: t("TOOL_PROJECTS_WRITE_DESCRIPTION", "Create and manage GitHub Projects: create projects, add/update/delete items, bulk-update many items at once, manage views, create status updates, and add iteration fields."), Annotations: &mcp.ToolAnnotations{ Title: t("TOOL_PROJECTS_WRITE_USER_TITLE", "Manage GitHub Projects"), ReadOnlyHint: false, - DestructiveHint: jsonschema.Ptr(true), + DestructiveHint: new(true), }, InputSchema: &jsonschema.Schema{ Type: "object", @@ -892,7 +897,8 @@ func ProjectsWrite(t translations.TranslationHelperFunc) inventory.ServerTool { }, }, scopes.RequireAll(scopes.Project), - func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, args map[string]any) (*mcp.CallToolResult, any, error) { + projectsSchemaOptions(), + projectsTypedHandler[ProjectsWriteInput](func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, args map[string]any) (*mcp.CallToolResult, any, error) { method, err := RequiredParam[string](args, "method") if err != nil { return utils.NewToolResultError(err.Error()), nil, nil @@ -984,8 +990,7 @@ func ProjectsWrite(t translations.TranslationHelperFunc) inventory.ServerTool { // Resolve the item by (item_owner, item_repo, issue_number). resolvedItemID, resolveErr := resolveItemIDFromIssueArgs(ctx, gqlClient, owner, ownerType, projectNumber, args) if resolveErr != nil { - var structured *ghErrors.StructuredResolutionError - if errors.As(resolveErr, &structured) { + if structured, ok := errors.AsType[*ghErrors.StructuredResolutionError](resolveErr); ok { return ghErrors.NewStructuredResolutionErrorResponse(structured), nil, nil } return utils.NewToolResultError(resolveErr.Error()), nil, nil @@ -1039,7 +1044,8 @@ func ProjectsWrite(t translations.TranslationHelperFunc) inventory.ServerTool { default: return utils.NewToolResultError(fmt.Sprintf("unknown method: %s", method)), nil, nil } - }, + }, decodeProjectsWriteOutput), + normalizeProjectsRouting("write"), ) return tool } @@ -1252,8 +1258,7 @@ func listProjectItems(ctx context.Context, client *github.Client, gqlClient *git if len(fieldNames) > 0 { resolvedIDs, resolveErr := resolveFieldNamesToIDs(ctx, gqlClient, owner, ownerType, projectNumber, fieldNames, "fields") if resolveErr != nil { - var structured *ghErrors.StructuredResolutionError - if errors.As(resolveErr, &structured) { + if structured, ok := errors.AsType[*ghErrors.StructuredResolutionError](resolveErr); ok { return ghErrors.NewStructuredResolutionErrorResponse(structured), nil, nil } return utils.NewToolResultError(resolveErr.Error()), nil, nil @@ -1270,11 +1275,9 @@ func listProjectItems(ctx context.Context, client *github.Client, gqlClient *git var projectItems []*github.ProjectV2Item opts := &github.ListProjectItemsOptions{ - Fields: fields, - ListProjectsOptions: github.ListProjectsOptions{ - ListProjectsPaginationOptions: pagination, - Query: queryStr, - }, + Fields: fields, + ListProjectsPaginationOptions: pagination, + Query: queryStr, } if ownerType == "org" { @@ -1446,8 +1449,7 @@ func fetchProjectItem(ctx context.Context, client *github.Client, owner, ownerTy func updateProjectItem(ctx context.Context, client *github.Client, gqlClient *githubv4.Client, owner, ownerType string, projectNumber int, itemID int64, fieldValue map[string]any) (*mcp.CallToolResult, any, error) { updatePayload, issueField, err := buildUpdateProjectItem(ctx, gqlClient, owner, ownerType, projectNumber, fieldValue) if err != nil { - var structured *ghErrors.StructuredResolutionError - if errors.As(err, &structured) { + if structured, ok := errors.AsType[*ghErrors.StructuredResolutionError](err); ok { return ghErrors.NewStructuredResolutionErrorResponse(structured), nil, nil } return utils.NewToolResultError(err.Error()), nil, nil @@ -1469,8 +1471,7 @@ func updateProjectItem(ctx context.Context, client *github.Client, gqlClient *gi issueID, resolveErr := projectItemIssueID(projectItem) if resolveErr != nil { - var structured *ghErrors.StructuredResolutionError - if errors.As(resolveErr, &structured) { + if structured, ok := errors.AsType[*ghErrors.StructuredResolutionError](resolveErr); ok { return ghErrors.NewStructuredResolutionErrorResponse(structured), nil, nil } return utils.NewToolResultError(resolveErr.Error()), nil, nil @@ -2136,8 +2137,7 @@ func createProjectView(ctx context.Context, gqlClient *githubv4.Client, args map } configuration, err := projectViewVisibleFieldsInput(ctx, gqlClient, args, owner, ownerType, projectNumber) if err != nil { - var structured *ghErrors.StructuredResolutionError - if errors.As(err, &structured) { + if structured, ok := errors.AsType[*ghErrors.StructuredResolutionError](err); ok { return ghErrors.NewStructuredResolutionErrorResponse(structured), nil, nil } return utils.NewToolResultError(err.Error()), nil, nil @@ -2267,8 +2267,7 @@ func updateProjectView(ctx context.Context, gqlClient *githubv4.Client, args map configuration, err := projectViewVisibleFieldsInput(ctx, gqlClient, args, owner, ownerType, projectNumber) if err != nil { - var structured *ghErrors.StructuredResolutionError - if errors.As(err, &structured) { + if structured, ok := errors.AsType[*ghErrors.StructuredResolutionError](err); ok { return ghErrors.NewStructuredResolutionErrorResponse(structured), nil, nil } return utils.NewToolResultError(err.Error()), nil, nil diff --git a/pkg/github/projects_batch.go b/pkg/github/projects_batch.go index 28493a4bf2..cf464f2870 100644 --- a/pkg/github/projects_batch.go +++ b/pkg/github/projects_batch.go @@ -9,9 +9,9 @@ import ( "sync" "time" - ghErrors "github.com/github/github-mcp-server/pkg/errors" - "github.com/github/github-mcp-server/pkg/utils" - "github.com/google/go-github/v89/github" + ghErrors "github.com/github/github-mcp-server/v2/pkg/errors" + "github.com/github/github-mcp-server/v2/pkg/utils" + "github.com/google/go-github/v92/github" "github.com/modelcontextprotocol/go-sdk/mcp" "github.com/shurcooL/githubv4" ) @@ -182,8 +182,7 @@ func updateProjectItemsBatch(ctx context.Context, client *github.Client, gqlClie } func batchTopLevelError(err error) *mcp.CallToolResult { - var structured *ghErrors.StructuredResolutionError - if errors.As(err, &structured) { + if structured, ok := errors.AsType[*ghErrors.StructuredResolutionError](err); ok { return ghErrors.NewStructuredResolutionErrorResponse(structured) } return utils.NewToolResultError(err.Error()) @@ -796,8 +795,7 @@ func resolveIssueRefs(ctx context.Context, gqlClient *githubv4.Client, projectID } func batchErrorFromResolution(err error) *batchItemError { - var structured *ghErrors.StructuredResolutionError - if errors.As(err, &structured) { + if structured, ok := errors.AsType[*ghErrors.StructuredResolutionError](err); ok { return &batchItemError{ Code: structured.Kind, Message: fmt.Sprintf("%s: %s", structured.Kind, structured.Name), diff --git a/pkg/github/projects_batch_mutation.go b/pkg/github/projects_batch_mutation.go index 0c478aabf9..13913e53bf 100644 --- a/pkg/github/projects_batch_mutation.go +++ b/pkg/github/projects_batch_mutation.go @@ -105,7 +105,7 @@ func executeAliasedMutation(ctx context.Context, gqlClient *githubv4.Client, kin outcomes := make([]mutationAliasOutcome, len(inputs)) elem := mutationPtr.Elem() for i := range inputs { - result, ok := elem.Field(i).Interface().(projectV2ItemMutationResult) + result, ok := reflect.TypeAssert[projectV2ItemMutationResult](elem.Field(i)) if !ok || result.ProjectV2Item.ID == "" { continue } diff --git a/pkg/github/projects_batch_test.go b/pkg/github/projects_batch_test.go index 985cd5bfc7..32b7522a31 100644 --- a/pkg/github/projects_batch_test.go +++ b/pkg/github/projects_batch_test.go @@ -14,10 +14,10 @@ import ( "testing" "time" - "github.com/github/github-mcp-server/internal/githubv4mock" - 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/v2/internal/githubv4mock" + ghErrors "github.com/github/github-mcp-server/v2/pkg/errors" + "github.com/github/github-mcp-server/v2/pkg/inventory" + "github.com/github/github-mcp-server/v2/pkg/translations" "github.com/shurcooL/githubv4" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -396,10 +396,10 @@ func Test_ProjectsWrite_UpdateProjectItems_NumericItemIDDeduplicatesRESTLookup(t } gqlClient := newTestGQLClient(transport) - var restCalls int32 + var restCalls atomic.Int32 restClient := mustNewGHClient(t, MockHTTPClientWithHandlers(map[string]http.HandlerFunc{ GetOrgsProjectsV2ItemsByProjectByItemID: func(w http.ResponseWriter, _ *http.Request) { - atomic.AddInt32(&restCalls, 1) + restCalls.Add(1) w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) _, _ = w.Write([]byte(`{"id":1001,"node_id":"PVTI_item1001"}`)) @@ -427,7 +427,7 @@ func Test_ProjectsWrite_UpdateProjectItems_NumericItemIDDeduplicatesRESTLookup(t require.NoError(t, json.Unmarshal([]byte(getTextResult(t, result).Text), &response)) assert.Equal(t, float64(1), response["succeeded"]) assert.Equal(t, float64(1), response["failed"]) - assert.Equal(t, int32(1), atomic.LoadInt32(&restCalls), "the same numeric item_id must only be resolved once") + assert.Equal(t, int32(1), restCalls.Load(), "the same numeric item_id must only be resolved once") results := response["results"].([]any) assert.Equal(t, "duplicate_target", results[1].(map[string]any)["error"].(map[string]any)["code"]) } @@ -581,10 +581,10 @@ func Test_ProjectsWrite_UpdateProjectItems_DuplicateTargetRejected(t *testing.T) }, } gqlClient := newTestGQLClient(transport) - var restCalls int32 + var restCalls atomic.Int32 restClient := mustNewGHClient(t, MockHTTPClientWithHandlers(map[string]http.HandlerFunc{ GetOrgsProjectsV2ItemsByProjectByItemID: func(w http.ResponseWriter, _ *http.Request) { - atomic.AddInt32(&restCalls, 1) + restCalls.Add(1) w.Header().Set("Content-Type", "application/json") _, _ = w.Write([]byte(`{"id":1001,"node_id":"PVTI_item1"}`)) }, @@ -616,7 +616,7 @@ func Test_ProjectsWrite_UpdateProjectItems_DuplicateTargetRejected(t *testing.T) second := results[1].(map[string]any) assert.Equal(t, "failed", second["status"]) assert.Equal(t, "duplicate_target", second["error"].(map[string]any)["code"]) - assert.Equal(t, int32(1), atomic.LoadInt32(&restCalls)) + assert.Equal(t, int32(1), restCalls.Load()) assert.Len(t, transport.mutationCalls, 1) } diff --git a/pkg/github/projects_resolver.go b/pkg/github/projects_resolver.go index 33e82d1de5..9716d36a93 100644 --- a/pkg/github/projects_resolver.go +++ b/pkg/github/projects_resolver.go @@ -6,8 +6,8 @@ import ( "strconv" "strings" - ghcontext "github.com/github/github-mcp-server/pkg/context" - ghErrors "github.com/github/github-mcp-server/pkg/errors" + ghcontext "github.com/github/github-mcp-server/v2/pkg/context" + ghErrors "github.com/github/github-mcp-server/v2/pkg/errors" "github.com/shurcooL/githubv4" ) @@ -606,7 +606,7 @@ func resolveFieldNamesToIDsFromFields(all []ResolvedField, names []string, owner for i, field := range resolved { id, parseErr := parseInt64(field.ID) if parseErr != nil { - return nil, fmt.Errorf("resolved field %q has non-numeric ID %q; pass it via '%s' instead", names[i], field.ID, idParameter) + return nil, fmt.Errorf("resolved field %q has non-numeric ID %q; pass it via '%s' instead", names[i], field.ID, idParameter) //nolint:gosec // G602: resolveFieldsByName returns exactly one field per name in order, or an error. } out = append(out, id) } diff --git a/pkg/github/projects_resolver_test.go b/pkg/github/projects_resolver_test.go index 459c6f1192..769572b411 100644 --- a/pkg/github/projects_resolver_test.go +++ b/pkg/github/projects_resolver_test.go @@ -6,10 +6,10 @@ import ( "net/http" "testing" - "github.com/github/github-mcp-server/internal/githubv4mock" - "github.com/github/github-mcp-server/pkg/http/headers" - transportpkg "github.com/github/github-mcp-server/pkg/http/transport" - "github.com/github/github-mcp-server/pkg/translations" + "github.com/github/github-mcp-server/v2/internal/githubv4mock" + "github.com/github/github-mcp-server/v2/pkg/http/headers" + transportpkg "github.com/github/github-mcp-server/v2/pkg/http/transport" + "github.com/github/github-mcp-server/v2/pkg/translations" "github.com/shurcooL/githubv4" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" diff --git a/pkg/github/projects_test.go b/pkg/github/projects_test.go index 8b40a569e0..9cbbdf26bf 100644 --- a/pkg/github/projects_test.go +++ b/pkg/github/projects_test.go @@ -6,14 +6,14 @@ import ( "net/http" "testing" - "github.com/github/github-mcp-server/internal/githubv4mock" - "github.com/github/github-mcp-server/internal/toolsnaps" - ghErrors "github.com/github/github-mcp-server/pkg/errors" - "github.com/github/github-mcp-server/pkg/http/headers" - transportpkg "github.com/github/github-mcp-server/pkg/http/transport" - "github.com/github/github-mcp-server/pkg/inventory" - "github.com/github/github-mcp-server/pkg/translations" - gogithub "github.com/google/go-github/v89/github" + "github.com/github/github-mcp-server/v2/internal/githubv4mock" + "github.com/github/github-mcp-server/v2/internal/toolsnaps" + ghErrors "github.com/github/github-mcp-server/v2/pkg/errors" + "github.com/github/github-mcp-server/v2/pkg/http/headers" + transportpkg "github.com/github/github-mcp-server/v2/pkg/http/transport" + "github.com/github/github-mcp-server/v2/pkg/inventory" + "github.com/github/github-mcp-server/v2/pkg/translations" + gogithub "github.com/google/go-github/v92/github" "github.com/google/jsonschema-go/jsonschema" "github.com/shurcooL/githubv4" "github.com/stretchr/testify/assert" @@ -37,7 +37,7 @@ func Test_ProjectsList(t *testing.T) { assert.Contains(t, inputSchema.Properties, "query") assert.Contains(t, inputSchema.Properties, "fields") assert.Contains(t, inputSchema.Properties["method"].Enum, projectsMethodListProjectViews) - assert.ElementsMatch(t, inputSchema.Required, []string{"method", "owner"}) + assert.ElementsMatch(t, []string{"method", "owner"}, inputSchema.Required) } func Test_ProjectsList_ListProjects(t *testing.T) { @@ -638,7 +638,7 @@ func Test_ProjectsGet(t *testing.T) { assert.Contains(t, inputSchema.Properties["method"].Enum, projectsMethodGetProjectView) assert.Contains(t, inputSchema.Properties, "field_id") assert.Contains(t, inputSchema.Properties, "item_id") - assert.ElementsMatch(t, inputSchema.Required, []string{"method"}) + assert.ElementsMatch(t, []string{"method"}, inputSchema.Required) } func Test_ProjectsGet_GetProject(t *testing.T) { @@ -934,7 +934,7 @@ func Test_ProjectsWrite(t *testing.T) { assert.Contains(t, inputSchema.Properties["method"].Enum, projectsMethodCreateProjectView) assert.Contains(t, inputSchema.Properties["method"].Enum, projectsMethodUpdateProjectView) assert.Contains(t, inputSchema.Properties["method"].Enum, projectsMethodDeleteProjectView) - assert.ElementsMatch(t, inputSchema.Required, []string{"method", "owner"}) + assert.ElementsMatch(t, []string{"method", "owner"}, inputSchema.Required) // Verify DestructiveHint is set assert.NotNil(t, toolDef.Tool.Annotations) @@ -1488,7 +1488,7 @@ func Test_BuildIssueFieldUpdate(t *testing.T) { func Test_ProjectItemIssueID_RejectsNonIssueItems(t *testing.T) { for _, contentType := range []string{"PullRequest", "DraftIssue"} { t.Run(contentType, func(t *testing.T) { - item := &gogithub.ProjectV2Item{ContentType: gogithub.Ptr(gogithub.ProjectV2ItemContentType(contentType))} + item := &gogithub.ProjectV2Item{ContentType: new(gogithub.ProjectV2ItemContentType(contentType))} _, err := projectItemIssueID(item) var structured *ghErrors.StructuredResolutionError require.ErrorAs(t, err, &structured) diff --git a/pkg/github/projects_types.go b/pkg/github/projects_types.go new file mode 100644 index 0000000000..746406ffca --- /dev/null +++ b/pkg/github/projects_types.go @@ -0,0 +1,617 @@ +package github + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "reflect" + + "github.com/github/github-mcp-server/v2/pkg/inventory" + "github.com/google/go-github/v92/github" + "github.com/google/jsonschema-go/jsonschema" + "github.com/modelcontextprotocol/go-sdk/mcp" +) + +// ProjectParameter retains the original JSON for the legacy method-specific +// validators. In particular, invalid or unused arguments must not fail before +// client acquisition, and numeric strings must retain their original coercion. +type ProjectParameter[T any] struct { + Value T + raw json.RawMessage +} + +func (p *ProjectParameter[T]) UnmarshalJSON(raw []byte) error { + p.raw = append(p.raw[:0], raw...) + // A value of the wrong type is reported by the selected method, not here. + var value T + if err := json.Unmarshal(raw, &value); err == nil { + p.Value = value + } + return nil +} + +func (p ProjectParameter[T]) MarshalJSON() ([]byte, error) { + if p.raw != nil { + return p.raw, nil + } + return json.Marshal(p.Value) +} + +type ProjectsListInput struct { + Method ProjectParameter[string] `json:"method"` + Owner ProjectParameter[string] `json:"owner"` + OwnerType ProjectParameter[string] `json:"owner_type"` + ProjectNumber ProjectParameter[int] `json:"project_number"` + Query ProjectParameter[string] `json:"query"` + Fields ProjectParameter[[]string] `json:"fields"` + FieldNames ProjectParameter[[]string] `json:"field_names"` + PerPage ProjectParameter[int] `json:"perPage"` + LegacyPerPage ProjectParameter[int] `json:"per_page"` + After ProjectParameter[string] `json:"after"` + Before ProjectParameter[string] `json:"before"` +} + +type ProjectsGetInput struct { + Method ProjectParameter[string] `json:"method"` + Owner ProjectParameter[string] `json:"owner"` + OwnerType ProjectParameter[string] `json:"owner_type"` + ProjectNumber ProjectParameter[int] `json:"project_number"` + FieldID ProjectParameter[int64] `json:"field_id"` + ItemID ProjectParameter[int64] `json:"item_id"` + Fields ProjectParameter[[]string] `json:"fields"` + FieldNames ProjectParameter[[]string] `json:"field_names"` + StatusUpdateID ProjectParameter[string] `json:"status_update_id"` + ViewID ProjectParameter[string] `json:"view_id"` +} + +type ProjectsWriteInput struct { + Method ProjectParameter[string] `json:"method"` + Owner ProjectParameter[string] `json:"owner"` + OwnerType ProjectParameter[string] `json:"owner_type"` + ProjectNumber ProjectParameter[int] `json:"project_number"` + Title ProjectParameter[string] `json:"title"` + ViewID ProjectParameter[string] `json:"view_id"` + Name ProjectParameter[string] `json:"name"` + Layout ProjectParameter[string] `json:"layout"` + Filter ProjectParameter[*string] `json:"filter"` + VisibleFields ProjectParameter[[]string] `json:"visible_fields"` + VisibleFieldNames ProjectParameter[[]string] `json:"visible_field_names"` + ItemID ProjectParameter[int64] `json:"item_id"` + ItemType ProjectParameter[string] `json:"item_type"` + ItemOwner ProjectParameter[string] `json:"item_owner"` + ItemRepo ProjectParameter[string] `json:"item_repo"` + IssueNumber ProjectParameter[int] `json:"issue_number"` + PullRequestNumber ProjectParameter[int] `json:"pull_request_number"` + UpdatedField ProjectParameter[ProjectUpdatedFieldInput] `json:"updated_field"` + Items ProjectParameter[[]ProjectItemReference] `json:"items"` + Body ProjectParameter[string] `json:"body"` + Status ProjectParameter[string] `json:"status"` + StartDate ProjectParameter[string] `json:"start_date"` + TargetDate ProjectParameter[string] `json:"target_date"` + FieldName ProjectParameter[string] `json:"field_name"` + IterationDuration ProjectParameter[int] `json:"iteration_duration"` + Iterations ProjectParameter[[]ProjectIterationInput] `json:"iterations"` +} + +func (input ProjectsListInput) MarshalJSON() ([]byte, error) { + return marshalProjectInput(input) +} + +func (input ProjectsGetInput) MarshalJSON() ([]byte, error) { + return marshalProjectInput(input) +} + +func (input ProjectsWriteInput) MarshalJSON() ([]byte, error) { + return marshalProjectInput(input) +} + +func marshalProjectInput(input any) ([]byte, error) { + args, err := projectArguments(input) + if err != nil { + return nil, err + } + return json.Marshal(args) +} + +func (input *ProjectsListInput) UnmarshalJSON(raw []byte) error { + return unmarshalProjectInput(raw, input) +} + +func (input *ProjectsGetInput) UnmarshalJSON(raw []byte) error { + return unmarshalProjectInput(raw, input) +} + +func (input *ProjectsWriteInput) UnmarshalJSON(raw []byte) error { + return unmarshalProjectInput(raw, input) +} + +// Legacy map handlers recognize only exact JSON keys; encoding/json's default +// case-insensitive struct matching must not turn ignored keys into write targets. +func unmarshalProjectInput(raw []byte, input any) error { + var args map[string]json.RawMessage + if err := json.Unmarshal(raw, &args); err != nil { + return err + } + value := reflect.ValueOf(input).Elem() + value.SetZero() + inputType := value.Type() + for i := range value.NumField() { + if argument, ok := args[inputType.Field(i).Tag.Get("json")]; ok { + if err := json.Unmarshal(argument, value.Field(i).Addr().Interface()); err != nil { + return err + } + } + } + return nil +} + +type ProjectUpdatedFieldInput struct { + ID *int64 `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Value json.RawMessage `json:"value"` +} + +type ProjectItemReference struct { + NodeID string `json:"node_id,omitempty"` + ItemID int64 `json:"item_id,omitempty"` + ItemOwner string `json:"item_owner,omitempty"` + ItemRepo string `json:"item_repo,omitempty"` + IssueNumber int `json:"issue_number,omitempty"` +} + +type ProjectIterationInput struct { + Title string `json:"title"` + StartDate string `json:"start_date"` + Duration float64 `json:"duration"` +} + +// The raw map is confined to the compatibility boundary with the existing +// validators and API helpers. Omitted parameters must stay omitted. +func projectArguments(input any) (map[string]any, error) { + value := reflect.ValueOf(input) + inputType := value.Type() + args := make(map[string]any, value.NumField()) + for i := range value.NumField() { + parameter := value.Field(i).Interface().(interface { + argumentJSON() (json.RawMessage, error) + }) + raw, err := parameter.argumentJSON() + if err != nil { + return nil, err + } + if raw == nil { + continue + } + var argument any + if err := json.Unmarshal(raw, &argument); err != nil { + return nil, err + } + args[inputType.Field(i).Tag.Get("json")] = argument + } + return args, nil +} + +func (p ProjectParameter[T]) argumentJSON() (json.RawMessage, error) { + if p.raw != nil { + return p.raw, nil + } + if reflect.ValueOf(&p.Value).Elem().IsZero() { + return nil, nil + } + return json.Marshal(p.Value) +} + +type ProjectsListOutput struct { + Method string `json:"method"` + Projects *ProjectListOutput `json:"projects,omitempty"` + Fields *ProjectFieldListOutput `json:"fields,omitempty"` + Items *ProjectItemListOutput `json:"items,omitempty"` + StatusUpdates *ProjectStatusUpdateListOutput `json:"status_updates,omitempty"` + Views *ProjectViewListOutput `json:"views,omitempty"` +} + +type ProjectListOutput struct { + Projects []MinimalProject `json:"projects"` + PageInfo *pageInfo `json:"pageInfo,omitempty"` + Note string `json:"note,omitempty"` +} + +type ProjectFieldListOutput struct { + Fields []ProjectFieldOutput `json:"fields"` + PageInfo pageInfo `json:"pageInfo"` +} + +// ProjectFieldOutput omits the derivable project API URL from REST fields. +type ProjectFieldOutput struct { + ID *int64 `json:"id,omitempty"` + NodeID *string `json:"node_id,omitempty"` + Name *string `json:"name,omitempty"` + DataType *string `json:"data_type,omitempty"` + Options []ProjectFieldOptionOutput `json:"options,omitempty"` + Configuration *ProjectFieldConfigurationOutput `json:"configuration,omitempty"` + CreatedAt *github.Timestamp `json:"created_at,omitempty"` + UpdatedAt *github.Timestamp `json:"updated_at,omitempty"` +} + +type ProjectFieldOptionOutput struct { + ID *string `json:"id,omitempty"` + Color *string `json:"color,omitempty"` + Description *ProjectFieldTextOutput `json:"description,omitempty"` + Name *ProjectFieldTextOutput `json:"name,omitempty"` +} + +type ProjectFieldTextOutput struct { + HTML *string `json:"html,omitempty"` + Raw *string `json:"raw,omitempty"` +} + +type ProjectFieldConfigurationOutput struct { + Duration *int `json:"duration,omitempty"` + StartDay *int `json:"start_day,omitempty"` + Iterations []ProjectFieldIterationOutput `json:"iterations,omitempty"` +} + +type ProjectFieldIterationOutput struct { + ID *string `json:"id,omitempty"` + Title *ProjectFieldTextOutput `json:"title,omitempty"` + StartDate *string `json:"start_date,omitempty"` + Duration *int `json:"duration,omitempty"` +} + +type ProjectItemListOutput struct { + Items []ProjectItemOutput `json:"items"` + PageInfo pageInfo `json:"pageInfo"` +} + +type ProjectStatusUpdateListOutput struct { + StatusUpdates []MinimalProjectStatusUpdate `json:"statusUpdates"` + PageInfo ProjectGraphQLPageInfo `json:"pageInfo"` +} + +type ProjectViewListOutput struct { + Views []MinimalProjectView `json:"views"` + PageInfo ProjectGraphQLPageInfo `json:"pageInfo"` +} + +type ProjectGraphQLPageInfo struct { + HasNextPage bool `json:"hasNextPage"` + HasPreviousPage bool `json:"hasPreviousPage"` + NextCursor string `json:"nextCursor"` + PrevCursor string `json:"prevCursor"` +} + +type ProjectsGetOutput struct { + Method string `json:"method"` + Project *MinimalProject `json:"project,omitempty"` + Field *ProjectFieldOutput `json:"field,omitempty"` + Item *ProjectItemOutput `json:"item,omitempty"` + StatusUpdate *MinimalProjectStatusUpdate `json:"status_update,omitempty"` + View *MinimalProjectView `json:"view,omitempty"` +} + +type ProjectItemOutput struct { + ID int64 `json:"id"` + NodeID string `json:"node_id,omitempty"` + ContentType string `json:"content_type,omitempty"` + Content *MinimalProjectItemContent `json:"content,omitempty"` + Fields []ProjectFieldValueOutput `json:"fields,omitempty"` + ArchivedAt string `json:"archived_at,omitempty"` + CreatedAt string `json:"created_at,omitempty"` + UpdatedAt string `json:"updated_at,omitempty"` + Creator string `json:"creator,omitempty"` +} + +type ProjectFieldValueOutput struct { + ID int64 `json:"id,omitempty"` + Name string `json:"name,omitempty"` + DataType string `json:"data_type,omitempty"` + // Unknown field types are recursively compacted by the legacy projection, + // including arbitrary object keys. A closed value union would lose data. + Value json.RawMessage `json:"value,omitempty"` +} + +type ProjectsWriteOutput struct { + Method string `json:"method"` + Added *ProjectAddedItemOutput `json:"added,omitempty"` + Item *ProjectItemOutput `json:"item,omitempty"` + IssueFields *ProjectIssueOutput `json:"issue_fields,omitempty"` + Batch *ProjectBatchOutput `json:"batch,omitempty"` + DeletedItem *RepositoryMessageOutput `json:"deleted_item,omitempty"` + StatusUpdate *MinimalProjectStatusUpdate `json:"status_update,omitempty"` + View *MinimalProjectView `json:"view,omitempty"` + DeletedView *ProjectDeletedViewOutput `json:"deleted_view,omitempty"` + Project *ProjectCreatedOutput `json:"project,omitempty"` + IterationField *ProjectIterationFieldOutput `json:"iteration_field,omitempty"` +} + +type ProjectIssueOutput struct { + ID string `json:"id"` + HTMLURL string `json:"html_url"` +} + +type ProjectAddedItemOutput struct { + ID *string `json:"id"` + Message string `json:"message"` + FullDatabaseID string `json:"full_database_id,omitempty"` + ItemID *int64 `json:"item_id,omitempty"` +} + +type ProjectDeletedViewOutput struct { + DeletedViewID string `json:"deleted_view_id"` +} + +type ProjectCreatedOutput struct { + ID string `json:"id"` + Number int `json:"number"` + Title string `json:"title"` + HTMLURL string `json:"html_url"` +} + +type ProjectIterationFieldOutput struct { + ID string `json:"id"` + Name string `json:"name"` + Configuration struct { + Iterations []ProjectIterationOutput `json:"iterations"` + } `json:"configuration"` +} + +type ProjectIterationOutput struct { + ID string `json:"id"` + Title string `json:"title"` + StartDate string `json:"start_date"` + Duration int `json:"duration"` +} + +type ProjectBatchOutput struct { + Total int `json:"total"` + Succeeded int `json:"succeeded"` + Failed int `json:"failed"` + Unknown int `json:"unknown"` + Results []ProjectBatchItemOutput `json:"results"` +} + +type ProjectBatchItemOutput struct { + Index int `json:"index"` + Status batchItemStatus `json:"status"` + Item *batchItemIdentity `json:"item,omitempty"` + Error *ProjectBatchError `json:"error,omitempty"` + // Batch entries echo user-supplied reference objects, including malformed + // references and extra keys, verbatim. + Ref json.RawMessage `json:"ref,omitempty"` +} + +type ProjectBatchError struct { + Code string `json:"code"` + Message string `json:"message"` + Candidates []ProjectResolutionCandidate `json:"candidates,omitempty"` + Hint string `json:"hint,omitempty"` +} + +type ProjectResolutionCandidate struct { + ID string `json:"id,omitempty"` + Name string `json:"name,omitempty"` + DataType string `json:"data_type,omitempty"` +} + +func projectsListOutputSchema() *jsonschema.Schema { + schema := projectOutputSchema[ProjectsListOutput]() + schema.Properties["method"].Enum = []any{projectsMethodListProjects, projectsMethodListProjectFields, projectsMethodListProjectItems, projectsMethodListProjectStatusUpdates, projectsMethodListProjectViews} + return schema +} + +func projectsGetOutputSchema() *jsonschema.Schema { + schema := projectOutputSchema[ProjectsGetOutput]() + schema.Properties["method"].Enum = []any{projectsMethodGetProject, projectsMethodGetProjectField, projectsMethodGetProjectItem, projectsMethodGetProjectStatusUpdate, projectsMethodGetProjectView} + return schema +} + +func projectsWriteOutputSchema() *jsonschema.Schema { + schema := projectOutputSchema[ProjectsWriteOutput]() + schema.Properties["method"].Enum = []any{projectsMethodAddProjectItem, projectsMethodUpdateProjectItem, projectsMethodUpdateProjectItems, projectsMethodDeleteProjectItem, projectsMethodCreateProjectStatusUpdate, projectsMethodCreateProjectView, projectsMethodUpdateProjectView, projectsMethodDeleteProjectView, projectsMethodCreateProject, projectsMethodCreateIterationField} + return schema +} + +func projectOutputSchema[T any]() *jsonschema.Schema { + user := repositoryOutputSchema[MinimalUser]() + delete(user.Properties, "details") + generated, err := inventory.CachedSchemaFor[T](&jsonschema.ForOptions{ + TypeSchemas: map[reflect.Type]*jsonschema.Schema{ + reflect.TypeFor[github.Timestamp](): {Type: "string", Format: "date-time"}, + reflect.TypeFor[MinimalUser](): user, + }, + }) + if err != nil { + panic(fmt.Sprintf("failed to generate project output schema: %v", err)) + } + schema := forbidOmittedNulls(inventory.CloneSchema(generated)) + var patch func(*jsonschema.Schema) + patch = func(schema *jsonschema.Schema) { + if schema == nil { + return + } + for name, property := range schema.Properties { + switch name { + case "value": + schema.Properties[name] = &jsonschema.Schema{Description: "Recursively compacted JSON field value; unknown field types retain arbitrary object keys."} + case "ref": + schema.Properties[name] = &jsonschema.Schema{Type: "object", Description: "Original batch reference, including malformed or extra fields.", AdditionalProperties: &jsonschema.Schema{}} + case "visible_fields": + property.Type, property.Types = "array", nil + patch(property) + case "created_at", "updated_at", "closed_at", "deleted_at", "archived_at": + property.Description = "RFC3339 timestamp." + case "start_date", "target_date": + property.Description = "Date in YYYY-MM-DD format." + case "duration": + property.Description = "Iteration duration in days." + case "layout": + property.Enum = []any{"board", "table", "roadmap"} + case "status": + if _, batch := schema.Properties["index"]; batch { + property.Enum = []any{"succeeded", "failed", "unknown"} + } else { + property.Enum = []any{"INACTIVE", "ON_TRACK", "AT_RISK", "OFF_TRACK", "COMPLETE"} + } + default: + patch(property) + } + } + patch(schema.Items) + for _, definition := range schema.Defs { + patch(definition) + } + } + patch(schema) + return schema +} + +func decodeProjectsListOutput(method string, raw []byte) (*ProjectsListOutput, error) { + out := &ProjectsListOutput{Method: method} + switch method { + case projectsMethodListProjects: + return out, json.Unmarshal(raw, &out.Projects) + case projectsMethodListProjectFields: + return out, json.Unmarshal(raw, &out.Fields) + case projectsMethodListProjectItems: + return out, json.Unmarshal(raw, &out.Items) + case projectsMethodListProjectStatusUpdates: + return out, json.Unmarshal(raw, &out.StatusUpdates) + case projectsMethodListProjectViews: + return out, json.Unmarshal(raw, &out.Views) + default: + return nil, fmt.Errorf("unexpected Projects list output method %q", method) + } +} + +func decodeProjectsGetOutput(method string, raw []byte) (*ProjectsGetOutput, error) { + out := &ProjectsGetOutput{Method: method} + switch method { + case projectsMethodGetProject: + return out, json.Unmarshal(raw, &out.Project) + case projectsMethodGetProjectField: + return out, json.Unmarshal(raw, &out.Field) + case projectsMethodGetProjectItem: + return out, json.Unmarshal(raw, &out.Item) + case projectsMethodGetProjectStatusUpdate: + return out, json.Unmarshal(raw, &out.StatusUpdate) + case projectsMethodGetProjectView: + return out, json.Unmarshal(raw, &out.View) + default: + return nil, fmt.Errorf("unexpected Projects get output method %q", method) + } +} + +func decodeProjectsWriteOutput(method string, raw []byte) (*ProjectsWriteOutput, error) { + out := &ProjectsWriteOutput{Method: method} + if bytes.Equal(bytes.TrimSpace(raw), []byte("null")) { + return out, nil + } + switch method { + case projectsMethodAddProjectItem: + return out, json.Unmarshal(raw, &out.Added) + case projectsMethodUpdateProjectItem: + var discriminator struct { + URL *string `json:"url"` + } + if err := json.Unmarshal(raw, &discriminator); err != nil { + return nil, err + } + if discriminator.URL != nil { + var issue MinimalResponse + if err := json.Unmarshal(raw, &issue); err != nil { + return nil, err + } + out.IssueFields = &ProjectIssueOutput{ID: issue.ID, HTMLURL: issue.URL} + return out, nil + } + return out, json.Unmarshal(raw, &out.Item) + case projectsMethodUpdateProjectItems: + return out, json.Unmarshal(raw, &out.Batch) + case projectsMethodDeleteProjectItem: + out.DeletedItem = &RepositoryMessageOutput{Message: string(raw)} + return out, nil + case projectsMethodCreateProjectStatusUpdate: + return out, json.Unmarshal(raw, &out.StatusUpdate) + case projectsMethodCreateProjectView, projectsMethodUpdateProjectView: + return out, json.Unmarshal(raw, &out.View) + case projectsMethodDeleteProjectView: + return out, json.Unmarshal(raw, &out.DeletedView) + case projectsMethodCreateProject: + var project struct { + ID string `json:"id"` + Number int `json:"number"` + Title string `json:"title"` + URL string `json:"url"` + } + if err := json.Unmarshal(raw, &project); err != nil { + return nil, err + } + out.Project = &ProjectCreatedOutput{ID: project.ID, Number: project.Number, Title: project.Title, HTMLURL: project.URL} + return out, nil + case projectsMethodCreateIterationField: + return out, json.Unmarshal(raw, &out.IterationField) + default: + return nil, fmt.Errorf("unexpected Projects write output method %q", method) + } +} + +func projectsTypedHandler[In, Out any]( + handler func(context.Context, ToolDependencies, *mcp.CallToolRequest, map[string]any) (*mcp.CallToolResult, any, error), + decode func(string, []byte) (Out, error), +) func(context.Context, ToolDependencies, *mcp.CallToolRequest, In) (*mcp.CallToolResult, Out, error) { + return func(ctx context.Context, deps ToolDependencies, req *mcp.CallToolRequest, input In) (*mcp.CallToolResult, Out, error) { + var zero Out + args, err := projectArguments(input) + if err != nil { + return nil, zero, fmt.Errorf("decode Projects arguments: %w", err) + } + result, _, err := handler(ctx, deps, req, args) + if err != nil || result == nil || result.IsError { + return result, zero, err + } + if len(result.Content) != 1 { + return nil, zero, fmt.Errorf("expected one Projects text result") + } + text, ok := result.Content[0].(*mcp.TextContent) + if !ok { + return nil, zero, fmt.Errorf("expected Projects text content") + } + method, err := RequiredParam[string](args, "method") + if err != nil { + return nil, zero, err + } + output, err := decode(method, []byte(text.Text)) + if err != nil { + return nil, zero, fmt.Errorf("decode %s output: %w", method, err) + } + return result, output, nil + } +} + +func projectsSchemaOptions() inventory.TypedSchemaOptions { + // Legacy Projects validators inspect only arguments consumed by the selected + // method, after routing and dependency acquisition. Discovery stays strict. + return inventory.TypedSchemaOptions{ + ValidationInputSchema: &jsonschema.Schema{Type: "object"}, + } +} + +func normalizeProjectsRouting(kind string) inventory.InputNormalizer { + return func(raw json.RawMessage) (json.RawMessage, error) { + var args map[string]any + if err := json.Unmarshal(raw, &args); err != nil { + return nil, &inventory.ToolInputError{Message: "invalid arguments: " + err.Error()} + } + method, err := RequiredParam[string](args, "method") + if err != nil { + return nil, &inventory.ToolInputError{Message: err.Error()} + } + if kind == "get" && (method == projectsMethodGetProjectStatusUpdate || method == projectsMethodGetProjectView) { + delete(args, "owner") + } else if _, err := RequiredParam[string](args, "owner"); err != nil { + return nil, &inventory.ToolInputError{Message: err.Error()} + } + return json.Marshal(args) + } +} diff --git a/pkg/github/projects_v2_test.go b/pkg/github/projects_v2_test.go index 2f397e7fce..f5255e99e5 100644 --- a/pkg/github/projects_v2_test.go +++ b/pkg/github/projects_v2_test.go @@ -9,8 +9,8 @@ import ( "testing" "time" - "github.com/github/github-mcp-server/internal/githubv4mock" - "github.com/github/github-mcp-server/pkg/translations" + "github.com/github/github-mcp-server/v2/internal/githubv4mock" + "github.com/github/github-mcp-server/v2/pkg/translations" "github.com/shurcooL/githubv4" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" diff --git a/pkg/github/prompts.go b/pkg/github/prompts.go index 0c1ac2e9ea..23c4bdfc99 100644 --- a/pkg/github/prompts.go +++ b/pkg/github/prompts.go @@ -1,8 +1,8 @@ package github import ( - "github.com/github/github-mcp-server/pkg/inventory" - "github.com/github/github-mcp-server/pkg/translations" + "github.com/github/github-mcp-server/v2/pkg/inventory" + "github.com/github/github-mcp-server/v2/pkg/translations" ) // AllPrompts returns all prompts with their embedded toolset metadata. diff --git a/pkg/github/public_repo_scopes_test.go b/pkg/github/public_repo_scopes_test.go index 305410a433..4d959bcb12 100644 --- a/pkg/github/public_repo_scopes_test.go +++ b/pkg/github/public_repo_scopes_test.go @@ -3,9 +3,9 @@ package github import ( "testing" - "github.com/github/github-mcp-server/pkg/inventory" - "github.com/github/github-mcp-server/pkg/scopes" - "github.com/github/github-mcp-server/pkg/translations" + "github.com/github/github-mcp-server/v2/pkg/inventory" + "github.com/github/github-mcp-server/v2/pkg/scopes" + "github.com/github/github-mcp-server/v2/pkg/translations" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/github/pullrequests.go b/pkg/github/pullrequests.go index 5cee8b3231..70fdfa197a 100644 --- a/pkg/github/pullrequests.go +++ b/pkg/github/pullrequests.go @@ -6,20 +6,21 @@ import ( "fmt" "io" "net/http" + "slices" "github.com/go-viper/mapstructure/v2" - "github.com/google/go-github/v89/github" + "github.com/google/go-github/v92/github" "github.com/google/jsonschema-go/jsonschema" "github.com/modelcontextprotocol/go-sdk/mcp" "github.com/shurcooL/githubv4" - ghErrors "github.com/github/github-mcp-server/pkg/errors" - "github.com/github/github-mcp-server/pkg/ifc" - "github.com/github/github-mcp-server/pkg/inventory" - "github.com/github/github-mcp-server/pkg/octicons" - "github.com/github/github-mcp-server/pkg/scopes" - "github.com/github/github-mcp-server/pkg/translations" - "github.com/github/github-mcp-server/pkg/utils" + ghErrors "github.com/github/github-mcp-server/v2/pkg/errors" + "github.com/github/github-mcp-server/v2/pkg/ifc" + "github.com/github/github-mcp-server/v2/pkg/inventory" + "github.com/github/github-mcp-server/v2/pkg/octicons" + "github.com/github/github-mcp-server/v2/pkg/scopes" + "github.com/github/github-mcp-server/v2/pkg/translations" + "github.com/github/github-mcp-server/v2/pkg/utils" ) // PullRequestRead creates a tool to get details of a specific pull request. @@ -67,11 +68,12 @@ Possible options: Description: "Cursor for pagination, used only by the get_review_comments method. Pass the endCursor from the previous page's PageInfo to fetch the next page.", } - return NewTool( + return NewTool[PullRequestReadInput, *PullRequestReadOutput]( ToolsetMetadataPullRequests, mcp.Tool{ - Name: "pull_request_read", - Description: t("TOOL_PULL_REQUEST_READ_DESCRIPTION", "Get information on a specific pull request in GitHub repository."), + Name: "pull_request_read", + OutputSchema: pullRequestReadOutputSchema(), + Description: t("TOOL_PULL_REQUEST_READ_DESCRIPTION", "Get information on a specific pull request in GitHub repository."), Annotations: &mcp.ToolAnnotations{ Title: t("TOOL_GET_PULL_REQUEST_USER_TITLE", "Get details for a single pull request"), ReadOnlyHint: true, @@ -79,7 +81,11 @@ Possible options: InputSchema: schema, }, scopes.PublicRead(scopes.Repo), - func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, args map[string]any) (*mcp.CallToolResult, any, error) { + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, input PullRequestReadInput) (*mcp.CallToolResult, *PullRequestReadOutput, error) { + args, err := discussionNotificationArguments(input) + if err != nil { + return nil, nil, err + } method, err := RequiredParam[string](args, "method") if err != nil { return utils.NewToolResultError(err.Error()), nil, nil @@ -119,20 +125,20 @@ Possible options: switch method { case "get": - result, err := GetPullRequest(ctx, client, deps, owner, repo, pullNumber) - return attachIFC(result), nil, err + result, output, err := getPullRequest(ctx, client, deps, owner, repo, pullNumber) + return attachIFC(result), output, err case "get_diff": - result, err := GetPullRequestDiff(ctx, client, deps, owner, repo, pullNumber) - return attachIFC(result), nil, err + result, output, err := getPullRequestDiff(ctx, client, deps, owner, repo, pullNumber) + return attachIFC(result), output, err case "get_status": - result, err := GetPullRequestStatus(ctx, client, owner, repo, pullNumber) - return attachIFC(result), nil, err + result, output, err := getPullRequestStatus(ctx, client, owner, repo, pullNumber) + return attachIFC(result), output, err case "get_files": - result, err := GetPullRequestFiles(ctx, client, deps, owner, repo, pullNumber, pagination) - return attachIFC(result), nil, err + result, output, err := getPullRequestFiles(ctx, client, deps, owner, repo, pullNumber, pagination) + return attachIFC(result), output, err case "get_commits": - result, err := GetPullRequestCommits(ctx, client, deps, owner, repo, pullNumber, pagination) - return attachIFC(result), nil, err + result, output, err := getPullRequestCommits(ctx, client, deps, owner, repo, pullNumber, pagination) + return attachIFC(result), output, err case "get_review_comments": gqlClient, err := deps.GetGQLClient(ctx) if err != nil { @@ -142,27 +148,32 @@ Possible options: if err != nil { return utils.NewToolResultError(err.Error()), nil, nil } - result, err := GetPullRequestReviewComments(ctx, gqlClient, deps, owner, repo, pullNumber, cursorPagination) - return attachIFC(result), nil, err + result, output, err := getPullRequestReviewComments(ctx, gqlClient, deps, owner, repo, pullNumber, cursorPagination) + return attachIFC(result), output, err case "get_reviews": - result, err := GetPullRequestReviews(ctx, client, deps, owner, repo, pullNumber, pagination) - return attachIFC(result), nil, err + result, output, err := getPullRequestReviews(ctx, client, deps, owner, repo, pullNumber, pagination) + return attachIFC(result), output, err case "get_comments": - result, err := GetIssueComments(ctx, client, deps, owner, repo, pullNumber, pagination) - return attachIFC(result), nil, err + result, output, err := getIssueComments(ctx, client, deps, owner, repo, pullNumber, pagination) + return attachIFC(result), pullRequestCommentsOutput(output), err case "get_check_runs": - result, err := GetPullRequestCheckRuns(ctx, client, owner, repo, pullNumber, pagination) - return attachIFC(result), nil, err + result, output, err := getPullRequestCheckRuns(ctx, client, owner, repo, pullNumber, pagination) + return attachIFC(result), output, err default: return utils.NewToolResultError(fmt.Sprintf("unknown method: %s", method)), nil, nil } - }) + }, normalizePullRequestArguments("read")) } func GetPullRequest(ctx context.Context, client *github.Client, deps ToolDependencies, owner, repo string, pullNumber int) (*mcp.CallToolResult, error) { + result, _, err := getPullRequest(ctx, client, deps, owner, repo, pullNumber) + return result, err +} + +func getPullRequest(ctx context.Context, client *github.Client, deps ToolDependencies, owner, repo string, pullNumber int) (*mcp.CallToolResult, *PullRequestReadOutput, error) { cache, err := deps.GetRepoAccessCache(ctx) if err != nil { - return nil, fmt.Errorf("failed to get repo access cache: %w", err) + return nil, nil, fmt.Errorf("failed to get repo access cache: %w", err) } ff := deps.GetFlags(ctx) @@ -172,27 +183,31 @@ func GetPullRequest(ctx context.Context, client *github.Client, deps ToolDepende "failed to get pull request", resp, err, - ), nil + ), nil, nil } defer func() { _ = resp.Body.Close() }() if resp.StatusCode != http.StatusOK { body, err := io.ReadAll(resp.Body) if err != nil { - return nil, fmt.Errorf("failed to read response body: %w", err) + return nil, nil, fmt.Errorf("failed to read response body: %w", err) } - return ghErrors.NewGitHubAPIStatusErrorResponse(ctx, "failed to get pull request", resp, body), nil + return ghErrors.NewGitHubAPIStatusErrorResponse(ctx, "failed to get pull request", resp, body), nil, nil + } + + if pr == nil { + return utils.NewToolResultText("null"), &PullRequestReadOutput{}, nil } if ff.LockdownMode { if restricted, err := authorLockdownResult(ctx, cache, owner, repo, pr.GetUser().GetLogin(), lockdownPullRequestRestrictedMessage); restricted != nil || err != nil { - return restricted, err + return restricted, nil, err } } minimalPR := convertToMinimalPullRequest(pr) - return MarshalledTextResult(minimalPR), nil + return MarshalledTextResult(minimalPR), &PullRequestReadOutput{PullRequest: &minimalPR}, nil } // enforcePullRequestLockdown returns a restricted tool result when lockdown mode is @@ -225,8 +240,13 @@ func enforcePullRequestLockdown(ctx context.Context, client *github.Client, deps } func GetPullRequestDiff(ctx context.Context, client *github.Client, deps ToolDependencies, owner, repo string, pullNumber int) (*mcp.CallToolResult, error) { + result, _, err := getPullRequestDiff(ctx, client, deps, owner, repo, pullNumber) + return result, err +} + +func getPullRequestDiff(ctx context.Context, client *github.Client, deps ToolDependencies, owner, repo string, pullNumber int) (*mcp.CallToolResult, *PullRequestReadOutput, error) { if restricted, err := enforcePullRequestLockdown(ctx, client, deps, owner, repo, pullNumber); restricted != nil || err != nil { - return restricted, err + return restricted, nil, err } raw, resp, err := client.PullRequests.GetRaw( @@ -241,40 +261,45 @@ func GetPullRequestDiff(ctx context.Context, client *github.Client, deps ToolDep "failed to get pull request diff", resp, err, - ), nil + ), nil, nil } if resp.StatusCode != http.StatusOK { body, err := io.ReadAll(resp.Body) if err != nil { - return nil, fmt.Errorf("failed to read response body: %w", err) + return nil, nil, fmt.Errorf("failed to read response body: %w", err) } - return ghErrors.NewGitHubAPIStatusErrorResponse(ctx, "failed to get pull request diff", resp, body), nil + return ghErrors.NewGitHubAPIStatusErrorResponse(ctx, "failed to get pull request diff", resp, body), nil, nil } defer func() { _ = resp.Body.Close() }() // Return the raw response - return utils.NewToolResultText(string(raw)), nil + return utils.NewToolResultText(string(raw)), &PullRequestReadOutput{Diff: &PullRequestDiffOutput{Diff: string(raw)}}, nil } func GetPullRequestStatus(ctx context.Context, client *github.Client, owner, repo string, pullNumber int) (*mcp.CallToolResult, error) { + result, _, err := getPullRequestStatus(ctx, client, owner, repo, pullNumber) + return result, err +} + +func getPullRequestStatus(ctx context.Context, client *github.Client, owner, repo string, pullNumber int) (*mcp.CallToolResult, *PullRequestReadOutput, error) { pr, resp, err := client.PullRequests.Get(ctx, owner, repo, pullNumber) if err != nil { return ghErrors.NewGitHubAPIErrorResponse(ctx, "failed to get pull request", resp, err, - ), nil + ), nil, nil } defer func() { _ = resp.Body.Close() }() if resp.StatusCode != http.StatusOK { body, err := io.ReadAll(resp.Body) if err != nil { - return nil, fmt.Errorf("failed to read response body: %w", err) + return nil, nil, fmt.Errorf("failed to read response body: %w", err) } - return ghErrors.NewGitHubAPIStatusErrorResponse(ctx, "failed to get pull request", resp, body), nil + return ghErrors.NewGitHubAPIStatusErrorResponse(ctx, "failed to get pull request", resp, body), nil, nil } // Get combined status for the head SHA @@ -284,27 +309,33 @@ func GetPullRequestStatus(ctx context.Context, client *github.Client, owner, rep "failed to get combined status", resp, err, - ), nil + ), nil, nil } defer func() { _ = resp.Body.Close() }() if resp.StatusCode != http.StatusOK { body, err := io.ReadAll(resp.Body) if err != nil { - return nil, fmt.Errorf("failed to read response body: %w", err) + return nil, nil, fmt.Errorf("failed to read response body: %w", err) } - return ghErrors.NewGitHubAPIStatusErrorResponse(ctx, "failed to get combined status", resp, body), nil + return ghErrors.NewGitHubAPIStatusErrorResponse(ctx, "failed to get combined status", resp, body), nil, nil } - r, err := json.Marshal(convertToMinimalCombinedStatus(status)) + minimalStatus := convertToMinimalCombinedStatus(status) + r, err := json.Marshal(minimalStatus) if err != nil { - return nil, fmt.Errorf("failed to marshal response: %w", err) + return nil, nil, fmt.Errorf("failed to marshal response: %w", err) } - return utils.NewToolResultText(string(r)), nil + return utils.NewToolResultText(string(r)), &PullRequestReadOutput{Status: &minimalStatus}, nil } func GetPullRequestCheckRuns(ctx context.Context, client *github.Client, owner, repo string, pullNumber int, pagination PaginationParams) (*mcp.CallToolResult, error) { + result, _, err := getPullRequestCheckRuns(ctx, client, owner, repo, pullNumber, pagination) + return result, err +} + +func getPullRequestCheckRuns(ctx context.Context, client *github.Client, owner, repo string, pullNumber int, pagination PaginationParams) (*mcp.CallToolResult, *PullRequestReadOutput, error) { // First get the PR to get the head SHA pr, resp, err := client.PullRequests.Get(ctx, owner, repo, pullNumber) if err != nil { @@ -312,24 +343,22 @@ func GetPullRequestCheckRuns(ctx context.Context, client *github.Client, owner, "failed to get pull request", resp, err, - ), nil + ), nil, nil } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { body, err := io.ReadAll(resp.Body) if err != nil { - return nil, fmt.Errorf("failed to read response body: %w", err) + return nil, nil, fmt.Errorf("failed to read response body: %w", err) } - return ghErrors.NewGitHubAPIStatusErrorResponse(ctx, "failed to get pull request", resp, body), nil + return ghErrors.NewGitHubAPIStatusErrorResponse(ctx, "failed to get pull request", resp, body), nil, nil } // Get check runs for the head SHA opts := &github.ListCheckRunsOptions{ - ListOptions: github.ListOptions{ - PerPage: pagination.PerPage, - Page: pagination.Page, - }, + PerPage: pagination.PerPage, + Page: pagination.Page, } checkRuns, resp, err := client.Checks.ListCheckRunsForRef(ctx, owner, repo, *pr.Head.SHA, opts) @@ -338,16 +367,16 @@ func GetPullRequestCheckRuns(ctx context.Context, client *github.Client, owner, "failed to get check runs", resp, err, - ), nil + ), nil, nil } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { body, err := io.ReadAll(resp.Body) if err != nil { - return nil, fmt.Errorf("failed to read response body: %w", err) + return nil, nil, fmt.Errorf("failed to read response body: %w", err) } - return ghErrors.NewGitHubAPIStatusErrorResponse(ctx, "failed to get check runs", resp, body), nil + return ghErrors.NewGitHubAPIStatusErrorResponse(ctx, "failed to get check runs", resp, body), nil, nil } // Convert to minimal check runs to reduce context usage @@ -363,15 +392,20 @@ func GetPullRequestCheckRuns(ctx context.Context, client *github.Client, owner, r, err := json.Marshal(minimalResult) if err != nil { - return nil, fmt.Errorf("failed to marshal response: %w", err) + return nil, nil, fmt.Errorf("failed to marshal response: %w", err) } - return utils.NewToolResultText(string(r)), nil + return utils.NewToolResultText(string(r)), &PullRequestReadOutput{CheckRuns: &minimalResult}, nil } func GetPullRequestFiles(ctx context.Context, client *github.Client, deps ToolDependencies, owner, repo string, pullNumber int, pagination PaginationParams) (*mcp.CallToolResult, error) { + result, _, err := getPullRequestFiles(ctx, client, deps, owner, repo, pullNumber, pagination) + return result, err +} + +func getPullRequestFiles(ctx context.Context, client *github.Client, deps ToolDependencies, owner, repo string, pullNumber int, pagination PaginationParams) (*mcp.CallToolResult, *PullRequestReadOutput, error) { if restricted, err := enforcePullRequestLockdown(ctx, client, deps, owner, repo, pullNumber); restricted != nil || err != nil { - return restricted, err + return restricted, nil, err } opts := &github.ListOptions{ @@ -384,29 +418,34 @@ func GetPullRequestFiles(ctx context.Context, client *github.Client, deps ToolDe "failed to get pull request files", resp, err, - ), nil + ), nil, nil } defer func() { _ = resp.Body.Close() }() if resp.StatusCode != http.StatusOK { body, err := io.ReadAll(resp.Body) if err != nil { - return nil, fmt.Errorf("failed to read response body: %w", err) + return nil, nil, fmt.Errorf("failed to read response body: %w", err) } - return ghErrors.NewGitHubAPIStatusErrorResponse(ctx, "failed to get pull request files", resp, body), nil + return ghErrors.NewGitHubAPIStatusErrorResponse(ctx, "failed to get pull request files", resp, body), nil, nil } minimalFiles := convertToMinimalPRFiles(files) - return MarshalledTextResult(minimalFiles), nil + return MarshalledTextResult(minimalFiles), &PullRequestReadOutput{Files: &minimalFiles}, nil } // GetPullRequestCommits returns the commits on a pull request. Under lockdown // mode it checks the PR author once rather than per commit, since every // commit on the PR belongs to the same untrusted head branch. func GetPullRequestCommits(ctx context.Context, client *github.Client, deps ToolDependencies, owner, repo string, pullNumber int, pagination PaginationParams) (*mcp.CallToolResult, error) { + result, _, err := getPullRequestCommits(ctx, client, deps, owner, repo, pullNumber, pagination) + return result, err +} + +func getPullRequestCommits(ctx context.Context, client *github.Client, deps ToolDependencies, owner, repo string, pullNumber int, pagination PaginationParams) (*mcp.CallToolResult, *PullRequestReadOutput, error) { if restricted, err := enforcePullRequestLockdown(ctx, client, deps, owner, repo, pullNumber); restricted != nil || err != nil { - return restricted, err + return restricted, nil, err } opts := &github.ListOptions{ @@ -419,21 +458,21 @@ func GetPullRequestCommits(ctx context.Context, client *github.Client, deps Tool "failed to get pull request commits", resp, err, - ), nil + ), nil, nil } defer func() { _ = resp.Body.Close() }() if resp.StatusCode != http.StatusOK { body, err := io.ReadAll(resp.Body) if err != nil { - return nil, fmt.Errorf("failed to read response body: %w", err) + return nil, nil, fmt.Errorf("failed to read response body: %w", err) } - return ghErrors.NewGitHubAPIStatusErrorResponse(ctx, "failed to get pull request commits", resp, body), nil + return ghErrors.NewGitHubAPIStatusErrorResponse(ctx, "failed to get pull request commits", resp, body), nil, nil } minimalCommits := convertToMinimalPullRequestCommits(commits) - return MarshalledTextResult(minimalCommits), nil + return MarshalledTextResult(minimalCommits), &PullRequestReadOutput{Commits: &minimalCommits}, nil } // GraphQL types for review threads query @@ -484,16 +523,21 @@ type pageInfoFragment struct { } func GetPullRequestReviewComments(ctx context.Context, gqlClient *githubv4.Client, deps ToolDependencies, owner, repo string, pullNumber int, pagination CursorPaginationParams) (*mcp.CallToolResult, error) { + result, _, err := getPullRequestReviewComments(ctx, gqlClient, deps, owner, repo, pullNumber, pagination) + return result, err +} + +func getPullRequestReviewComments(ctx context.Context, gqlClient *githubv4.Client, deps ToolDependencies, owner, repo string, pullNumber int, pagination CursorPaginationParams) (*mcp.CallToolResult, *PullRequestReadOutput, error) { cache, err := deps.GetRepoAccessCache(ctx) if err != nil { - return nil, fmt.Errorf("failed to get repo access cache: %w", err) + return nil, nil, fmt.Errorf("failed to get repo access cache: %w", err) } ff := deps.GetFlags(ctx) // Convert pagination parameters to GraphQL format gqlParams, err := pagination.ToGraphQLParams() if err != nil { - return utils.NewToolResultError(fmt.Sprintf("invalid pagination parameters: %v", err)), nil + return utils.NewToolResultError(fmt.Sprintf("invalid pagination parameters: %v", err)), nil, nil } // Build variables for GraphQL query @@ -518,13 +562,13 @@ func GetPullRequestReviewComments(ctx context.Context, gqlClient *githubv4.Clien return ghErrors.NewGitHubGraphQLErrorResponse(ctx, "failed to get pull request review threads", err, - ), nil + ), nil, nil } // Lockdown mode filtering if ff.LockdownMode { if cache == nil { - return nil, fmt.Errorf("lockdown cache is not configured") + return nil, nil, fmt.Errorf("lockdown cache is not configured") } // Iterate through threads and filter comments @@ -537,7 +581,7 @@ func GetPullRequestReviewComments(ctx context.Context, gqlClient *githubv4.Clien if login != "" { isSafeContent, err := cache.IsSafeContent(ctx, login, owner, repo) if err != nil { - return nil, fmt.Errorf("failed to check lockdown mode: %w", err) + return nil, nil, fmt.Errorf("failed to check lockdown mode: %w", err) } if isSafeContent { filteredComments = append(filteredComments, comment) @@ -550,13 +594,19 @@ func GetPullRequestReviewComments(ctx context.Context, gqlClient *githubv4.Clien } } - return MarshalledTextResult(convertToMinimalReviewThreadsResponse(query)), nil + threads := convertToMinimalReviewThreadsResponse(query) + return MarshalledTextResult(threads), &PullRequestReadOutput{ReviewThreads: &threads}, nil } func GetPullRequestReviews(ctx context.Context, client *github.Client, deps ToolDependencies, owner, repo string, pullNumber int, pagination PaginationParams) (*mcp.CallToolResult, error) { + result, _, err := getPullRequestReviews(ctx, client, deps, owner, repo, pullNumber, pagination) + return result, err +} + +func getPullRequestReviews(ctx context.Context, client *github.Client, deps ToolDependencies, owner, repo string, pullNumber int, pagination PaginationParams) (*mcp.CallToolResult, *PullRequestReadOutput, error) { cache, err := deps.GetRepoAccessCache(ctx) if err != nil { - return nil, fmt.Errorf("failed to get repo access cache: %w", err) + return nil, nil, fmt.Errorf("failed to get repo access cache: %w", err) } ff := deps.GetFlags(ctx) @@ -569,21 +619,21 @@ func GetPullRequestReviews(ctx context.Context, client *github.Client, deps Tool "failed to get pull request reviews", resp, err, - ), nil + ), nil, nil } defer func() { _ = resp.Body.Close() }() if resp.StatusCode != http.StatusOK { body, err := io.ReadAll(resp.Body) if err != nil { - return nil, fmt.Errorf("failed to read response body: %w", err) + return nil, nil, fmt.Errorf("failed to read response body: %w", err) } - return ghErrors.NewGitHubAPIStatusErrorResponse(ctx, "failed to get pull request reviews", resp, body), nil + return ghErrors.NewGitHubAPIStatusErrorResponse(ctx, "failed to get pull request reviews", resp, body), nil, nil } if ff.LockdownMode { if cache == nil { - return nil, fmt.Errorf("lockdown cache is not configured") + return nil, nil, fmt.Errorf("lockdown cache is not configured") } filteredReviews := make([]*github.PullRequestReview, 0, len(reviews)) for _, review := range reviews { @@ -593,7 +643,7 @@ func GetPullRequestReviews(ctx context.Context, client *github.Client, deps Tool } isSafeContent, err := cache.IsSafeContent(ctx, login, owner, repo) if err != nil { - return nil, fmt.Errorf("failed to check lockdown mode: %w", err) + return nil, nil, fmt.Errorf("failed to check lockdown mode: %w", err) } if isSafeContent { filteredReviews = append(filteredReviews, review) @@ -607,7 +657,7 @@ func GetPullRequestReviews(ctx context.Context, client *github.Client, deps Tool minimalReviews = append(minimalReviews, convertToMinimalPullRequestReview(review)) } - return MarshalledTextResult(minimalReviews), nil + return MarshalledTextResult(minimalReviews), &PullRequestReadOutput{Reviews: &minimalReviews}, nil } // PullRequestWriteUIResourceURI is the URI for the create_pull_request tool's MCP App UI resource. @@ -648,11 +698,12 @@ var pullRequestUpdateFormParams = map[string]struct{}{ // CreatePullRequest creates a tool to create a new pull request. func CreatePullRequest(t translations.TranslationHelperFunc) inventory.ServerTool { - return NewTool( + return NewTool[CreatePullRequestInput, *PullRequestWriteOutput]( ToolsetMetadataPullRequests, mcp.Tool{ - Name: "create_pull_request", - Description: t("TOOL_CREATE_PULL_REQUEST_DESCRIPTION", "Create a new pull request in a GitHub repository."), + Name: "create_pull_request", + OutputSchema: pullRequestWriteOutputSchema(), + Description: t("TOOL_CREATE_PULL_REQUEST_DESCRIPTION", "Create a new pull request in a GitHub repository."), Annotations: &mcp.ToolAnnotations{ Title: t("TOOL_CREATE_PULL_REQUEST_USER_TITLE", "Open new pull request"), ReadOnlyHint: false, @@ -710,7 +761,11 @@ func CreatePullRequest(t translations.TranslationHelperFunc) inventory.ServerToo }, }, publicRepositoryWriteScopeAccess(), - func(ctx context.Context, deps ToolDependencies, req *mcp.CallToolRequest, args map[string]any) (*mcp.CallToolResult, any, error) { + func(ctx context.Context, deps ToolDependencies, req *mcp.CallToolRequest, input CreatePullRequestInput) (*mcp.CallToolResult, *PullRequestWriteOutput, error) { + args, err := discussionNotificationArguments(input) + if err != nil { + return nil, nil, err + } owner, err := RequiredParam[string](args, "owner") if err != nil { return utils.NewToolResultError(err.Error()), nil, nil @@ -722,15 +777,19 @@ func CreatePullRequest(t translations.TranslationHelperFunc) inventory.ServerToo // Hand off to the interactive MCP App form unless this call must // execute now (see shouldDeferToForm). - if shouldDeferToForm(ctx, deps, req, args, pullRequestWriteFormParams) { - return utils.NewToolResultAwaitingFormSubmission(fmt.Sprintf( + formArgs, err := pullRequestFormArguments(req, args) + if err != nil { + return nil, nil, err + } + if shouldDeferToForm(ctx, deps, req, formArgs, pullRequestWriteFormParams) { + return pullRequestAwaitingFormResult(fmt.Sprintf( "An interactive form has been shown to the user for creating a new pull request in %s/%s. "+ "STOP — do not call any other tools, do not respond as if the pull request was created, "+ "and do not claim the operation succeeded. The pull request has NOT been created yet; "+ "only the form was rendered. Wait silently for the user to review and click Submit. "+ "When they do, the real result will be delivered to your context automatically.", owner, repo, - )), nil, nil + )) } // When creating PR, title/head/base are required @@ -777,17 +836,17 @@ func CreatePullRequest(t translations.TranslationHelperFunc) inventory.ServerToo } newPR := &github.CreatePullRequest{ - Title: github.Ptr(title), + Title: new(title), Head: head, Base: base, } if body != "" { - newPR.Body = github.Ptr(body) + newPR.Body = new(body) } - newPR.Draft = github.Ptr(draft) - newPR.MaintainerCanModify = github.Ptr(maintainerCanModify) + newPR.Draft = new(draft) + newPR.MaintainerCanModify = new(maintainerCanModify) client, err := deps.GetClient(ctx) if err != nil { @@ -852,8 +911,8 @@ func CreatePullRequest(t translations.TranslationHelperFunc) inventory.ServerToo return utils.NewToolResultErrorFromErr("failed to marshal response", err), nil, nil } - return utils.NewToolResultText(string(r)), nil, nil - }) + return utils.NewToolResultText(string(r)), &PullRequestWriteOutput{PullRequest: pullRequestMutationReference(minimalResponse)}, nil + }, normalizePullRequestArguments("create")) } // UpdatePullRequest creates a tool to update an existing pull request. @@ -909,11 +968,12 @@ func UpdatePullRequest(t translations.TranslationHelperFunc) inventory.ServerToo Required: []string{"owner", "repo", "pullNumber"}, } - st := NewTool( + st := NewTool[UpdatePullRequestInput, *PullRequestWriteOutput]( ToolsetMetadataPullRequests, mcp.Tool{ - Name: "update_pull_request", - Description: t("TOOL_UPDATE_PULL_REQUEST_DESCRIPTION", "Update an existing pull request in a GitHub repository."), + Name: "update_pull_request", + OutputSchema: pullRequestWriteOutputSchema(), + Description: t("TOOL_UPDATE_PULL_REQUEST_DESCRIPTION", "Update an existing pull request in a GitHub repository."), Annotations: &mcp.ToolAnnotations{ Title: t("TOOL_UPDATE_PULL_REQUEST_USER_TITLE", "Edit pull request"), ReadOnlyHint: false, @@ -927,7 +987,11 @@ func UpdatePullRequest(t translations.TranslationHelperFunc) inventory.ServerToo InputSchema: schema, }, scopes.RequireAll(scopes.Repo), - func(ctx context.Context, deps ToolDependencies, req *mcp.CallToolRequest, args map[string]any) (*mcp.CallToolResult, any, error) { + func(ctx context.Context, deps ToolDependencies, req *mcp.CallToolRequest, input UpdatePullRequestInput) (*mcp.CallToolResult, *PullRequestWriteOutput, error) { + args, err := discussionNotificationArguments(input) + if err != nil { + return nil, nil, err + } owner, err := RequiredParam[string](args, "owner") if err != nil { return utils.NewToolResultError(err.Error()), nil, nil @@ -943,15 +1007,19 @@ func UpdatePullRequest(t translations.TranslationHelperFunc) inventory.ServerToo // Hand off to the interactive MCP App form unless this call must // execute now (see shouldDeferToForm). - if shouldDeferToForm(ctx, deps, req, args, pullRequestUpdateFormParams) { - return utils.NewToolResultAwaitingFormSubmission(fmt.Sprintf( + formArgs, err := pullRequestFormArguments(req, args) + if err != nil { + return nil, nil, err + } + if shouldDeferToForm(ctx, deps, req, formArgs, pullRequestUpdateFormParams) { + return pullRequestAwaitingFormResult(fmt.Sprintf( "An interactive form has been shown to the user for editing pull request #%d in %s/%s. "+ "STOP — do not call any other tools, do not respond as if the pull request was updated, "+ "and do not claim the operation succeeded. The pull request has NOT been updated yet; "+ "only the form was rendered. Wait silently for the user to review and click Submit. "+ "When they do, the real result will be delivered to your context automatically.", pullNumber, owner, repo, - )), nil, nil + )) } _, draftProvided := args["draft"] @@ -969,35 +1037,35 @@ func UpdatePullRequest(t translations.TranslationHelperFunc) inventory.ServerToo if title, ok, err := OptionalParamOK[string](args, "title"); err != nil { return utils.NewToolResultError(err.Error()), nil, nil } else if ok { - update.Title = github.Ptr(title) + update.Title = new(title) restUpdateNeeded = true } if body, ok, err := OptionalParamOK[string](args, "body"); err != nil { return utils.NewToolResultError(err.Error()), nil, nil } else if ok { - update.Body = github.Ptr(body) + update.Body = new(body) restUpdateNeeded = true } if state, ok, err := OptionalParamOK[string](args, "state"); err != nil { return utils.NewToolResultError(err.Error()), nil, nil } else if ok { - update.State = github.Ptr(state) + update.State = new(state) restUpdateNeeded = true } if base, ok, err := OptionalParamOK[string](args, "base"); err != nil { return utils.NewToolResultError(err.Error()), nil, nil } else if ok { - update.Base = &github.PullRequestBranch{Ref: github.Ptr(base)} + update.Base = &github.PullRequestBranch{Ref: new(base)} restUpdateNeeded = true } if maintainerCanModify, ok, err := OptionalParamOK[bool](args, "maintainer_can_modify"); err != nil { return utils.NewToolResultError(err.Error()), nil, nil } else if ok { - update.MaintainerCanModify = github.Ptr(maintainerCanModify) + update.MaintainerCanModify = new(maintainerCanModify) restUpdateNeeded = true } @@ -1167,8 +1235,8 @@ func UpdatePullRequest(t translations.TranslationHelperFunc) inventory.ServerToo return utils.NewToolResultErrorFromErr("Failed to marshal response", err), nil, nil } - return utils.NewToolResultText(string(r)), nil, nil - }) + return utils.NewToolResultText(string(r)), &PullRequestWriteOutput{PullRequest: pullRequestMutationReference(minimalResponse)}, nil + }, normalizePullRequestArguments("update")) st.FeatureRule = pullRequestsConsolidatedRule return st } @@ -1193,7 +1261,7 @@ func AddReplyToPullRequestComment(t translations.TranslationHelperFunc) inventor "commentId": { Type: "number", Description: "The numeric ID of the pull request review comment to reply or react to. Use the number from a #discussion_r... anchor, not the GraphQL thread node ID (PRRT_...).", - Minimum: jsonschema.Ptr(1.0), + Minimum: new(1.0), }, "body": { Type: "string", @@ -1208,11 +1276,12 @@ func AddReplyToPullRequestComment(t translations.TranslationHelperFunc) inventor Required: []string{"owner", "repo", "commentId"}, } - return NewTool( + return NewTool[AddReplyToPullRequestCommentInput, *PullRequestCommentReplyOutput]( ToolsetMetadataPullRequests, mcp.Tool{ - Name: "add_reply_to_pull_request_comment", - Description: t("TOOL_ADD_REPLY_TO_PULL_REQUEST_COMMENT_DESCRIPTION", "Add a reply and/or reaction to an existing pull request comment. This can create a new comment linked as a reply to the specified comment, add an emoji reaction to the specified comment, or do both. At least one of body or reaction is required."), + Name: "add_reply_to_pull_request_comment", + OutputSchema: pullRequestCommentReplyOutputSchema(), + Description: t("TOOL_ADD_REPLY_TO_PULL_REQUEST_COMMENT_DESCRIPTION", "Add a reply and/or reaction to an existing pull request comment. This can create a new comment linked as a reply to the specified comment, add an emoji reaction to the specified comment, or do both. At least one of body or reaction is required."), Annotations: &mcp.ToolAnnotations{ Title: t("TOOL_ADD_REPLY_TO_PULL_REQUEST_COMMENT_USER_TITLE", "Add reply to pull request comment"), ReadOnlyHint: false, @@ -1220,7 +1289,11 @@ func AddReplyToPullRequestComment(t translations.TranslationHelperFunc) inventor InputSchema: schema, }, scopes.RequireAll(scopes.Repo), - func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, args map[string]any) (*mcp.CallToolResult, any, error) { + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, input AddReplyToPullRequestCommentInput) (*mcp.CallToolResult, *PullRequestCommentReplyOutput, error) { + args, err := discussionNotificationArguments(input) + if err != nil { + return nil, nil, err + } owner, err := RequiredParam[string](args, "owner") if err != nil { return utils.NewToolResultError(err.Error()), nil, nil @@ -1302,29 +1375,160 @@ func AddReplyToPullRequestComment(t translations.TranslationHelperFunc) inventor } } - var result any + var output PullRequestCommentReplyOutput + var r []byte switch { case hasBody && hasReaction: - result = map[string]MinimalResponse{ - "comment": *commentResponse, - "reaction": *reactionResponse, + output.ReplyAndReaction = &PullRequestReplyAndReactionOutput{ + Comment: *pullRequestMutationReference(*commentResponse), + Reaction: PullRequestMutationReference{ID: reactionResponse.ID}, } + r, err = json.Marshal(map[string]*MinimalResponse{"comment": commentResponse, "reaction": reactionResponse}) case hasReaction: - result = reactionResponse + output.Response = &PullRequestMutationReference{ID: reactionResponse.ID} + r, err = json.Marshal(reactionResponse) default: - result = commentResponse + output.Response = pullRequestMutationReference(*commentResponse) + r, err = json.Marshal(commentResponse) } - r, err := json.Marshal(result) if err != nil { return utils.NewToolResultErrorFromErr("failed to marshal response", err), nil, nil } - return utils.NewToolResultText(string(r)), nil, nil - }) + return utils.NewToolResultText(string(r)), &output, nil + }, normalizePullRequestArguments("reply")) } // ListPullRequests creates a tool to list pull requests in a GitHub repository. +type ListPullRequestsInput struct { + Owner string `json:"owner"` + Repo string `json:"repo"` + State string `json:"state,omitempty"` + Head string `json:"head,omitempty"` + Base string `json:"base,omitempty"` + Sort string `json:"sort,omitempty"` + Direction string `json:"direction,omitempty"` + Fields []string `json:"fields,omitempty"` + Page *int `json:"page,omitempty"` + PerPage *int `json:"perPage,omitempty"` +} + +type ListPullRequestOutput struct { + Number *int `json:"number,omitempty"` + Title *string `json:"title,omitempty"` + Body *string `json:"body,omitempty"` + State *string `json:"state,omitempty" jsonschema:"Pull request state: open or closed."` + Draft *bool `json:"draft,omitempty"` + Merged *bool `json:"merged,omitempty"` + MergeableState *string `json:"mergeable_state,omitempty"` + HTMLURL *string `json:"html_url,omitempty"` + User *MinimalUser `json:"user,omitempty"` + Labels *[]string `json:"labels,omitempty"` + Assignees *[]string `json:"assignees,omitempty"` + RequestedReviewers *[]string `json:"requested_reviewers,omitempty"` + MergedBy *string `json:"merged_by,omitempty"` + Head *MinimalPRBranch `json:"head,omitempty"` + Base *MinimalPRBranch `json:"base,omitempty"` + Additions *int `json:"additions,omitempty" jsonschema:"Number of lines added."` + Deletions *int `json:"deletions,omitempty" jsonschema:"Number of lines removed."` + ChangedFiles *int `json:"changed_files,omitempty" jsonschema:"Number of files changed."` + Commits *int `json:"commits,omitempty" jsonschema:"Number of commits in the pull request."` + Comments *int `json:"comments,omitempty" jsonschema:"Number of comments on the pull request."` + CreatedAt *string `json:"created_at,omitempty" jsonschema:"Creation time in RFC 3339 format."` + UpdatedAt *string `json:"updated_at,omitempty" jsonschema:"Last update time in RFC 3339 format."` + ClosedAt *string `json:"closed_at,omitempty" jsonschema:"Closing time in RFC 3339 format."` + MergedAt *string `json:"merged_at,omitempty" jsonschema:"Merge time in RFC 3339 format."` + Milestone *string `json:"milestone,omitempty"` +} + +func structuredListPullRequestsOutput(pullRequests []MinimalPullRequest, fields []string) []ListPullRequestOutput { + output := make([]ListPullRequestOutput, 0, len(pullRequests)) + selected := func(field string) bool { + return len(fields) == 0 || slices.Contains(fields, field) + } + for _, pr := range pullRequests { + item := ListPullRequestOutput{} + if selected("number") { + item.Number = new(pr.Number) + } + if selected("title") { + item.Title = new(pr.Title) + } + if selected("body") && pr.Body != "" { + item.Body = new(pr.Body) + } + if selected("state") { + item.State = new(pr.State) + } + if selected("draft") { + item.Draft = new(pr.Draft) + } + if selected("merged") { + item.Merged = new(pr.Merged) + } + if selected("mergeable_state") && pr.MergeableState != "" { + item.MergeableState = new(pr.MergeableState) + } + if selected("html_url") { + item.HTMLURL = new(pr.HTMLURL) + } + if selected("user") && pr.User != nil { + item.User = pr.User + } + if selected("labels") && len(pr.Labels) > 0 { + item.Labels = &pr.Labels + } + if selected("assignees") && len(pr.Assignees) > 0 { + item.Assignees = &pr.Assignees + } + if selected("requested_reviewers") && len(pr.RequestedReviewers) > 0 { + item.RequestedReviewers = &pr.RequestedReviewers + } + if selected("merged_by") && pr.MergedBy != "" { + item.MergedBy = new(pr.MergedBy) + } + if selected("head") && pr.Head != nil { + item.Head = pr.Head + } + if selected("base") && pr.Base != nil { + item.Base = pr.Base + } + if selected("additions") && pr.Additions != 0 { + item.Additions = new(pr.Additions) + } + if selected("deletions") && pr.Deletions != 0 { + item.Deletions = new(pr.Deletions) + } + if selected("changed_files") && pr.ChangedFiles != 0 { + item.ChangedFiles = new(pr.ChangedFiles) + } + if selected("commits") && pr.Commits != 0 { + item.Commits = new(pr.Commits) + } + if selected("comments") && pr.Comments != 0 { + item.Comments = new(pr.Comments) + } + if selected("created_at") && pr.CreatedAt != "" { + item.CreatedAt = new(pr.CreatedAt) + } + if selected("updated_at") && pr.UpdatedAt != "" { + item.UpdatedAt = new(pr.UpdatedAt) + } + if selected("closed_at") && pr.ClosedAt != "" { + item.ClosedAt = new(pr.ClosedAt) + } + if selected("merged_at") && pr.MergedAt != "" { + item.MergedAt = new(pr.MergedAt) + } + if selected("milestone") && pr.Milestone != "" { + item.Milestone = new(pr.Milestone) + } + output = append(output, item) + } + return output +} + func ListPullRequests(t translations.TranslationHelperFunc) inventory.ServerTool { schema := &jsonschema.Schema{ Type: "object", @@ -1369,7 +1573,7 @@ func ListPullRequests(t translations.TranslationHelperFunc) inventory.ServerTool ) WithPagination(schema) - return NewTool( + return NewTool[ListPullRequestsInput, []ListPullRequestOutput]( ToolsetMetadataPullRequests, mcp.Tool{ Name: "list_pull_requests", @@ -1381,61 +1585,36 @@ func ListPullRequests(t translations.TranslationHelperFunc) inventory.ServerTool InputSchema: schema, }, scopes.PublicRead(scopes.Repo), - func(ctx context.Context, deps ToolDependencies, _ *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 - } - repo, err := RequiredParam[string](args, "repo") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - state, err := OptionalParam[string](args, "state") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - head, err := OptionalParam[string](args, "head") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - base, err := OptionalParam[string](args, "base") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - sort, err := OptionalParam[string](args, "sort") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, input ListPullRequestsInput) (*mcp.CallToolResult, []ListPullRequestOutput, error) { + if input.Owner == "" { + return utils.NewToolResultError("missing required parameter: owner"), nil, nil } - direction, err := OptionalParam[string](args, "direction") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil + if input.Repo == "" { + return utils.NewToolResultError("missing required parameter: repo"), nil, nil } - fields, err := OptionalStringArrayParam(args, "fields") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil + pagination := PaginationParams{Page: 1, PerPage: 30} + if input.Page != nil { + pagination.Page = *input.Page } - pagination, err := OptionalPaginationParams(args) - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil + if input.PerPage != nil { + pagination.PerPage = *input.PerPage } opts := &github.PullRequestListOptions{ - State: state, - Head: head, - Base: base, - Sort: sort, - Direction: direction, - ListOptions: github.ListOptions{ - PerPage: pagination.PerPage, - Page: pagination.Page, - }, + State: input.State, + Head: input.Head, + Base: input.Base, + Sort: input.Sort, + Direction: input.Direction, + PerPage: pagination.PerPage, + Page: pagination.Page, } client, err := deps.GetClient(ctx) if err != nil { return utils.NewToolResultErrorFromErr("failed to get GitHub client", err), nil, nil } - prs, resp, err := client.PullRequests.List(ctx, owner, repo, opts) + prs, resp, err := client.PullRequests.List(ctx, input.Owner, input.Repo, opts) if err != nil { return ghErrors.NewGitHubAPIErrorResponse(ctx, "failed to list pull requests", @@ -1462,8 +1641,8 @@ func ListPullRequests(t translations.TranslationHelperFunc) inventory.ServerTool filtered := false var payload any = minimalPRs - if len(fields) > 0 { - filteredPRs, err := filterEachField(minimalPRs, fields) + if len(input.Fields) > 0 { + filteredPRs, err := filterEachField(minimalPRs, input.Fields) if err != nil { return utils.NewToolResultErrorFromErr("failed to filter pull requests", err), nil, nil } @@ -1481,9 +1660,11 @@ func ListPullRequests(t translations.TranslationHelperFunc) inventory.ServerTool result := utils.NewToolResultText(string(r)) // Pull request titles/bodies are user-authored (untrusted); // confidentiality follows repo visibility. - result = attachRepoVisibilityIFCLabel(ctx, deps, client, owner, repo, result, ifc.LabelRepoUserContent) - return result, nil, nil - }) + result = attachRepoVisibilityIFCLabel(ctx, deps, client, input.Owner, input.Repo, result, ifc.LabelRepoUserContent) + return result, structuredListPullRequestsOutput(minimalPRs, input.Fields), nil + }, + normalizeTypedReadArguments(nil, false), + ) } // MergePullRequest creates a tool to merge a pull request. @@ -1524,12 +1705,13 @@ func MergePullRequest(t translations.TranslationHelperFunc) inventory.ServerTool Required: []string{"owner", "repo", "pullNumber"}, } - return NewTool( + return NewTool[MergePullRequestInput, *PullRequestMergeOutput]( ToolsetMetadataPullRequests, mcp.Tool{ - Name: "merge_pull_request", - Description: t("TOOL_MERGE_PULL_REQUEST_DESCRIPTION", "Merge a pull request in a GitHub repository."), - Icons: octicons.Icons("git-merge"), + Name: "merge_pull_request", + OutputSchema: pullRequestMergeOutputSchema(), + Description: t("TOOL_MERGE_PULL_REQUEST_DESCRIPTION", "Merge a pull request in a GitHub repository."), + Icons: octicons.Icons("git-merge"), Annotations: &mcp.ToolAnnotations{ Title: t("TOOL_MERGE_PULL_REQUEST_USER_TITLE", "Merge pull request"), ReadOnlyHint: false, @@ -1537,7 +1719,11 @@ func MergePullRequest(t translations.TranslationHelperFunc) inventory.ServerTool InputSchema: schema, }, scopes.RequireAll(scopes.Repo), - func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, args map[string]any) (*mcp.CallToolResult, any, error) { + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, input MergePullRequestInput) (*mcp.CallToolResult, *PullRequestMergeOutput, error) { + args, err := discussionNotificationArguments(input) + if err != nil { + return nil, nil, err + } owner, err := RequiredParam[string](args, "owner") if err != nil { return utils.NewToolResultError(err.Error()), nil, nil @@ -1600,8 +1786,12 @@ func MergePullRequest(t translations.TranslationHelperFunc) inventory.ServerTool return utils.NewToolResultErrorFromErr("failed to marshal response", err), nil, nil } - return utils.NewToolResultText(string(r)), nil, nil - }) + output := &PullRequestMergeOutput{} + if result != nil { + output.Result = &PullRequestMergeResult{SHA: result.SHA, Merged: result.Merged, Message: result.Message} + } + return utils.NewToolResultText(string(r)), output, nil + }, normalizePullRequestArguments("merge")) } // SearchPullRequests creates a tool to search for pull requests. @@ -1652,7 +1842,7 @@ func SearchPullRequests(t translations.TranslationHelperFunc) inventory.ServerTo ) WithPagination(schema) - return NewTool( + return NewTool[SearchIssuesInput, SearchIssuesOutput]( ToolsetMetadataPullRequests, mcp.Tool{ Name: "search_pull_requests", @@ -1664,16 +1854,14 @@ func SearchPullRequests(t translations.TranslationHelperFunc) inventory.ServerTo InputSchema: schema, }, scopes.PublicRead(scopes.Repo), - func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, args map[string]any) (*mcp.CallToolResult, any, error) { + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, input SearchIssuesInput) (*mcp.CallToolResult, SearchIssuesOutput, error) { options := []searchOption{ifcSearchPostProcessOption(ctx, deps)} - fields, err := OptionalStringArrayParam(args, "fields") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - options = append(options, withFieldsFiltering(deps, "search_pull_requests", fields)) - result, err := searchHandler(ctx, deps.GetClient, args, "pr", "failed to search pull requests", options...) - return result, nil, err - }) + options = append(options, withFieldsFiltering(deps, "search_pull_requests", input.Fields)) + result, response, err := searchHandler(ctx, deps.GetClient, input, "pr", "failed to search pull requests", options...) + return result, structuredSearchIssuesOutput(response, input.Fields), err + }, + normalizeTypedReadArguments(nil, false), + ) } // UpdatePullRequestBranch creates a tool to update a pull request branch with the latest changes from the base branch. @@ -1701,11 +1889,12 @@ func UpdatePullRequestBranch(t translations.TranslationHelperFunc) inventory.Ser Required: []string{"owner", "repo", "pullNumber"}, } - return NewTool( + return NewTool[UpdatePullRequestBranchInput, *PullRequestBranchUpdateOutput]( ToolsetMetadataPullRequests, mcp.Tool{ - Name: "update_pull_request_branch", - Description: t("TOOL_UPDATE_PULL_REQUEST_BRANCH_DESCRIPTION", "Update the branch of a pull request with the latest changes from the base branch."), + Name: "update_pull_request_branch", + OutputSchema: pullRequestBranchUpdateOutputSchema(), + Description: t("TOOL_UPDATE_PULL_REQUEST_BRANCH_DESCRIPTION", "Update the branch of a pull request with the latest changes from the base branch."), Annotations: &mcp.ToolAnnotations{ Title: t("TOOL_UPDATE_PULL_REQUEST_BRANCH_USER_TITLE", "Update pull request branch"), ReadOnlyHint: false, @@ -1713,7 +1902,11 @@ func UpdatePullRequestBranch(t translations.TranslationHelperFunc) inventory.Ser InputSchema: schema, }, scopes.RequireAll(scopes.Repo), - func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, args map[string]any) (*mcp.CallToolResult, any, error) { + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, input UpdatePullRequestBranchInput) (*mcp.CallToolResult, *PullRequestBranchUpdateOutput, error) { + args, err := discussionNotificationArguments(input) + if err != nil { + return nil, nil, err + } owner, err := RequiredParam[string](args, "owner") if err != nil { return utils.NewToolResultError(err.Error()), nil, nil @@ -1732,7 +1925,7 @@ func UpdatePullRequestBranch(t translations.TranslationHelperFunc) inventory.Ser } opts := &github.PullRequestBranchUpdateOptions{} if expectedHeadSHA != "" { - opts.ExpectedHeadSHA = github.Ptr(expectedHeadSHA) + opts.ExpectedHeadSHA = new(expectedHeadSHA) } client, err := deps.GetClient(ctx) @@ -1744,7 +1937,8 @@ func UpdatePullRequestBranch(t translations.TranslationHelperFunc) inventory.Ser // Check if it's an acceptedError. An acceptedError indicates that the update is in progress, // and it's not a real error. if resp != nil && resp.StatusCode == http.StatusAccepted && isAcceptedError(err) { - return utils.NewToolResultText("Pull request branch update is in progress"), nil, nil + message := "Pull request branch update is in progress" + return utils.NewToolResultText(message), &PullRequestBranchUpdateOutput{Result: &PullRequestBranchUpdateResult{Message: &message}}, nil } return ghErrors.NewGitHubAPIErrorResponse(ctx, "failed to update pull request branch", @@ -1767,8 +1961,12 @@ func UpdatePullRequestBranch(t translations.TranslationHelperFunc) inventory.Ser return utils.NewToolResultErrorFromErr("failed to marshal response", err), nil, nil } - return utils.NewToolResultText(string(r)), nil, nil - }) + output := &PullRequestBranchUpdateOutput{} + if result != nil { + output.Result = &PullRequestBranchUpdateResult{Message: result.Message} + } + return utils.NewToolResultText(string(r)), output, nil + }, normalizePullRequestArguments("branch")) } type PullRequestReviewWriteParams struct { @@ -1850,10 +2048,11 @@ func pullRequestReviewWrite(t translations.TranslationHelperFunc, withResolution } } - st := NewTool( + st := NewTool[PullRequestReviewWriteInput, *RepositoryMessageOutput]( ToolsetMetadataPullRequests, mcp.Tool{ - Name: "pull_request_review_write", + Name: "pull_request_review_write", + OutputSchema: pullRequestOutputSchema[RepositoryMessageOutput](), Description: t("TOOL_PULL_REQUEST_REVIEW_WRITE_DESCRIPTION", `Create and/or submit, delete review of a pull request. Available methods: @@ -1870,7 +2069,11 @@ Available methods: InputSchema: schema, }, scopes.RequireAll(scopes.Repo), - func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, args map[string]any) (*mcp.CallToolResult, any, error) { + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, input PullRequestReviewWriteInput) (*mcp.CallToolResult, *RepositoryMessageOutput, error) { + args, err := discussionNotificationArguments(input) + if err != nil { + return nil, nil, err + } var params PullRequestReviewWriteParams if err := mapstructure.WeakDecode(args, ¶ms); err != nil { return utils.NewToolResultError(err.Error()), nil, nil @@ -1882,30 +2085,32 @@ Available methods: return utils.NewToolResultError(fmt.Sprintf("failed to get GitHub GQL client: %v", err)), nil, nil } + var result *mcp.CallToolResult + switch params.Method { case "create": - result, err := CreatePullRequestReview(ctx, client, params) - return result, nil, err + result, err = CreatePullRequestReview(ctx, client, params) + return pullRequestMessageResult(result, err) case "submit_pending": - result, err := SubmitPendingPullRequestReview(ctx, client, params) - return result, nil, err + result, err = SubmitPendingPullRequestReview(ctx, client, params) + return pullRequestMessageResult(result, err) case "delete_pending": - result, err := DeletePendingPullRequestReview(ctx, client, params) - return result, nil, err + result, err = DeletePendingPullRequestReview(ctx, client, params) + return pullRequestMessageResult(result, err) case "resolve_thread": if !withResolutionReason { - result, err := ResolveReviewThread(ctx, client, params.ThreadID, true) - return result, nil, err + result, err = ResolveReviewThread(ctx, client, params.ThreadID, true) + return pullRequestMessageResult(result, err) } - result, err := ResolveReviewThreadWithReason(ctx, client, params.ThreadID, params.ResolutionReason, true) - return result, nil, err + result, err = ResolveReviewThreadWithReason(ctx, client, params.ThreadID, params.ResolutionReason, true) + return pullRequestMessageResult(result, err) case "unresolve_thread": - result, err := ResolveReviewThread(ctx, client, params.ThreadID, false) - return result, nil, err + result, err = ResolveReviewThread(ctx, client, params.ThreadID, false) + return pullRequestMessageResult(result, err) default: return utils.NewToolResultError(fmt.Sprintf("unknown method: %s", params.Method)), nil, nil } - }) + }, normalizePullRequestReviewWriteArguments) if withResolutionReason { st.FeatureRule = inventory.NewFeatureRule( []inventory.FeatureFlag{FeatureFlagThreadResolutionReason, inventory.FeatureFlag(FeatureFlagPullRequestsGranular)}, @@ -1989,57 +2194,9 @@ func CreatePullRequestReview(ctx context.Context, client *githubv4.Client, param } func SubmitPendingPullRequestReview(ctx context.Context, client *githubv4.Client, params PullRequestReviewWriteParams) (*mcp.CallToolResult, error) { - // First we'll get the current user - var getViewerQuery struct { - Viewer struct { - Login githubv4.String - } - } - - if err := client.Query(ctx, &getViewerQuery, nil); err != nil { - return ghErrors.NewGitHubGraphQLErrorResponse(ctx, - "failed to get current user", - err, - ), nil - } - - var getLatestReviewForViewerQuery struct { - Repository struct { - PullRequest struct { - Reviews struct { - Nodes []struct { - ID githubv4.ID - State githubv4.PullRequestReviewState - URL githubv4.URI - } - } `graphql:"reviews(first: 1, author: $author)"` - } `graphql:"pullRequest(number: $prNum)"` - } `graphql:"repository(owner: $owner, name: $name)"` - } - - vars := map[string]any{ - "author": githubv4.String(getViewerQuery.Viewer.Login), - "owner": githubv4.String(params.Owner), - "name": githubv4.String(params.Repo), - "prNum": githubv4.Int(params.PullNumber), - } - - if err := client.Query(ctx, &getLatestReviewForViewerQuery, vars); err != nil { - return ghErrors.NewGitHubGraphQLErrorResponse(ctx, - "failed to get latest review for current user", - err, - ), nil - } - - // Validate there is one review and the state is pending - if len(getLatestReviewForViewerQuery.Repository.PullRequest.Reviews.Nodes) == 0 { - return utils.NewToolResultError("No pending review found for the viewer"), nil - } - - review := getLatestReviewForViewerQuery.Repository.PullRequest.Reviews.Nodes[0] - if review.State != githubv4.PullRequestReviewStatePending { - errText := fmt.Sprintf("The latest review, found at %s is not pending", review.URL) - return utils.NewToolResultError(errText), nil + review, result := getPendingPullRequestReviewForViewer(ctx, client, params.Owner, params.Repo, params.PullNumber) + if result != nil { + return result, nil } // Prepare the mutation @@ -2055,7 +2212,7 @@ func SubmitPendingPullRequestReview(ctx context.Context, client *githubv4.Client ctx, &submitPullRequestReviewMutation, githubv4.SubmitPullRequestReviewInput{ - PullRequestReviewID: &review.ID, + PullRequestReviewID: review, Event: githubv4.PullRequestReviewEvent(params.Event), Body: newGQLStringlikePtr[githubv4.String](¶ms.Body), }, @@ -2074,57 +2231,9 @@ func SubmitPendingPullRequestReview(ctx context.Context, client *githubv4.Client } func DeletePendingPullRequestReview(ctx context.Context, client *githubv4.Client, params PullRequestReviewWriteParams) (*mcp.CallToolResult, error) { - // First we'll get the current user - var getViewerQuery struct { - Viewer struct { - Login githubv4.String - } - } - - if err := client.Query(ctx, &getViewerQuery, nil); err != nil { - return ghErrors.NewGitHubGraphQLErrorResponse(ctx, - "failed to get current user", - err, - ), nil - } - - var getLatestReviewForViewerQuery struct { - Repository struct { - PullRequest struct { - Reviews struct { - Nodes []struct { - ID githubv4.ID - State githubv4.PullRequestReviewState - URL githubv4.URI - } - } `graphql:"reviews(first: 1, author: $author)"` - } `graphql:"pullRequest(number: $prNum)"` - } `graphql:"repository(owner: $owner, name: $name)"` - } - - vars := map[string]any{ - "author": githubv4.String(getViewerQuery.Viewer.Login), - "owner": githubv4.String(params.Owner), - "name": githubv4.String(params.Repo), - "prNum": githubv4.Int(params.PullNumber), - } - - if err := client.Query(ctx, &getLatestReviewForViewerQuery, vars); err != nil { - return ghErrors.NewGitHubGraphQLErrorResponse(ctx, - "failed to get latest review for current user", - err, - ), nil - } - - // Validate there is one review and the state is pending - if len(getLatestReviewForViewerQuery.Repository.PullRequest.Reviews.Nodes) == 0 { - return utils.NewToolResultError("No pending review found for the viewer"), nil - } - - review := getLatestReviewForViewerQuery.Repository.PullRequest.Reviews.Nodes[0] - if review.State != githubv4.PullRequestReviewStatePending { - errText := fmt.Sprintf("The latest review, found at %s is not pending", review.URL) - return utils.NewToolResultError(errText), nil + review, result := getPendingPullRequestReviewForViewer(ctx, client, params.Owner, params.Repo, params.PullNumber) + if result != nil { + return result, nil } // Prepare the mutation @@ -2140,7 +2249,7 @@ func DeletePendingPullRequestReview(ctx context.Context, client *githubv4.Client ctx, &deletePullRequestReviewMutation, githubv4.DeletePullRequestReviewInput{ - PullRequestReviewID: &review.ID, + PullRequestReviewID: review, }, nil, ); err != nil { @@ -2235,57 +2344,9 @@ type AddCommentToPendingReviewParams struct { // AddCommentToPendingReviewCall adds a review comment to the viewer's pending pull request review. func AddCommentToPendingReviewCall(ctx context.Context, client *githubv4.Client, params AddCommentToPendingReviewParams) (*mcp.CallToolResult, error) { - // Get the current user - var getViewerQuery struct { - Viewer struct { - Login githubv4.String - } - } - - if err := client.Query(ctx, &getViewerQuery, nil); err != nil { - return ghErrors.NewGitHubGraphQLErrorResponse(ctx, - "failed to get current user", - err, - ), nil - } - - var getLatestReviewForViewerQuery struct { - Repository struct { - PullRequest struct { - Reviews struct { - Nodes []struct { - ID githubv4.ID - State githubv4.PullRequestReviewState - URL githubv4.URI - } - } `graphql:"reviews(first: 1, author: $author)"` - } `graphql:"pullRequest(number: $prNum)"` - } `graphql:"repository(owner: $owner, name: $name)"` - } - - vars := map[string]any{ - "author": githubv4.String(getViewerQuery.Viewer.Login), - "owner": githubv4.String(params.Owner), - "name": githubv4.String(params.Repo), - "prNum": githubv4.Int(params.PullNumber), - } - - if err := client.Query(ctx, &getLatestReviewForViewerQuery, vars); err != nil { - return ghErrors.NewGitHubGraphQLErrorResponse(ctx, - "failed to get latest review for current user", - err, - ), nil - } - - // Validate there is one review and the state is pending - if len(getLatestReviewForViewerQuery.Repository.PullRequest.Reviews.Nodes) == 0 { - return utils.NewToolResultError("No pending review found for the viewer"), nil - } - - review := getLatestReviewForViewerQuery.Repository.PullRequest.Reviews.Nodes[0] - if review.State != githubv4.PullRequestReviewStatePending { - errText := fmt.Sprintf("The latest review, found at %s is not pending", review.URL) - return utils.NewToolResultError(errText), nil + review, result := getPendingPullRequestReviewForViewer(ctx, client, params.Owner, params.Repo, params.PullNumber) + if result != nil { + return result, nil } // Create a new review thread comment on the review. @@ -2301,14 +2362,14 @@ func AddCommentToPendingReviewCall(ctx context.Context, client *githubv4.Client, ctx, &addPullRequestReviewThreadMutation, githubv4.AddPullRequestReviewThreadInput{ - Path: githubv4.String(params.Path), + Path: newGQLStringlikePtr[githubv4.String](¶ms.Path), Body: githubv4.String(params.Body), SubjectType: newGQLStringlikePtr[githubv4.PullRequestReviewThreadSubjectType](¶ms.SubjectType), Line: newGQLIntPtr(params.Line), Side: newGQLStringlikePtr[githubv4.DiffSide](params.Side), StartLine: newGQLIntPtr(params.StartLine), StartSide: newGQLStringlikePtr[githubv4.DiffSide](params.StartSide), - PullRequestReviewID: &review.ID, + PullRequestReviewID: review, }, nil, ); err != nil { @@ -2326,6 +2387,100 @@ func AddCommentToPendingReviewCall(ctx context.Context, client *githubv4.Client, return utils.NewToolResultText("pull request review comment successfully added to pending review"), nil } +type pendingReviewAuthor struct { + Bot struct { + ID githubv4.ID `graphql:"botId: id"` + } `graphql:"... on Bot"` + EnterpriseUserAccount struct { + ID githubv4.ID `graphql:"enterpriseUserAccountId: id"` + } `graphql:"... on EnterpriseUserAccount"` + Mannequin struct { + ID githubv4.ID `graphql:"mannequinId: id"` + } `graphql:"... on Mannequin"` + Organization struct { + ID githubv4.ID `graphql:"organizationId: id"` + } `graphql:"... on Organization"` + User struct { + ID githubv4.ID `graphql:"userId: id"` + } `graphql:"... on User"` +} + +func (a pendingReviewAuthor) id() githubv4.ID { + for _, id := range []githubv4.ID{ + a.Bot.ID, + a.EnterpriseUserAccount.ID, + a.Mannequin.ID, + a.Organization.ID, + a.User.ID, + } { + if id != nil { + return id + } + } + return nil +} + +func getPendingPullRequestReviewForViewer(ctx context.Context, client *githubv4.Client, owner, repo string, pullNumber int32) (*githubv4.ID, *mcp.CallToolResult) { + var getViewerQuery struct { + Viewer struct { + ID githubv4.ID + } + } + + if err := client.Query(ctx, &getViewerQuery, nil); err != nil { + return nil, ghErrors.NewGitHubGraphQLErrorResponse(ctx, + "failed to get current user", + err, + ) + } + + vars := map[string]any{ + "after": (*githubv4.String)(nil), + "owner": githubv4.String(owner), + "name": githubv4.String(repo), + "prNum": githubv4.Int(pullNumber), + "states": []githubv4.PullRequestReviewState{githubv4.PullRequestReviewStatePending}, + } + + for { + var getPendingReviewsQuery struct { + Repository struct { + PullRequest struct { + Reviews struct { + Nodes []struct { + ID githubv4.ID + Author pendingReviewAuthor + } + PageInfo struct { + HasNextPage githubv4.Boolean + EndCursor githubv4.String + } + } `graphql:"reviews(first: 100, after: $after, states: $states)"` + } `graphql:"pullRequest(number: $prNum)"` + } `graphql:"repository(owner: $owner, name: $name)"` + } + + if err := client.Query(ctx, &getPendingReviewsQuery, vars); err != nil { + return nil, ghErrors.NewGitHubGraphQLErrorResponse(ctx, + "failed to get pending pull request reviews", + err, + ) + } + + for _, review := range getPendingReviewsQuery.Repository.PullRequest.Reviews.Nodes { + if review.Author.id() == getViewerQuery.Viewer.ID { + reviewID := review.ID + return &reviewID, nil + } + } + + if !getPendingReviewsQuery.Repository.PullRequest.Reviews.PageInfo.HasNextPage { + return nil, utils.NewToolResultError("No pending review found for the viewer") + } + vars["after"] = githubv4.NewString(getPendingReviewsQuery.Repository.PullRequest.Reviews.PageInfo.EndCursor) + } +} + // AddCommentToPendingReview creates a tool to add a comment to a pull request review. func AddCommentToPendingReview(t translations.TranslationHelperFunc) inventory.ServerTool { schema := &jsonschema.Schema{ @@ -2387,11 +2542,12 @@ func AddCommentToPendingReview(t translations.TranslationHelperFunc) inventory.S Required: []string{"owner", "repo", "pullNumber", "path", "body", "subjectType"}, } - st := NewTool( + st := NewTool[AddCommentToPendingReviewInput, *RepositoryMessageOutput]( ToolsetMetadataPullRequests, mcp.Tool{ - Name: "add_comment_to_pending_review", - Description: t("TOOL_ADD_COMMENT_TO_PENDING_REVIEW_DESCRIPTION", "Add review comment to the requester's latest pending pull request review. A pending review needs to already exist to call this (check with the user if not sure)."), + Name: "add_comment_to_pending_review", + OutputSchema: pullRequestOutputSchema[RepositoryMessageOutput](), + Description: t("TOOL_ADD_COMMENT_TO_PENDING_REVIEW_DESCRIPTION", "Add review comment to the requester's latest pending pull request review. A pending review needs to already exist to call this (check with the user if not sure)."), Annotations: &mcp.ToolAnnotations{ Title: t("TOOL_ADD_COMMENT_TO_PENDING_REVIEW_USER_TITLE", "Add review comment to the requester's latest pending pull request review"), ReadOnlyHint: false, @@ -2399,7 +2555,11 @@ func AddCommentToPendingReview(t translations.TranslationHelperFunc) inventory.S InputSchema: schema, }, scopes.RequireAll(scopes.Repo), - func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, args map[string]any) (*mcp.CallToolResult, any, error) { + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, input AddCommentToPendingReviewInput) (*mcp.CallToolResult, *RepositoryMessageOutput, error) { + args, err := discussionNotificationArguments(input) + if err != nil { + return nil, nil, err + } owner, err := RequiredParam[string](args, "owner") if err != nil { return utils.NewToolResultError(err.Error()), nil, nil @@ -2469,8 +2629,8 @@ func AddCommentToPendingReview(t translations.TranslationHelperFunc) inventory.S StartLine: startLinePtr, StartSide: startSidePtr, }) - return result, nil, err - }) + return pullRequestMessageResult(result, err) + }, normalizePullRequestArguments("pending_comment")) st.FeatureRule = pullRequestsConsolidatedRule return st } diff --git a/pkg/github/pullrequests_granular.go b/pkg/github/pullrequests_granular.go index e670da9a34..423a53114d 100644 --- a/pkg/github/pullrequests_granular.go +++ b/pkg/github/pullrequests_granular.go @@ -7,24 +7,50 @@ import ( "maps" "strings" - ghErrors "github.com/github/github-mcp-server/pkg/errors" - "github.com/github/github-mcp-server/pkg/inventory" - "github.com/github/github-mcp-server/pkg/scopes" - "github.com/github/github-mcp-server/pkg/translations" - "github.com/github/github-mcp-server/pkg/utils" - gogithub "github.com/google/go-github/v89/github" + ghErrors "github.com/github/github-mcp-server/v2/pkg/errors" + "github.com/github/github-mcp-server/v2/pkg/inventory" + "github.com/github/github-mcp-server/v2/pkg/scopes" + "github.com/github/github-mcp-server/v2/pkg/translations" + "github.com/github/github-mcp-server/v2/pkg/utils" + gogithub "github.com/google/go-github/v92/github" "github.com/google/jsonschema-go/jsonschema" "github.com/modelcontextprotocol/go-sdk/mcp" "github.com/shurcooL/githubv4" ) +func newGranularPullRequestTool[In, Out any]( + toolset inventory.ToolsetMetadata, + tool mcp.Tool, + scopeAccess inventory.ScopeAccess, + handler func(ctx context.Context, deps ToolDependencies, req *mcp.CallToolRequest, args In) (*mcp.CallToolResult, Out, error), + inputNormalizers ...inventory.InputNormalizer, +) inventory.ServerTool { + inputSchema, ok := tool.InputSchema.(*jsonschema.Schema) + if !ok { + panic("granular pull request tool input schema must be a JSON Schema") + } + return NewToolWithSchemaOptions( + toolset, + tool, + scopeAccess, + inventory.TypedSchemaOptions{ + ValidationInputSchema: granularPullRequestValidationSchema(inputSchema), + }, + handler, + inputNormalizers..., + ) +} + // prUpdateTool is a helper to create single-field pull request update tools via REST. -func prUpdateTool( +func prUpdateTool[In interface { + pullRequestCoordinate() GranularPullRequestCoordinate +}]( t translations.TranslationHelperFunc, name, description, title string, extraProps map[string]*jsonschema.Schema, extraRequired []string, - buildRequest func(args map[string]any) (*gogithub.PullRequest, error), + buildRequest func(args In) *gogithub.PullRequest, + normalizer inventory.InputNormalizer, ) inventory.ServerTool { props := map[string]*jsonschema.Schema{ "owner": { @@ -38,14 +64,14 @@ func prUpdateTool( "pullNumber": { Type: "number", Description: "The pull request number", - Minimum: jsonschema.Ptr(1.0), + Minimum: new(1.0), }, } maps.Copy(props, extraProps) required := append([]string{"owner", "repo", "pullNumber"}, extraRequired...) - st := NewTool( + st := newGranularPullRequestTool( ToolsetMetadataPullRequests, mcp.Tool{ Name: name, @@ -53,8 +79,8 @@ func prUpdateTool( Annotations: &mcp.ToolAnnotations{ Title: t("TOOL_"+strings.ToUpper(name)+"_USER_TITLE", title), ReadOnlyHint: false, - DestructiveHint: jsonschema.Ptr(false), - OpenWorldHint: jsonschema.Ptr(true), + DestructiveHint: new(false), + OpenWorldHint: new(true), }, InputSchema: &jsonschema.Schema{ Type: "object", @@ -63,24 +89,10 @@ func prUpdateTool( }, }, scopes.RequireAll(scopes.Repo), - func(ctx context.Context, deps ToolDependencies, _ *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 - } - repo, err := RequiredParam[string](args, "repo") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - pullNumber, err := RequiredInt(args, "pullNumber") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - - prReq, err := buildRequest(args) - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, args In) (*mcp.CallToolResult, *MinimalResponse, error) { + coordinate := args.pullRequestCoordinate() + owner, repo, pullNumber := coordinate.Owner, coordinate.Repo, coordinate.PullNumber + prReq := buildRequest(args) client, err := deps.GetClient(ctx) if err != nil { @@ -93,15 +105,17 @@ func prUpdateTool( } defer func() { _ = resp.Body.Close() }() - r, err := json.Marshal(MinimalResponse{ + output := &MinimalResponse{ ID: fmt.Sprintf("%d", pr.GetID()), URL: pr.GetHTMLURL(), - }) + } + r, err := json.Marshal(output) if err != nil { return utils.NewToolResultErrorFromErr("failed to marshal response", err), nil, nil } - return utils.NewToolResultText(string(r)), nil, nil + return utils.NewToolResultText(string(r)), output, nil }, + normalizer, ) st.FeatureRule = pullRequestsGranularFeatureRule return st @@ -117,13 +131,10 @@ func GranularUpdatePullRequestTitle(t translations.TranslationHelperFunc) invent "title": {Type: "string", Description: "The new title for the pull request"}, }, []string{"title"}, - func(args map[string]any) (*gogithub.PullRequest, error) { - title, err := RequiredParam[string](args, "title") - if err != nil { - return nil, err - } - return &gogithub.PullRequest{Title: &title}, nil + func(args GranularPullRequestTitleInput) *gogithub.PullRequest { + return &gogithub.PullRequest{Title: &args.Title} }, + normalizeGranularPullRequestArguments("title"), ) } @@ -137,13 +148,10 @@ func GranularUpdatePullRequestBody(t translations.TranslationHelperFunc) invento "body": {Type: "string", Description: "The new body content for the pull request"}, }, []string{"body"}, - func(args map[string]any) (*gogithub.PullRequest, error) { - body, err := RequiredParam[string](args, "body") - if err != nil { - return nil, err - } - return &gogithub.PullRequest{Body: &body}, nil + func(args GranularPullRequestBodyInput) *gogithub.PullRequest { + return &gogithub.PullRequest{Body: &args.Body} }, + normalizeGranularPullRequestArguments("body"), ) } @@ -157,23 +165,21 @@ func GranularUpdatePullRequestState(t translations.TranslationHelperFunc) invent "state": { Type: "string", Description: "The new state for the pull request", - Enum: []any{"open", "closed"}, + Enum: GranularPullRequestState("").JSONSchema().Enum, }, }, []string{"state"}, - func(args map[string]any) (*gogithub.PullRequest, error) { - state, err := RequiredParam[string](args, "state") - if err != nil { - return nil, err - } - return &gogithub.PullRequest{State: &state}, nil + func(args GranularPullRequestStateInput) *gogithub.PullRequest { + state := string(args.State) + return &gogithub.PullRequest{State: &state} }, + normalizeGranularPullRequestArguments("state"), ) } // GranularUpdatePullRequestDraftState creates a tool to toggle draft state. func GranularUpdatePullRequestDraftState(t translations.TranslationHelperFunc) inventory.ServerTool { - st := NewTool( + st := newGranularPullRequestTool( ToolsetMetadataPullRequests, mcp.Tool{ Name: "update_pull_request_draft_state", @@ -181,42 +187,23 @@ func GranularUpdatePullRequestDraftState(t translations.TranslationHelperFunc) i Annotations: &mcp.ToolAnnotations{ Title: t("TOOL_UPDATE_PULL_REQUEST_DRAFT_STATE_USER_TITLE", "Update Pull Request Draft State"), ReadOnlyHint: false, - DestructiveHint: jsonschema.Ptr(false), - OpenWorldHint: jsonschema.Ptr(true), + DestructiveHint: new(false), + OpenWorldHint: new(true), }, InputSchema: &jsonschema.Schema{ Type: "object", Properties: map[string]*jsonschema.Schema{ "owner": {Type: "string", Description: "Repository owner (username or organization)"}, "repo": {Type: "string", Description: "Repository name"}, - "pullNumber": {Type: "number", Description: "The pull request number", Minimum: jsonschema.Ptr(1.0)}, + "pullNumber": {Type: "number", Description: "The pull request number", Minimum: new(1.0)}, "draft": {Type: "boolean", Description: "Set to true to convert to draft, false to mark as ready for review"}, }, Required: []string{"owner", "repo", "pullNumber", "draft"}, }, }, scopes.RequireAll(scopes.Repo), - func(ctx context.Context, deps ToolDependencies, _ *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 - } - repo, err := RequiredParam[string](args, "repo") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - pullNumber, err := RequiredInt(args, "pullNumber") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - // Use presence check + OptionalParam since RequiredParam rejects false (zero-value for bool) - if _, ok := args["draft"]; !ok { - return utils.NewToolResultError("missing required parameter: draft"), nil, nil - } - draft, err := OptionalParam[bool](args, "draft") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, args GranularPullRequestDraftInput) (*mcp.CallToolResult, *RepositoryMessageOutput, error) { + owner, repo, pullNumber, draft := args.Owner, args.Repo, args.PullNumber, args.Draft gqlClient, err := deps.GetGQLClient(ctx) if err != nil { @@ -253,7 +240,7 @@ func GranularUpdatePullRequestDraftState(t translations.TranslationHelperFunc) i }, nil); err != nil { return ghErrors.NewGitHubGraphQLErrorResponse(ctx, "failed to convert to draft", err), nil, nil } - return utils.NewToolResultText("pull request converted to draft"), nil, nil + return pullRequestMessageResult(utils.NewToolResultText("pull request converted to draft"), nil) } var mutation struct { @@ -269,8 +256,9 @@ func GranularUpdatePullRequestDraftState(t translations.TranslationHelperFunc) i }, nil); err != nil { return ghErrors.NewGitHubGraphQLErrorResponse(ctx, "failed to mark ready for review", err), nil, nil } - return utils.NewToolResultText("pull request marked as ready for review"), nil, nil + return pullRequestMessageResult(utils.NewToolResultText("pull request marked as ready for review"), nil) }, + normalizeGranularPullRequestArguments("draft"), ) st.FeatureRule = pullRequestsGranularFeatureRule return st @@ -278,7 +266,7 @@ func GranularUpdatePullRequestDraftState(t translations.TranslationHelperFunc) i // GranularRequestPullRequestReviewers creates a tool to request reviewers. func GranularRequestPullRequestReviewers(t translations.TranslationHelperFunc) inventory.ServerTool { - st := NewTool( + st := newGranularPullRequestTool( ToolsetMetadataPullRequests, mcp.Tool{ Name: "request_pull_request_reviewers", @@ -286,15 +274,15 @@ func GranularRequestPullRequestReviewers(t translations.TranslationHelperFunc) i Annotations: &mcp.ToolAnnotations{ Title: t("TOOL_REQUEST_PULL_REQUEST_REVIEWERS_USER_TITLE", "Request Pull Request Reviewers"), ReadOnlyHint: false, - DestructiveHint: jsonschema.Ptr(false), - OpenWorldHint: jsonschema.Ptr(true), + DestructiveHint: new(false), + OpenWorldHint: new(true), }, InputSchema: &jsonschema.Schema{ Type: "object", Properties: map[string]*jsonschema.Schema{ "owner": {Type: "string", Description: "Repository owner (username or organization)"}, "repo": {Type: "string", Description: "Repository name"}, - "pullNumber": {Type: "number", Description: "The pull request number", Minimum: jsonschema.Ptr(1.0)}, + "pullNumber": {Type: "number", Description: "The pull request number", Minimum: new(1.0)}, "reviewers": { Type: "array", Description: "GitHub usernames or ORG/team-slug team reviewers to request reviews from", @@ -305,27 +293,9 @@ func GranularRequestPullRequestReviewers(t translations.TranslationHelperFunc) i }, }, scopes.RequireAll(scopes.Repo), - func(ctx context.Context, deps ToolDependencies, _ *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 - } - repo, err := RequiredParam[string](args, "repo") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - pullNumber, err := RequiredInt(args, "pullNumber") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - reviewers, err := OptionalStringArrayParam(args, "reviewers") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - if len(reviewers) == 0 { - return utils.NewToolResultError("missing required parameter: reviewers"), nil, nil - } - userReviewers, teamReviewers := splitPullRequestReviewers(reviewers) + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, args GranularPullRequestReviewersInput) (*mcp.CallToolResult, *MinimalResponse, error) { + owner, repo, pullNumber := args.Owner, args.Repo, args.PullNumber + userReviewers, teamReviewers := splitPullRequestReviewers(args.Reviewers) client, err := deps.GetClient(ctx) if err != nil { @@ -341,15 +311,17 @@ func GranularRequestPullRequestReviewers(t translations.TranslationHelperFunc) i } defer func() { _ = resp.Body.Close() }() - r, err := json.Marshal(MinimalResponse{ + output := &MinimalResponse{ ID: fmt.Sprintf("%d", pr.GetID()), URL: pr.GetHTMLURL(), - }) + } + r, err := json.Marshal(output) if err != nil { return utils.NewToolResultErrorFromErr("failed to marshal response", err), nil, nil } - return utils.NewToolResultText(string(r)), nil, nil + return utils.NewToolResultText(string(r)), output, nil }, + normalizeGranularPullRequestArguments("reviewers"), ) st.FeatureRule = pullRequestsGranularFeatureRule return st @@ -373,7 +345,7 @@ func splitPullRequestReviewers(reviewers []string) ([]string, []string) { // GranularCreatePullRequestReview creates a tool to create a PR review. func GranularCreatePullRequestReview(t translations.TranslationHelperFunc) inventory.ServerTool { - st := NewTool( + st := newGranularPullRequestTool( ToolsetMetadataPullRequests, mcp.Tool{ Name: "create_pull_request_review", @@ -381,39 +353,26 @@ func GranularCreatePullRequestReview(t translations.TranslationHelperFunc) inven Annotations: &mcp.ToolAnnotations{ Title: t("TOOL_CREATE_PULL_REQUEST_REVIEW_USER_TITLE", "Create Pull Request Review"), ReadOnlyHint: false, - DestructiveHint: jsonschema.Ptr(false), - OpenWorldHint: jsonschema.Ptr(true), + DestructiveHint: new(false), + OpenWorldHint: new(true), }, InputSchema: &jsonschema.Schema{ Type: "object", Properties: map[string]*jsonschema.Schema{ "owner": {Type: "string", Description: "Repository owner (username or organization)"}, "repo": {Type: "string", Description: "Repository name"}, - "pullNumber": {Type: "number", Description: "The pull request number", Minimum: jsonschema.Ptr(1.0)}, + "pullNumber": {Type: "number", Description: "The pull request number", Minimum: new(1.0)}, "body": {Type: "string", Description: "The review body text (optional)"}, - "event": {Type: "string", Description: "The review action to perform. If omitted, creates a pending review.", Enum: []any{"APPROVE", "REQUEST_CHANGES", "COMMENT"}}, + "event": {Type: "string", Description: "The review action to perform. If omitted, creates a pending review.", Enum: GranularPullRequestReviewEvent("").JSONSchema().Enum}, "commitID": {Type: "string", Description: "The SHA of the commit to review (optional, defaults to latest)"}, }, Required: []string{"owner", "repo", "pullNumber"}, }, }, scopes.RequireAll(scopes.Repo), - func(ctx context.Context, deps ToolDependencies, _ *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 - } - repo, err := RequiredParam[string](args, "repo") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - pullNumber, err := RequiredInt(args, "pullNumber") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - body, _ := OptionalParam[string](args, "body") - event, _ := OptionalParam[string](args, "event") - commitID, _ := OptionalParam[string](args, "commitID") + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, args GranularCreatePullRequestReviewInput) (*mcp.CallToolResult, *RepositoryMessageOutput, error) { + owner, repo, pullNumber := args.Owner, args.Repo, args.PullNumber + body, event, commitID := args.Body, string(args.Event), args.CommitID gqlClient, err := deps.GetGQLClient(ctx) if err != nil { @@ -433,8 +392,9 @@ func GranularCreatePullRequestReview(t translations.TranslationHelperFunc) inven Event: event, CommitID: commitIDPtr, }) - return result, nil, err + return pullRequestMessageResult(result, err) }, + normalizeGranularPullRequestArguments("create_review"), ) st.FeatureRule = pullRequestsGranularFeatureRule return st @@ -442,7 +402,7 @@ func GranularCreatePullRequestReview(t translations.TranslationHelperFunc) inven // GranularSubmitPendingPullRequestReview creates a tool to submit a pending review. func GranularSubmitPendingPullRequestReview(t translations.TranslationHelperFunc) inventory.ServerTool { - st := NewTool( + st := newGranularPullRequestTool( ToolsetMetadataPullRequests, mcp.Tool{ Name: "submit_pending_pull_request_review", @@ -450,40 +410,24 @@ func GranularSubmitPendingPullRequestReview(t translations.TranslationHelperFunc Annotations: &mcp.ToolAnnotations{ Title: t("TOOL_SUBMIT_PENDING_PULL_REQUEST_REVIEW_USER_TITLE", "Submit Pending Pull Request Review"), ReadOnlyHint: false, - DestructiveHint: jsonschema.Ptr(false), - OpenWorldHint: jsonschema.Ptr(true), + DestructiveHint: new(false), + OpenWorldHint: new(true), }, InputSchema: &jsonschema.Schema{ Type: "object", Properties: map[string]*jsonschema.Schema{ "owner": {Type: "string", Description: "Repository owner (username or organization)"}, "repo": {Type: "string", Description: "Repository name"}, - "pullNumber": {Type: "number", Description: "The pull request number", Minimum: jsonschema.Ptr(1.0)}, - "event": {Type: "string", Description: "The review action to perform", Enum: []any{"APPROVE", "REQUEST_CHANGES", "COMMENT"}}, + "pullNumber": {Type: "number", Description: "The pull request number", Minimum: new(1.0)}, + "event": {Type: "string", Description: "The review action to perform", Enum: GranularPullRequestReviewEvent("").JSONSchema().Enum}, "body": {Type: "string", Description: "The review body text (optional)"}, }, Required: []string{"owner", "repo", "pullNumber", "event"}, }, }, scopes.RequireAll(scopes.Repo), - func(ctx context.Context, deps ToolDependencies, _ *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 - } - repo, err := RequiredParam[string](args, "repo") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - pullNumber, err := RequiredInt(args, "pullNumber") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - event, err := RequiredParam[string](args, "event") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - body, _ := OptionalParam[string](args, "body") + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, args GranularSubmitPullRequestReviewInput) (*mcp.CallToolResult, *RepositoryMessageOutput, error) { + owner, repo, pullNumber, event, body := args.Owner, args.Repo, args.PullNumber, string(args.Event), args.Body gqlClient, err := deps.GetGQLClient(ctx) if err != nil { @@ -497,8 +441,9 @@ func GranularSubmitPendingPullRequestReview(t translations.TranslationHelperFunc Event: event, Body: body, }) - return result, nil, err + return pullRequestMessageResult(result, err) }, + normalizeGranularPullRequestArguments("submit_review"), ) st.FeatureRule = pullRequestsGranularFeatureRule return st @@ -506,7 +451,7 @@ func GranularSubmitPendingPullRequestReview(t translations.TranslationHelperFunc // GranularDeletePendingPullRequestReview creates a tool to delete a pending review. func GranularDeletePendingPullRequestReview(t translations.TranslationHelperFunc) inventory.ServerTool { - st := NewTool( + st := newGranularPullRequestTool( ToolsetMetadataPullRequests, mcp.Tool{ Name: "delete_pending_pull_request_review", @@ -514,33 +459,22 @@ func GranularDeletePendingPullRequestReview(t translations.TranslationHelperFunc Annotations: &mcp.ToolAnnotations{ Title: t("TOOL_DELETE_PENDING_PULL_REQUEST_REVIEW_USER_TITLE", "Delete Pending Pull Request Review"), ReadOnlyHint: false, - DestructiveHint: jsonschema.Ptr(true), - OpenWorldHint: jsonschema.Ptr(true), + DestructiveHint: new(true), + OpenWorldHint: new(true), }, InputSchema: &jsonschema.Schema{ Type: "object", Properties: map[string]*jsonschema.Schema{ "owner": {Type: "string", Description: "Repository owner (username or organization)"}, "repo": {Type: "string", Description: "Repository name"}, - "pullNumber": {Type: "number", Description: "The pull request number", Minimum: jsonschema.Ptr(1.0)}, + "pullNumber": {Type: "number", Description: "The pull request number", Minimum: new(1.0)}, }, Required: []string{"owner", "repo", "pullNumber"}, }, }, scopes.RequireAll(scopes.Repo), - func(ctx context.Context, deps ToolDependencies, _ *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 - } - repo, err := RequiredParam[string](args, "repo") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - pullNumber, err := RequiredInt(args, "pullNumber") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, args GranularPullRequestCoordinate) (*mcp.CallToolResult, *RepositoryMessageOutput, error) { + owner, repo, pullNumber := args.Owner, args.Repo, args.PullNumber gqlClient, err := deps.GetGQLClient(ctx) if err != nil { @@ -552,8 +486,9 @@ func GranularDeletePendingPullRequestReview(t translations.TranslationHelperFunc Repo: repo, PullNumber: int32(pullNumber), // #nosec G115 - PR numbers are always small positive integers }) - return result, nil, err + return pullRequestMessageResult(result, err) }, + normalizeGranularPullRequestArguments("delete_review"), ) st.FeatureRule = pullRequestsGranularFeatureRule return st @@ -561,7 +496,7 @@ func GranularDeletePendingPullRequestReview(t translations.TranslationHelperFunc // GranularAddPullRequestReviewComment creates a tool to add a review comment. func GranularAddPullRequestReviewComment(t translations.TranslationHelperFunc) inventory.ServerTool { - st := NewTool( + st := newGranularPullRequestTool( ToolsetMetadataPullRequests, mcp.Tool{ Name: "add_pull_request_review_comment", @@ -569,62 +504,29 @@ func GranularAddPullRequestReviewComment(t translations.TranslationHelperFunc) i Annotations: &mcp.ToolAnnotations{ Title: t("TOOL_ADD_PULL_REQUEST_REVIEW_COMMENT_USER_TITLE", "Add Pull Request Review Comment"), ReadOnlyHint: false, - DestructiveHint: jsonschema.Ptr(false), - OpenWorldHint: jsonschema.Ptr(true), + DestructiveHint: new(false), + OpenWorldHint: new(true), }, InputSchema: &jsonschema.Schema{ Type: "object", Properties: map[string]*jsonschema.Schema{ "owner": {Type: "string", Description: "Repository owner (username or organization)"}, "repo": {Type: "string", Description: "Repository name"}, - "pullNumber": {Type: "number", Description: "The pull request number", Minimum: jsonschema.Ptr(1.0)}, + "pullNumber": {Type: "number", Description: "The pull request number", Minimum: new(1.0)}, "path": {Type: "string", Description: "The relative path of the file to comment on"}, "body": {Type: "string", Description: "The comment body"}, - "subjectType": {Type: "string", Description: "The subject type of the comment", Enum: []any{"FILE", "LINE"}}, + "subjectType": {Type: "string", Description: "The subject type of the comment", Enum: GranularPullRequestCommentSubject("").JSONSchema().Enum}, "line": {Type: "number", Description: "The line number in the diff to comment on (optional)"}, - "side": {Type: "string", Description: "The side of the diff to comment on (optional)", Enum: []any{"LEFT", "RIGHT"}}, + "side": {Type: "string", Description: "The side of the diff to comment on (optional)", Enum: GranularPullRequestDiffSide("").JSONSchema().Enum}, "startLine": {Type: "number", Description: "The start line of a multi-line comment (optional)"}, - "startSide": {Type: "string", Description: "The start side of a multi-line comment (optional)", Enum: []any{"LEFT", "RIGHT"}}, + "startSide": {Type: "string", Description: "The start side of a multi-line comment (optional)", Enum: GranularPullRequestDiffSide("").JSONSchema().Enum}, }, Required: []string{"owner", "repo", "pullNumber", "path", "body", "subjectType"}, }, }, scopes.RequireAll(scopes.Repo), - func(ctx context.Context, deps ToolDependencies, _ *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 - } - repo, err := RequiredParam[string](args, "repo") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - pullNumber, err := RequiredInt(args, "pullNumber") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - path, err := RequiredParam[string](args, "path") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - body, err := RequiredParam[string](args, "body") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - subjectType, err := RequiredParam[string](args, "subjectType") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - line, err := OptionalIntParam(args, "line") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - side, _ := OptionalParam[string](args, "side") - startLine, err := OptionalIntParam(args, "startLine") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - startSide, _ := OptionalParam[string](args, "startSide") + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, args GranularPullRequestReviewCommentInput) (*mcp.CallToolResult, *RepositoryMessageOutput, error) { + owner, repo, pullNumber := args.Owner, args.Repo, args.PullNumber gqlClient, err := deps.GetGQLClient(ctx) if err != nil { @@ -633,21 +535,23 @@ func GranularAddPullRequestReviewComment(t translations.TranslationHelperFunc) i // Convert optional int params to *int32 for the helper var linePtr, startLinePtr *int32 - if line != 0 { - l := int32(line) // #nosec G115 + if args.Line != nil && *args.Line != 0 { + l := int32(*args.Line) // #nosec G115 linePtr = &l } - if startLine != 0 { - sl := int32(startLine) // #nosec G115 + if args.StartLine != nil && *args.StartLine != 0 { + sl := int32(*args.StartLine) // #nosec G115 startLinePtr = &sl } // Convert optional string params: pass nil (not empty string) when absent var sidePtr, startSidePtr *string - if side != "" { + if args.Side != nil && *args.Side != "" { + side := string(*args.Side) sidePtr = &side } - if startSide != "" { + if args.StartSide != nil && *args.StartSide != "" { + startSide := string(*args.StartSide) startSidePtr = &startSide } @@ -655,16 +559,17 @@ func GranularAddPullRequestReviewComment(t translations.TranslationHelperFunc) i Owner: owner, Repo: repo, PullNumber: int32(pullNumber), // #nosec G115 - PR numbers are always small positive integers - Path: path, - Body: body, - SubjectType: subjectType, + Path: args.Path, + Body: args.Body, + SubjectType: string(args.SubjectType), Line: linePtr, Side: sidePtr, StartLine: startLinePtr, StartSide: startSidePtr, }) - return result, nil, err + return pullRequestMessageResult(result, err) }, + normalizeGranularPullRequestArguments("comment"), ) st.FeatureRule = pullRequestsGranularFeatureRule return st @@ -701,7 +606,7 @@ func granularResolveReviewThread(t translations.TranslationHelperFunc, withResol } } - st := NewTool( + st := newGranularPullRequestTool( ToolsetMetadataPullRequests, mcp.Tool{ Name: "resolve_review_thread", @@ -709,8 +614,8 @@ func granularResolveReviewThread(t translations.TranslationHelperFunc, withResol Annotations: &mcp.ToolAnnotations{ Title: t("TOOL_RESOLVE_REVIEW_THREAD_USER_TITLE", "Resolve Review Thread"), ReadOnlyHint: false, - DestructiveHint: jsonschema.Ptr(false), - OpenWorldHint: jsonschema.Ptr(true), + DestructiveHint: new(false), + OpenWorldHint: new(true), }, InputSchema: &jsonschema.Schema{ Type: "object", @@ -719,20 +624,11 @@ func granularResolveReviewThread(t translations.TranslationHelperFunc, withResol }, }, scopes.RequireAll(scopes.Repo), - func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, args map[string]any) (*mcp.CallToolResult, any, error) { - threadID, err := RequiredParam[string](args, "threadID") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, args GranularResolveReviewThreadInput) (*mcp.CallToolResult, *RepositoryMessageOutput, error) { + threadID := args.ThreadID var resolutionReasonPtr *string if withResolutionReason { - resolutionReason, hasResolutionReason, err := OptionalParamOK[string](args, "resolutionReason") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - if hasResolutionReason { - resolutionReasonPtr = &resolutionReason - } + resolutionReasonPtr = args.ResolutionReason } gqlClient, err := deps.GetGQLClient(ctx) @@ -742,11 +638,12 @@ func granularResolveReviewThread(t translations.TranslationHelperFunc, withResol if !withResolutionReason { result, err := ResolveReviewThread(ctx, gqlClient, threadID, true) - return result, nil, err + return pullRequestMessageResult(result, err) } result, err := ResolveReviewThreadWithReason(ctx, gqlClient, threadID, resolutionReasonPtr, true) - return result, nil, err + return pullRequestMessageResult(result, err) }, + normalizeGranularResolveReviewThreadArguments(withResolutionReason), ) switch { case withResolutionReason: @@ -773,7 +670,7 @@ func granularResolveReviewThread(t translations.TranslationHelperFunc, withResol // GranularUnresolveReviewThread creates a tool to unresolve a review thread. func GranularUnresolveReviewThread(t translations.TranslationHelperFunc) inventory.ServerTool { - st := NewTool( + st := newGranularPullRequestTool( ToolsetMetadataPullRequests, mcp.Tool{ Name: "unresolve_review_thread", @@ -781,8 +678,8 @@ func GranularUnresolveReviewThread(t translations.TranslationHelperFunc) invento Annotations: &mcp.ToolAnnotations{ Title: t("TOOL_UNRESOLVE_REVIEW_THREAD_USER_TITLE", "Unresolve Review Thread"), ReadOnlyHint: false, - DestructiveHint: jsonschema.Ptr(false), - OpenWorldHint: jsonschema.Ptr(true), + DestructiveHint: new(false), + OpenWorldHint: new(true), }, InputSchema: &jsonschema.Schema{ Type: "object", @@ -796,11 +693,8 @@ func GranularUnresolveReviewThread(t translations.TranslationHelperFunc) invento }, }, scopes.RequireAll(scopes.Repo), - func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, args map[string]any) (*mcp.CallToolResult, any, error) { - threadID, err := RequiredParam[string](args, "threadID") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, args GranularReviewThreadInput) (*mcp.CallToolResult, *RepositoryMessageOutput, error) { + threadID := args.ThreadID gqlClient, err := deps.GetGQLClient(ctx) if err != nil { @@ -808,8 +702,9 @@ func GranularUnresolveReviewThread(t translations.TranslationHelperFunc) invento } result, err := ResolveReviewThread(ctx, gqlClient, threadID, false) - return result, nil, err + return pullRequestMessageResult(result, err) }, + normalizeGranularPullRequestArguments("unresolve"), ) st.FeatureRule = pullRequestsGranularFeatureRule return st @@ -817,16 +712,17 @@ func GranularUnresolveReviewThread(t translations.TranslationHelperFunc) invento // GranularAddPullRequestReviewCommentReaction adds a reaction to a pull request review comment. func GranularAddPullRequestReviewCommentReaction(t translations.TranslationHelperFunc) inventory.ServerTool { - st := NewTool( + st := newGranularPullRequestTool( ToolsetMetadataPullRequests, mcp.Tool{ - Name: "add_pull_request_review_comment_reaction", - Description: t("TOOL_ADD_PULL_REQUEST_REVIEW_COMMENT_REACTION_DESCRIPTION", "Add a reaction to a pull request review comment."), + Name: "add_pull_request_review_comment_reaction", + OutputSchema: minimalPullRequestCommentReactionSchema(), + Description: t("TOOL_ADD_PULL_REQUEST_REVIEW_COMMENT_REACTION_DESCRIPTION", "Add a reaction to a pull request review comment."), Annotations: &mcp.ToolAnnotations{ Title: t("TOOL_ADD_PULL_REQUEST_REVIEW_COMMENT_REACTION_USER_TITLE", "Add Pull Request Review Comment Reaction"), ReadOnlyHint: false, - DestructiveHint: jsonschema.Ptr(false), - OpenWorldHint: jsonschema.Ptr(true), + DestructiveHint: new(false), + OpenWorldHint: new(true), }, InputSchema: &jsonschema.Schema{ Type: "object", @@ -842,56 +738,43 @@ func GranularAddPullRequestReviewCommentReaction(t translations.TranslationHelpe "comment_id": { Type: "number", Description: "The numeric pull request review comment ID. Use the number from a #discussion_r... anchor, not the GraphQL thread node ID (PRRT_...).", - Minimum: jsonschema.Ptr(1.0), + Minimum: new(1.0), }, "content": { Type: "string", Description: "The emoji reaction type", - Enum: []any{"+1", "-1", "laugh", "confused", "heart", "hooray", "rocket", "eyes"}, + Enum: PullRequestCommentReactionType("").JSONSchema().Enum, }, }, Required: []string{"owner", "repo", "comment_id", "content"}, }, }, scopes.RequireAll(scopes.Repo), - func(ctx context.Context, deps ToolDependencies, _ *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 - } - repo, err := RequiredParam[string](args, "repo") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - commentID, err := RequiredBigInt(args, "comment_id") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - content, err := RequiredParam[string](args, "content") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, args GranularAddPullRequestCommentReactionInput) (*mcp.CallToolResult, *MinimalPullRequestCommentReaction, error) { + owner, repo, commentID, content := args.Owner, args.Repo, args.CommentID, args.Content client, err := deps.GetClient(ctx) if err != nil { return utils.NewToolResultErrorFromErr("failed to get GitHub client", err), nil, nil } - reaction, resp, err := client.Reactions.CreatePullRequestCommentReaction(ctx, owner, repo, commentID, content) + reaction, resp, err := client.Reactions.CreatePullRequestCommentReaction(ctx, owner, repo, commentID, string(content)) if err != nil { return ghErrors.NewGitHubAPIErrorResponse(ctx, "failed to add reaction to pull request review comment", resp, err), nil, nil } defer func() { _ = resp.Body.Close() }() - r, err := json.Marshal(MinimalResponse{ + output := &MinimalResponse{ ID: fmt.Sprintf("%d", reaction.GetID()), URL: fmt.Sprintf("%srepos/%s/%s/pulls/comments/%d/reactions/%d", client.BaseURL(), owner, repo, commentID, reaction.GetID()), - }) + } + r, err := json.Marshal(output) if err != nil { return utils.NewToolResultErrorFromErr("failed to marshal response", err), nil, nil } - return utils.NewToolResultText(string(r)), nil, nil + return utils.NewToolResultText(string(r)), output, nil }, + normalizeGranularPullRequestArguments("add_reaction"), ) st.FeatureRule = pullRequestsGranularFeatureRule return st @@ -899,7 +782,7 @@ func GranularAddPullRequestReviewCommentReaction(t translations.TranslationHelpe // GranularRemovePullRequestReviewCommentReaction removes a reaction from a pull request review comment. func GranularRemovePullRequestReviewCommentReaction(t translations.TranslationHelperFunc) inventory.ServerTool { - st := NewTool( + st := newGranularPullRequestTool( ToolsetMetadataPullRequests, mcp.Tool{ Name: "remove_pull_request_review_comment_reaction", @@ -907,8 +790,8 @@ func GranularRemovePullRequestReviewCommentReaction(t translations.TranslationHe Annotations: &mcp.ToolAnnotations{ Title: t("TOOL_REMOVE_PULL_REQUEST_REVIEW_COMMENT_REACTION_USER_TITLE", "Remove Pull Request Review Comment Reaction"), ReadOnlyHint: false, - DestructiveHint: jsonschema.Ptr(true), - OpenWorldHint: jsonschema.Ptr(true), + DestructiveHint: new(true), + OpenWorldHint: new(true), }, InputSchema: &jsonschema.Schema{ Type: "object", @@ -924,35 +807,20 @@ func GranularRemovePullRequestReviewCommentReaction(t translations.TranslationHe "comment_id": { Type: "number", Description: "The numeric pull request review comment ID. Use the number from a #discussion_r... anchor, not the GraphQL thread node ID (PRRT_...).", - Minimum: jsonschema.Ptr(1.0), + Minimum: new(1.0), }, "reaction_id": { Type: "number", Description: "The reaction ID to remove", - Minimum: jsonschema.Ptr(1.0), + Minimum: new(1.0), }, }, Required: []string{"owner", "repo", "comment_id", "reaction_id"}, }, }, scopes.RequireAll(scopes.Repo), - func(ctx context.Context, deps ToolDependencies, _ *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 - } - repo, err := RequiredParam[string](args, "repo") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - commentID, err := RequiredBigInt(args, "comment_id") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - reactionID, err := RequiredBigInt(args, "reaction_id") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, args GranularRemovePullRequestCommentReactionInput) (*mcp.CallToolResult, *RepositoryMessageOutput, error) { + owner, repo, commentID, reactionID := args.Owner, args.Repo, args.CommentID, args.ReactionID client, err := deps.GetClient(ctx) if err != nil { @@ -967,9 +835,30 @@ func GranularRemovePullRequestReviewCommentReaction(t translations.TranslationHe return ghErrors.NewGitHubAPIErrorResponse(ctx, "failed to remove reaction from pull request review comment", resp, err), nil, nil } - return utils.NewToolResultText("reaction successfully removed from pull request review comment"), nil, nil + return pullRequestMessageResult(utils.NewToolResultText("reaction successfully removed from pull request review comment"), nil) }, + normalizeGranularPullRequestArguments("remove_reaction"), ) st.FeatureRule = pullRequestsGranularFeatureRule return st } + +// GranularHidePullRequestReviewComment hides (minimizes) an inline pull request review comment. +func GranularHidePullRequestReviewComment(t translations.TranslationHelperFunc) inventory.ServerTool { + return commentVisibilityTool(t, pullRequestReviewCommentVisibilityTarget, true) +} + +// GranularUnhidePullRequestReviewComment unhides (unminimizes) an inline pull request review comment. +func GranularUnhidePullRequestReviewComment(t translations.TranslationHelperFunc) inventory.ServerTool { + return commentVisibilityTool(t, pullRequestReviewCommentVisibilityTarget, false) +} + +// GranularHidePullRequestReview hides (minimizes) the body of a pull request review. +func GranularHidePullRequestReview(t translations.TranslationHelperFunc) inventory.ServerTool { + return commentVisibilityTool(t, pullRequestReviewVisibilityTarget, true) +} + +// GranularUnhidePullRequestReview unhides (unminimizes) the body of a pull request review. +func GranularUnhidePullRequestReview(t translations.TranslationHelperFunc) inventory.ServerTool { + return commentVisibilityTool(t, pullRequestReviewVisibilityTarget, false) +} diff --git a/pkg/github/pullrequests_sha_pinning_test.go b/pkg/github/pullrequests_sha_pinning_test.go index 77e2d5152a..0995855f87 100644 --- a/pkg/github/pullrequests_sha_pinning_test.go +++ b/pkg/github/pullrequests_sha_pinning_test.go @@ -5,8 +5,8 @@ import ( "net/http" "testing" - "github.com/github/github-mcp-server/pkg/translations" - "github.com/google/go-github/v89/github" + "github.com/github/github-mcp-server/v2/pkg/translations" + "github.com/google/go-github/v92/github" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -17,9 +17,9 @@ func Test_MergePullRequestSHAPinning(t *testing.T) { const pinnedSHA = "0123456789abcdef0123456789abcdef01234567" mockMergeResult := &github.PullRequestMergeResult{ - SHA: github.Ptr("merge-result-sha"), - Merged: github.Ptr(true), - Message: github.Ptr("Pull Request successfully merged"), + SHA: new("merge-result-sha"), + Merged: new(true), + Message: new("Pull Request successfully merged"), } t.Run("expected head SHA is sent as REST sha", func(t *testing.T) { diff --git a/pkg/github/pullrequests_test.go b/pkg/github/pullrequests_test.go index c0e392aea6..546094910c 100644 --- a/pkg/github/pullrequests_test.go +++ b/pkg/github/pullrequests_test.go @@ -9,11 +9,13 @@ import ( "testing" "time" - "github.com/github/github-mcp-server/internal/githubv4mock" - "github.com/github/github-mcp-server/internal/toolsnaps" - "github.com/github/github-mcp-server/pkg/translations" - "github.com/google/go-github/v89/github" + "github.com/github/github-mcp-server/v2/internal/githubv4mock" + "github.com/github/github-mcp-server/v2/internal/toolsnaps" + "github.com/github/github-mcp-server/v2/pkg/inventory" + "github.com/github/github-mcp-server/v2/pkg/translations" + "github.com/google/go-github/v92/github" "github.com/google/jsonschema-go/jsonschema" + "github.com/modelcontextprotocol/go-sdk/mcp" "github.com/shurcooL/githubv4" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -36,20 +38,20 @@ func Test_GetPullRequest(t *testing.T) { // Setup mock PR for success case mockPR := &github.PullRequest{ - Number: github.Ptr(42), - Title: github.Ptr("Test PR"), - State: github.Ptr("open"), - HTMLURL: github.Ptr("https://github.com/owner/repo/pull/42"), + Number: new(42), + Title: new("Test PR"), + State: new("open"), + HTMLURL: new("https://github.com/owner/repo/pull/42"), Head: &github.PullRequestBranch{ - SHA: github.Ptr("abcd1234"), - Ref: github.Ptr("feature-branch"), + SHA: new("abcd1234"), + Ref: new("feature-branch"), }, Base: &github.PullRequestBranch{ - Ref: github.Ptr("main"), + Ref: new("main"), }, - Body: github.Ptr("This is a test PR"), + Body: new("This is a test PR"), User: &github.User{ - Login: github.Ptr("testuser"), + Login: new("testuser"), }, } @@ -203,32 +205,32 @@ func Test_UpdatePullRequest(t *testing.T) { // Setup mock PR for success case mockUpdatedPR := &github.PullRequest{ - Number: github.Ptr(42), - Title: github.Ptr("Updated Test PR Title"), - State: github.Ptr("open"), - HTMLURL: github.Ptr("https://github.com/owner/repo/pull/42"), - Body: github.Ptr("Updated test PR body."), - MaintainerCanModify: github.Ptr(false), - Draft: github.Ptr(false), + Number: new(42), + Title: new("Updated Test PR Title"), + State: new("open"), + HTMLURL: new("https://github.com/owner/repo/pull/42"), + Body: new("Updated test PR body."), + MaintainerCanModify: new(false), + Draft: new(false), Base: &github.PullRequestBranch{ - Ref: github.Ptr("develop"), + Ref: new("develop"), }, } mockClosedPR := &github.PullRequest{ - Number: github.Ptr(42), - Title: github.Ptr("Test PR"), - State: github.Ptr("closed"), // State updated + Number: new(42), + Title: new("Test PR"), + State: new("closed"), // State updated } // Mock PR for when there are no updates but we still need a response mockPRWithReviewers := &github.PullRequest{ - Number: github.Ptr(42), - Title: github.Ptr("Test PR"), - State: github.Ptr("open"), + Number: new(42), + Title: new("Test PR"), + State: new("open"), RequestedReviewers: []*github.User{ - {Login: github.Ptr("reviewer1")}, - {Login: github.Ptr("reviewer2")}, + {Login: new("reviewer1")}, + {Login: new("reviewer2")}, }, } @@ -430,15 +432,15 @@ func Test_UpdatePullRequest(t *testing.T) { func Test_UpdatePullRequest_Draft(t *testing.T) { // Setup mock PR for success case mockUpdatedPR := &github.PullRequest{ - Number: github.Ptr(42), - Title: github.Ptr("Test PR Title"), - State: github.Ptr("open"), - HTMLURL: github.Ptr("https://github.com/owner/repo/pull/42"), - Body: github.Ptr("Test PR body."), - MaintainerCanModify: github.Ptr(false), - Draft: github.Ptr(false), // Updated to ready for review + Number: new(42), + Title: new("Test PR Title"), + State: new("open"), + HTMLURL: new("https://github.com/owner/repo/pull/42"), + Body: new("Test PR body."), + MaintainerCanModify: new(false), + Draft: new(false), // Updated to ready for review Base: &github.PullRequestBranch{ - Ref: github.Ptr("main"), + Ref: new("main"), }, } @@ -635,16 +637,16 @@ func Test_ListPullRequests(t *testing.T) { // Setup mock PRs for success case mockPRs := []*github.PullRequest{ { - Number: github.Ptr(42), - Title: github.Ptr("First PR"), - State: github.Ptr("open"), - HTMLURL: github.Ptr("https://github.com/owner/repo/pull/42"), + Number: new(42), + Title: new("First PR"), + State: new("open"), + HTMLURL: new("https://github.com/owner/repo/pull/42"), }, { - Number: github.Ptr(43), - Title: github.Ptr("Second PR"), - State: github.Ptr("closed"), - HTMLURL: github.Ptr("https://github.com/owner/repo/pull/43"), + Number: new(43), + Title: new("Second PR"), + State: new("closed"), + HTMLURL: new("https://github.com/owner/repo/pull/43"), }, } @@ -745,6 +747,80 @@ func Test_ListPullRequests(t *testing.T) { } } +func Test_ListPullRequests_MergedState(t *testing.T) { + for _, tc := range []struct { + name string + response string + wantMerged bool + }{ + {"merged list entry", `[{"number":42,"state":"closed","merged_at":"2026-10-08T11:25:51Z"}]`, true}, + {"closed unmerged", `[{"number":42,"state":"closed","merged_at":null}]`, false}, + {"open", `[{"number":42,"state":"open","merged_at":null}]`, false}, + {"explicit true", `[{"number":42,"state":"closed","merged":true}]`, true}, + {"explicit false", `[{"number":42,"state":"closed","merged":false,"merged_at":"2026-10-08T11:25:51Z"}]`, false}, + {"zero timestamp", `[{"number":42,"state":"closed","merged_at":"0001-01-01T00:00:00Z"}]`, false}, + } { + for _, fields := range [][]string{nil, {"number", "merged", "merged_at"}} { + name := "all fields" + if fields != nil { + name = "selected fields" + } + t.Run(tc.name+"/"+name, func(t *testing.T) { + mockedClient := MockHTTPClientWithHandlers(map[string]http.HandlerFunc{ + GetReposPullsByOwnerByRepo: func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, err := w.Write([]byte(tc.response)) + require.NoError(t, err) + }, + }) + deps := BaseDeps{Client: mustNewGHClient(t, mockedClient)} + serverTool := ListPullRequests(translations.NullTranslationHelper) + handler := serverTool.Handler(deps) + args := map[string]any{"owner": "owner", "repo": "repo", "state": "all"} + if fields != nil { + args["fields"] = fields + } + request := createMCPRequest(args) + result, err := handler(ContextWithDeps(t.Context(), deps), &request) + require.NoError(t, err) + require.False(t, result.IsError) + var textPRs []MinimalPullRequest + require.NoError(t, json.Unmarshal([]byte(getTextResult(t, result).Text), &textPRs)) + require.Len(t, textPRs, 1) + assert.Equal(t, tc.wantMerged, textPRs[0].Merged) + + server := mcp.NewServer(&mcp.Implementation{Name: "test-server", Version: "v0.0.1"}, nil) + server.AddReceivingMiddleware(InjectDepsMiddleware(deps)) + serverTool.RegisterFunc(server, deps) + serverTransport, clientTransport := mcp.NewInMemoryTransports() + serverSession, err := server.Connect(t.Context(), serverTransport, nil) + require.NoError(t, err) + t.Cleanup(func() { _ = serverSession.Close() }) + client := mcp.NewClient(&mcp.Implementation{Name: "test-client", Version: "v0.0.1"}, nil) + clientSession, err := client.Connect(t.Context(), clientTransport, &mcp.ClientSessionOptions{ + ProtocolVersion: inventory.ProtocolVersionMultiRoundTrip, + }) + require.NoError(t, err) + t.Cleanup(func() { _ = clientSession.Close() }) + result, err = clientSession.CallTool(t.Context(), &mcp.CallToolParams{ + Name: serverTool.Tool.Name, + Arguments: args, + Meta: mcp.Meta{mcp.MetaKeyProtocolVersion: inventory.ProtocolVersionMultiRoundTrip}, + }) + require.NoError(t, err) + require.False(t, result.IsError) + structured, err := json.Marshal(result.StructuredContent) + require.NoError(t, err) + var typedPRs []ListPullRequestOutput + require.NoError(t, json.Unmarshal(structured, &typedPRs)) + require.Len(t, typedPRs, 1) + require.NotNil(t, typedPRs[0].Merged) + assert.Equal(t, tc.wantMerged, *typedPRs[0].Merged) + }) + } + } +} + func Test_MergePullRequest(t *testing.T) { // Verify tool definition once serverTool := MergePullRequest(translations.NullTranslationHelper) @@ -765,9 +841,9 @@ func Test_MergePullRequest(t *testing.T) { // Setup mock merge result for success case mockMergeResult := &github.PullRequestMergeResult{ - Merged: github.Ptr(true), - Message: github.Ptr("Pull Request successfully merged"), - SHA: github.Ptr("abcd1234efgh5678"), + Merged: new(true), + Message: new("Pull Request successfully merged"), + SHA: new("abcd1234efgh5678"), } tests := []struct { @@ -879,29 +955,29 @@ func Test_SearchPullRequests(t *testing.T) { assert.ElementsMatch(t, schema.Required, []string{"query"}) mockSearchResult := &github.IssuesSearchResult{ - Total: github.Ptr(2), - IncompleteResults: github.Ptr(false), + Total: new(2), + IncompleteResults: new(false), Issues: []*github.Issue{ { - Number: github.Ptr(42), - Title: github.Ptr("Test PR 1"), - Body: github.Ptr("Updated tests."), - State: github.Ptr("open"), - HTMLURL: github.Ptr("https://github.com/owner/repo/pull/1"), - Comments: github.Ptr(5), + Number: new(42), + Title: new("Test PR 1"), + Body: new("Updated tests."), + State: new("open"), + HTMLURL: new("https://github.com/owner/repo/pull/1"), + Comments: new(5), User: &github.User{ - Login: github.Ptr("user1"), + Login: new("user1"), }, }, { - Number: github.Ptr(43), - Title: github.Ptr("Test PR 2"), - Body: github.Ptr("Updated build scripts."), - State: github.Ptr("open"), - HTMLURL: github.Ptr("https://github.com/owner/repo/pull/2"), - Comments: github.Ptr(3), + Number: new(43), + Title: new("Test PR 2"), + Body: new("Updated build scripts."), + State: new("open"), + HTMLURL: new("https://github.com/owner/repo/pull/2"), + Comments: new(3), User: &github.User{ - Login: github.Ptr("user2"), + Login: new("user2"), }, }, }, @@ -1168,20 +1244,20 @@ func Test_GetPullRequestFiles(t *testing.T) { // Setup mock PR files for success case mockFiles := []*github.CommitFile{ { - Filename: github.Ptr("file1.go"), - Status: github.Ptr("modified"), - Additions: github.Ptr(10), - Deletions: github.Ptr(5), - Changes: github.Ptr(15), - Patch: github.Ptr("@@ -1,5 +1,10 @@"), + Filename: new("file1.go"), + Status: new("modified"), + Additions: new(10), + Deletions: new(5), + Changes: new(15), + Patch: new("@@ -1,5 +1,10 @@"), }, { - Filename: github.Ptr("file2.go"), - Status: github.Ptr("added"), - Additions: github.Ptr(20), - Deletions: github.Ptr(0), - Changes: github.Ptr(20), - Patch: github.Ptr("@@ -0,0 +1,20 @@"), + Filename: new("file2.go"), + Status: new("added"), + Additions: new(20), + Deletions: new(0), + Changes: new(20), + Patch: new("@@ -0,0 +1,20 @@"), }, } @@ -1261,8 +1337,8 @@ func Test_GetPullRequestFiles(t *testing.T) { name: "lockdown enabled - author lacks push access", mockedClient: MockHTTPClientWithHandlers(map[string]http.HandlerFunc{ GetReposPullsByOwnerByRepoByPullNumber: mockResponse(t, http.StatusOK, &github.PullRequest{ - Number: github.Ptr(42), - User: &github.User{Login: github.Ptr("reader")}, + Number: new(42), + User: &github.User{Login: new("reader")}, }), }), requestArgs: map[string]any{ @@ -1280,8 +1356,8 @@ func Test_GetPullRequestFiles(t *testing.T) { name: "lockdown enabled - author has push access", mockedClient: MockHTTPClientWithHandlers(map[string]http.HandlerFunc{ GetReposPullsByOwnerByRepoByPullNumber: mockResponse(t, http.StatusOK, &github.PullRequest{ - Number: github.Ptr(42), - User: &github.User{Login: github.Ptr("writer")}, + Number: new(42), + User: &github.User{Login: new("writer")}, }), GetReposPullsFilesByOwnerByRepoByPullNumber: mockResponse(t, http.StatusOK, mockFiles), }), @@ -1391,39 +1467,39 @@ func Test_GetPullRequestCommits(t *testing.T) { authorDate := time.Date(2026, 4, 1, 12, 0, 0, 0, time.UTC) mockCommits := []*github.RepositoryCommit{ { - SHA: github.Ptr("abc123def456"), - HTMLURL: github.Ptr("https://github.com/owner/repo/commit/abc123def456"), + SHA: new("abc123def456"), + HTMLURL: new("https://github.com/owner/repo/commit/abc123def456"), Commit: &github.Commit{ - Message: github.Ptr("feat: add commit listing"), + Message: new("feat: add commit listing"), Author: &github.CommitAuthor{ - Name: github.Ptr("Test User"), - Email: github.Ptr("test@example.com"), + Name: new("Test User"), + Email: new("test@example.com"), Date: &github.Timestamp{Time: authorDate}, }, Committer: &github.CommitAuthor{ - Name: github.Ptr("Merge Bot"), - Email: github.Ptr("merge@example.com"), + Name: new("Merge Bot"), + Email: new("merge@example.com"), Date: &github.Timestamp{Time: authorDate.Add(30 * time.Minute)}, }, }, Author: &github.User{ - Login: github.Ptr("test-user"), - ID: github.Ptr(int64(12345)), - HTMLURL: github.Ptr("https://github.com/test-user"), - AvatarURL: github.Ptr("https://github.com/test-user.png"), + Login: new("test-user"), + ID: new(int64(12345)), + HTMLURL: new("https://github.com/test-user"), + AvatarURL: new("https://github.com/test-user.png"), }, Committer: &github.User{ - Login: github.Ptr("merge-bot"), - ID: github.Ptr(int64(67890)), - HTMLURL: github.Ptr("https://github.com/merge-bot"), - AvatarURL: github.Ptr("https://github.com/merge-bot.png"), + Login: new("merge-bot"), + ID: new(int64(67890)), + HTMLURL: new("https://github.com/merge-bot"), + AvatarURL: new("https://github.com/merge-bot.png"), }, }, { - SHA: github.Ptr("def456abc789"), - HTMLURL: github.Ptr("https://github.com/owner/repo/commit/def456abc789"), + SHA: new("def456abc789"), + HTMLURL: new("https://github.com/owner/repo/commit/def456abc789"), Commit: &github.Commit{ - Message: github.Ptr("fix: handle pagination"), + Message: new("fix: handle pagination"), }, }, } @@ -1504,8 +1580,8 @@ func Test_GetPullRequestCommits(t *testing.T) { name: "lockdown enabled - author lacks push access", mockedClient: MockHTTPClientWithHandlers(map[string]http.HandlerFunc{ GetReposPullsByOwnerByRepoByPullNumber: mockResponse(t, http.StatusOK, &github.PullRequest{ - Number: github.Ptr(42), - User: &github.User{Login: github.Ptr("reader")}, + Number: new(42), + User: &github.User{Login: new("reader")}, }), }), requestArgs: map[string]any{ @@ -1523,8 +1599,8 @@ func Test_GetPullRequestCommits(t *testing.T) { name: "lockdown enabled - author has push access", mockedClient: MockHTTPClientWithHandlers(map[string]http.HandlerFunc{ GetReposPullsByOwnerByRepoByPullNumber: mockResponse(t, http.StatusOK, &github.PullRequest{ - Number: github.Ptr(42), - User: &github.User{Login: github.Ptr("writer")}, + Number: new(42), + User: &github.User{Login: new("writer")}, }), GetReposPullsCommitsByOwnerByRepoByPullNumber: mockResponse(t, http.StatusOK, mockCommits), }), @@ -1543,8 +1619,8 @@ func Test_GetPullRequestCommits(t *testing.T) { name: "lockdown enabled - trusted bot author lacks push access", mockedClient: MockHTTPClientWithHandlers(map[string]http.HandlerFunc{ GetReposPullsByOwnerByRepoByPullNumber: mockResponse(t, http.StatusOK, &github.PullRequest{ - Number: github.Ptr(42), - User: &github.User{Login: github.Ptr("github-actions[bot]")}, + Number: new(42), + User: &github.User{Login: new("github-actions[bot]")}, }), GetReposPullsCommitsByOwnerByRepoByPullNumber: mockResponse(t, http.StatusOK, mockCommits), }), @@ -1653,54 +1729,54 @@ func Test_GetPullRequestStatus(t *testing.T) { // Setup mock PR for successful PR fetch mockPR := &github.PullRequest{ - Number: github.Ptr(42), - Title: github.Ptr("Test PR"), - HTMLURL: github.Ptr("https://github.com/owner/repo/pull/42"), + Number: new(42), + Title: new("Test PR"), + HTMLURL: new("https://github.com/owner/repo/pull/42"), Head: &github.PullRequestBranch{ - SHA: github.Ptr("abcd1234"), - Ref: github.Ptr("feature-branch"), + SHA: new("abcd1234"), + Ref: new("feature-branch"), }, } statusCreatedAt := &github.Timestamp{Time: time.Date(2026, time.August, 11, 9, 30, 0, 0, time.UTC)} statusUpdatedAt := &github.Timestamp{Time: time.Date(2026, time.August, 11, 9, 35, 0, 0, time.UTC)} mockStatus := &github.CombinedStatus{ - Name: github.Ptr("abcd1234"), - State: github.Ptr("success"), - SHA: github.Ptr("abcd1234"), - TotalCount: github.Ptr(2), - CommitURL: github.Ptr("https://api.github.com/repos/owner/repo/commits/abcd1234"), - RepositoryURL: github.Ptr( + Name: new("abcd1234"), + State: new("success"), + SHA: new("abcd1234"), + TotalCount: new(2), + CommitURL: new("https://api.github.com/repos/owner/repo/commits/abcd1234"), + RepositoryURL: new( "https://api.github.com/repos/owner/repo", ), Statuses: []*github.RepoStatus{ { - ID: github.Ptr(int64(101)), - NodeID: github.Ptr("SC_kwDOStatus101"), - URL: github.Ptr("https://api.github.com/repos/owner/repo/statuses/abcd1234"), - State: github.Ptr("success"), - Context: github.Ptr("continuous-integration/travis-ci"), - Description: github.Ptr("Build succeeded"), - TargetURL: github.Ptr("https://travis-ci.org/owner/repo/builds/123"), - AvatarURL: github.Ptr("https://avatars.githubusercontent.com/in/123"), + ID: new(int64(101)), + NodeID: new("SC_kwDOStatus101"), + URL: new("https://api.github.com/repos/owner/repo/statuses/abcd1234"), + State: new("success"), + Context: new("continuous-integration/travis-ci"), + Description: new("Build succeeded"), + TargetURL: new("https://travis-ci.org/owner/repo/builds/123"), + AvatarURL: new("https://avatars.githubusercontent.com/in/123"), Creator: &github.User{ - Login: github.Ptr("ci-bot"), + Login: new("ci-bot"), }, CreatedAt: statusCreatedAt, UpdatedAt: statusUpdatedAt, }, { - State: github.Ptr("success"), - Context: github.Ptr("codecov/patch"), - Description: github.Ptr("Coverage increased"), - TargetURL: github.Ptr("https://codecov.io/gh/owner/repo/pull/42"), + State: new("success"), + Context: new("codecov/patch"), + Description: new("Coverage increased"), + TargetURL: new("https://codecov.io/gh/owner/repo/pull/42"), }, }, } emptyStatus := &github.CombinedStatus{ - State: github.Ptr("pending"), - SHA: github.Ptr("abcd1234"), - TotalCount: github.Ptr(0), + State: new("pending"), + SHA: new("abcd1234"), + TotalCount: new(0), Statuses: []*github.RepoStatus{nil}, } @@ -1881,32 +1957,32 @@ func Test_GetPullRequestCheckRuns(t *testing.T) { // Setup mock PR for successful PR fetch mockPR := &github.PullRequest{ - Number: github.Ptr(42), - Title: github.Ptr("Test PR"), - HTMLURL: github.Ptr("https://github.com/owner/repo/pull/42"), + Number: new(42), + Title: new("Test PR"), + HTMLURL: new("https://github.com/owner/repo/pull/42"), Head: &github.PullRequestBranch{ - SHA: github.Ptr("abcd1234"), - Ref: github.Ptr("feature-branch"), + SHA: new("abcd1234"), + Ref: new("feature-branch"), }, } // Setup mock check runs for success case mockCheckRuns := &github.ListCheckRunsResults{ - Total: github.Ptr(2), + Total: new(2), CheckRuns: []*github.CheckRun{ { - ID: github.Ptr(int64(1)), - Name: github.Ptr("build"), - Status: github.Ptr("completed"), - Conclusion: github.Ptr("success"), - HTMLURL: github.Ptr("https://github.com/owner/repo/runs/1"), + ID: new(int64(1)), + Name: new("build"), + Status: new("completed"), + Conclusion: new("success"), + HTMLURL: new("https://github.com/owner/repo/runs/1"), }, { - ID: github.Ptr(int64(2)), - Name: github.Ptr("test"), - Status: github.Ptr("completed"), - Conclusion: github.Ptr("success"), - HTMLURL: github.Ptr("https://github.com/owner/repo/runs/2"), + ID: new(int64(2)), + Name: new("test"), + Status: new("completed"), + Conclusion: new("success"), + HTMLURL: new("https://github.com/owner/repo/runs/2"), }, }, } @@ -2036,8 +2112,8 @@ func Test_UpdatePullRequestBranch(t *testing.T) { // Setup mock update result for success case mockUpdateResult := &github.PullRequestBranchUpdateResponse{ - Message: github.Ptr("Branch was updated successfully"), - URL: github.Ptr("https://api.github.com/repos/owner/repo/pulls/42"), + Message: new("Branch was updated successfully"), + URL: new("https://api.github.com/repos/owner/repo/pulls/42"), } tests := []struct { @@ -2579,25 +2655,25 @@ func Test_GetPullRequestReviews(t *testing.T) { // Setup mock PR reviews for success case mockReviews := []*github.PullRequestReview{ { - ID: github.Ptr(int64(201)), - State: github.Ptr("APPROVED"), - Body: github.Ptr("LGTM"), - HTMLURL: github.Ptr("https://github.com/owner/repo/pull/42#pullrequestreview-201"), + ID: new(int64(201)), + State: new("APPROVED"), + Body: new("LGTM"), + HTMLURL: new("https://github.com/owner/repo/pull/42#pullrequestreview-201"), User: &github.User{ - Login: github.Ptr("approver"), + Login: new("approver"), }, - CommitID: github.Ptr("abcdef123456"), + CommitID: new("abcdef123456"), SubmittedAt: &github.Timestamp{Time: time.Now().Add(-24 * time.Hour)}, }, { - ID: github.Ptr(int64(202)), - State: github.Ptr("CHANGES_REQUESTED"), - Body: github.Ptr("Please address the following issues"), - HTMLURL: github.Ptr("https://github.com/owner/repo/pull/42#pullrequestreview-202"), + ID: new(int64(202)), + State: new("CHANGES_REQUESTED"), + Body: new("Please address the following issues"), + HTMLURL: new("https://github.com/owner/repo/pull/42#pullrequestreview-202"), User: &github.User{ - Login: github.Ptr("reviewer"), + Login: new("reviewer"), }, - CommitID: github.Ptr("abcdef123456"), + CommitID: new("abcdef123456"), SubmittedAt: &github.Timestamp{Time: time.Now().Add(-12 * time.Hour)}, }, } @@ -2674,16 +2750,16 @@ func Test_GetPullRequestReviews(t *testing.T) { mockedClient: MockHTTPClientWithHandlers(map[string]http.HandlerFunc{ GetReposPullsReviewsByOwnerByRepoByPullNumber: mockResponse(t, http.StatusOK, []*github.PullRequestReview{ { - ID: github.Ptr(int64(2030)), - State: github.Ptr("APPROVED"), - Body: github.Ptr("Maintainer review"), - User: &github.User{Login: github.Ptr("maintainer")}, + ID: new(int64(2030)), + State: new("APPROVED"), + Body: new("Maintainer review"), + User: &github.User{Login: new("maintainer")}, }, { - ID: github.Ptr(int64(2031)), - State: github.Ptr("COMMENTED"), - Body: github.Ptr("External reviewer"), - User: &github.User{Login: github.Ptr("testuser")}, + ID: new(int64(2031)), + State: new("COMMENTED"), + Body: new("External reviewer"), + User: &github.User{Login: new("testuser")}, }, }), }), @@ -2696,10 +2772,10 @@ func Test_GetPullRequestReviews(t *testing.T) { expectError: false, expectedReviews: []*github.PullRequestReview{ { - ID: github.Ptr(int64(2030)), - State: github.Ptr("APPROVED"), - Body: github.Ptr("Maintainer review"), - User: &github.User{Login: github.Ptr("maintainer")}, + ID: new(int64(2030)), + State: new("APPROVED"), + Body: new("Maintainer review"), + User: &github.User{Login: new("maintainer")}, }, }, lockdownEnabled: true, @@ -2709,15 +2785,15 @@ func Test_GetPullRequestReviews(t *testing.T) { mockedClient: MockHTTPClientWithHandlers(map[string]http.HandlerFunc{ GetReposPullsReviewsByOwnerByRepoByPullNumber: mockResponse(t, http.StatusOK, []*github.PullRequestReview{ { - ID: github.Ptr(int64(2040)), - State: github.Ptr("APPROVED"), - Body: github.Ptr("Ghost review"), - User: &github.User{Login: github.Ptr("")}, + ID: new(int64(2040)), + State: new("APPROVED"), + Body: new("Ghost review"), + User: &github.User{Login: new("")}, }, { - ID: github.Ptr(int64(2041)), - State: github.Ptr("COMMENTED"), - Body: github.Ptr("Another ghost review"), + ID: new(int64(2041)), + State: new("COMMENTED"), + Body: new("Another ghost review"), }, }), }), @@ -2814,23 +2890,23 @@ func Test_CreatePullRequest(t *testing.T) { // Setup mock PR for success case mockPR := &github.PullRequest{ - Number: github.Ptr(42), - Title: github.Ptr("Test PR"), - State: github.Ptr("open"), - HTMLURL: github.Ptr("https://github.com/owner/repo/pull/42"), + Number: new(42), + Title: new("Test PR"), + State: new("open"), + HTMLURL: new("https://github.com/owner/repo/pull/42"), Head: &github.PullRequestBranch{ - SHA: github.Ptr("abcd1234"), - Ref: github.Ptr("feature-branch"), + SHA: new("abcd1234"), + Ref: new("feature-branch"), }, Base: &github.PullRequestBranch{ - SHA: github.Ptr("efgh5678"), - Ref: github.Ptr("main"), + SHA: new("efgh5678"), + Ref: new("main"), }, - Body: github.Ptr("This is a test PR"), - Draft: github.Ptr(false), - MaintainerCanModify: github.Ptr(true), + Body: new("This is a test PR"), + Draft: new(false), + MaintainerCanModify: new(true), User: &github.User{ - Login: github.Ptr("testuser"), + Login: new("testuser"), }, } @@ -2949,12 +3025,12 @@ func Test_CreatePullRequest_MCPAppsFeature_UIGate(t *testing.T) { t.Parallel() mockPR := &github.PullRequest{ - Number: github.Ptr(42), - Title: github.Ptr("Test PR"), - HTMLURL: github.Ptr("https://github.com/owner/repo/pull/42"), - Head: &github.PullRequestBranch{SHA: github.Ptr("abc"), Ref: github.Ptr("feature")}, - Base: &github.PullRequestBranch{SHA: github.Ptr("def"), Ref: github.Ptr("main")}, - User: &github.User{Login: github.Ptr("testuser")}, + Number: new(42), + Title: new("Test PR"), + HTMLURL: new("https://github.com/owner/repo/pull/42"), + Head: &github.PullRequestBranch{SHA: new("abc"), Ref: new("feature")}, + Base: &github.PullRequestBranch{SHA: new("def"), Ref: new("main")}, + User: &github.User{Login: new("testuser")}, } serverTool := CreatePullRequest(translations.NullTranslationHelper) @@ -2966,7 +3042,7 @@ func Test_CreatePullRequest_MCPAppsFeature_UIGate(t *testing.T) { deps := BaseDeps{ Client: client, GQLClient: githubv4.NewClient(nil), - featureChecker: featureCheckerFor(MCPAppsFeatureFlag), + featureChecker: featureCheckerFor(), } handler := serverTool.Handler(deps) @@ -3050,12 +3126,12 @@ func Test_UpdatePullRequest_MCPAppsFeature_UIGate(t *testing.T) { t.Parallel() mockPR := &github.PullRequest{ - Number: github.Ptr(42), - Title: github.Ptr("Updated"), - HTMLURL: github.Ptr("https://github.com/owner/repo/pull/42"), - Head: &github.PullRequestBranch{SHA: github.Ptr("abc"), Ref: github.Ptr("feature")}, - Base: &github.PullRequestBranch{SHA: github.Ptr("def"), Ref: github.Ptr("main")}, - User: &github.User{Login: github.Ptr("testuser")}, + Number: new(42), + Title: new("Updated"), + HTMLURL: new("https://github.com/owner/repo/pull/42"), + Head: &github.PullRequestBranch{SHA: new("abc"), Ref: new("feature")}, + Base: &github.PullRequestBranch{SHA: new("def"), Ref: new("main")}, + User: &github.User{Login: new("testuser")}, } serverTool := UpdatePullRequest(translations.NullTranslationHelper) @@ -3068,7 +3144,7 @@ func Test_UpdatePullRequest_MCPAppsFeature_UIGate(t *testing.T) { deps := BaseDeps{ Client: client, GQLClient: githubv4.NewClient(nil), - featureChecker: featureCheckerFor(MCPAppsFeatureFlag), + featureChecker: featureCheckerFor(), } handler := serverTool.Handler(deps) @@ -3667,7 +3743,7 @@ func TestAddPullRequestReviewCommentToPendingReview(t *testing.T) { expectedToolErrMsg string }{ { - name: "successful line comment addition", + name: "selects viewer pending review by ID", requestArgs: map[string]any{ "owner": "owner", "repo": "repo", @@ -3681,18 +3757,21 @@ func TestAddPullRequestReviewCommentToPendingReview(t *testing.T) { "startSide": "RIGHT", }, mockedClient: githubv4mock.NewMockedHTTPClient( - viewerQuery("williammartin"), - getLatestPendingReviewQuery(getLatestPendingReviewQueryParams{ - author: "williammartin", - owner: "owner", - repo: "repo", - prNum: 42, - - reviews: []getLatestPendingReviewQueryReview{ + viewerIDQuery("U_viewer"), + getPendingReviewsQuery(getPendingReviewsQueryParams{ + owner: "owner", + repo: "repo", + prNum: 42, + + reviews: []pendingReviewQueryReview{ + { + id: "PR_other", + authorID: "U_other", + }, { - id: "PR_kwDODKw3uc6WYN1T", - state: "PENDING", - url: "https://github.com/owner/repo/pull/42", + id: "PR_kwDODKw3uc6WYN1T", + authorID: "U_viewer", + authorField: "botId", }, }, }), @@ -3705,7 +3784,7 @@ func TestAddPullRequestReviewCommentToPendingReview(t *testing.T) { } `graphql:"addPullRequestReviewThread(input: $input)"` }{}, githubv4.AddPullRequestReviewThreadInput{ - Path: githubv4.String("file.go"), + Path: githubv4.NewString("file.go"), Body: githubv4.String("This is a test comment"), SubjectType: githubv4mock.Ptr(githubv4.PullRequestReviewThreadSubjectTypeLine), Line: githubv4.NewInt(10), @@ -3740,18 +3819,16 @@ func TestAddPullRequestReviewCommentToPendingReview(t *testing.T) { "startSide": "RIGHT", }, mockedClient: githubv4mock.NewMockedHTTPClient( - viewerQuery("williammartin"), - getLatestPendingReviewQuery(getLatestPendingReviewQueryParams{ - author: "williammartin", - owner: "owner", - repo: "repo", - prNum: 42, - - reviews: []getLatestPendingReviewQueryReview{ + viewerIDQuery("U_viewer"), + getPendingReviewsQuery(getPendingReviewsQueryParams{ + owner: "owner", + repo: "repo", + prNum: 42, + + reviews: []pendingReviewQueryReview{ { - id: "PR_kwDODKw3uc6WYN1T", - state: "PENDING", - url: "https://github.com/owner/repo/pull/42", + id: "PR_kwDODKw3uc6WYN1T", + authorID: "U_viewer", }, }, }), @@ -3764,7 +3841,7 @@ func TestAddPullRequestReviewCommentToPendingReview(t *testing.T) { } `graphql:"addPullRequestReviewThread(input: $input)"` }{}, githubv4.AddPullRequestReviewThreadInput{ - Path: githubv4.String("file.go"), + Path: githubv4.NewString("file.go"), Body: githubv4.String("This is a test comment"), SubjectType: githubv4mock.Ptr(githubv4.PullRequestReviewThreadSubjectTypeLine), Line: githubv4.NewInt(10), @@ -3821,18 +3898,16 @@ func TestAddPullRequestReviewCommentToPendingReview(t *testing.T) { "side": "RIGHT", }, mockedClient: githubv4mock.NewMockedHTTPClient( - viewerQuery("williammartin"), - getLatestPendingReviewQuery(getLatestPendingReviewQueryParams{ - author: "williammartin", - owner: "owner", - repo: "repo", - prNum: 42, - - reviews: []getLatestPendingReviewQueryReview{ + viewerIDQuery("U_viewer"), + getPendingReviewsQuery(getPendingReviewsQueryParams{ + owner: "owner", + repo: "repo", + prNum: 42, + + reviews: []pendingReviewQueryReview{ { - id: "PR_kwDODKw3uc6WYN1T", - state: "PENDING", - url: "https://github.com/owner/repo/pull/42", + id: "PR_kwDODKw3uc6WYN1T", + authorID: "U_viewer", }, }, }), @@ -3845,7 +3920,7 @@ func TestAddPullRequestReviewCommentToPendingReview(t *testing.T) { } `graphql:"addPullRequestReviewThread(input: $input)"` }{}, githubv4.AddPullRequestReviewThreadInput{ - Path: githubv4.String("file.go"), + Path: githubv4.NewString("file.go"), Body: githubv4.String("Comment on non-existent line"), SubjectType: githubv4mock.Ptr(githubv4.PullRequestReviewThreadSubjectTypeLine), Line: githubv4.NewInt(999), @@ -3939,18 +4014,16 @@ func TestSubmitPendingPullRequestReview(t *testing.T) { "body": "This is a test review", }, mockedClient: githubv4mock.NewMockedHTTPClient( - viewerQuery("williammartin"), - getLatestPendingReviewQuery(getLatestPendingReviewQueryParams{ - author: "williammartin", - owner: "owner", - repo: "repo", - prNum: 42, - - reviews: []getLatestPendingReviewQueryReview{ + viewerIDQuery("U_viewer"), + getPendingReviewsQuery(getPendingReviewsQueryParams{ + owner: "owner", + repo: "repo", + prNum: 42, + + reviews: []pendingReviewQueryReview{ { - id: "PR_kwDODKw3uc6WYN1T", - state: "PENDING", - url: "https://github.com/owner/repo/pull/42", + id: "PR_kwDODKw3uc6WYN1T", + authorID: "U_viewer", }, }, }), @@ -4040,18 +4113,16 @@ func TestDeletePendingPullRequestReview(t *testing.T) { "pullNumber": float64(42), }, mockedClient: githubv4mock.NewMockedHTTPClient( - viewerQuery("williammartin"), - getLatestPendingReviewQuery(getLatestPendingReviewQueryParams{ - author: "williammartin", - owner: "owner", - repo: "repo", - prNum: 42, - - reviews: []getLatestPendingReviewQueryReview{ + viewerIDQuery("U_viewer"), + getPendingReviewsQuery(getPendingReviewsQueryParams{ + owner: "owner", + repo: "repo", + prNum: 42, + + reviews: []pendingReviewQueryReview{ { - id: "PR_kwDODKw3uc6WYN1T", - state: "PENDING", - url: "https://github.com/owner/repo/pull/42", + id: "PR_kwDODKw3uc6WYN1T", + authorID: "U_viewer", }, }, }), @@ -4106,6 +4177,57 @@ func TestDeletePendingPullRequestReview(t *testing.T) { } } +func TestGetPendingPullRequestReviewForViewerPaginates(t *testing.T) { + t.Parallel() + + var reviewQueries atomic.Int32 + transport := NewMockRoundTripper().OnRequest(http.MethodPost, "/graphql", func(w http.ResponseWriter, r *http.Request) { + var request struct { + Query string `json:"query"` + Variables map[string]any `json:"variables"` + } + require.NoError(t, json.NewDecoder(r.Body).Decode(&request)) + + w.Header().Set("Content-Type", "application/json") + switch { + case strings.Contains(request.Query, "viewer"): + require.NoError(t, json.NewEncoder(w).Encode(map[string]any{ + "data": map[string]any{ + "viewer": map[string]any{"id": "U_viewer"}, + }, + })) + case strings.Contains(request.Query, "reviews"): + queryNumber := reviewQueries.Add(1) + if queryNumber == 1 { + assert.Nil(t, request.Variables["after"]) + require.NoError(t, json.NewEncoder(w).Encode(pendingReviewsResponse( + []pendingReviewQueryReview{{id: "PR_other", authorID: "U_other"}}, + true, + "cursor-1", + ))) + return + } + + assert.Equal(t, "cursor-1", request.Variables["after"]) + require.NoError(t, json.NewEncoder(w).Encode(pendingReviewsResponse( + []pendingReviewQueryReview{{id: "PR_viewer", authorID: "U_viewer"}}, + false, + "", + ))) + default: + t.Fatalf("unexpected GraphQL query: %s", request.Query) + } + }) + + client := githubv4.NewClient(&http.Client{Transport: transport}) + reviewID, result := getPendingPullRequestReviewForViewer(context.Background(), client, "owner", "repo", 42) + + require.Nil(t, result) + require.NotNil(t, reviewID) + assert.Equal(t, githubv4.ID("PR_viewer"), *reviewID) + assert.Equal(t, int32(2), reviewQueries.Load()) +} + func TestGetPullRequestDiff(t *testing.T) { t.Parallel() @@ -4140,8 +4262,8 @@ index 5d6e7b2..8a4f5c3 100644 // author, then the raw diff; branch on the Accept header to serve both. prOrDiffHandler := func(authorLogin string) http.HandlerFunc { mockPR := &github.PullRequest{ - Number: github.Ptr(42), - User: &github.User{Login: github.Ptr(authorLogin)}, + Number: new(42), + User: &github.User{Login: new(authorLogin)}, } return func(w http.ResponseWriter, r *http.Request) { if strings.Contains(r.Header.Get("Accept"), "diff") { @@ -4252,76 +4374,103 @@ index 5d6e7b2..8a4f5c3 100644 } } -func viewerQuery(login string) githubv4mock.Matcher { +func viewerIDQuery(id string) githubv4mock.Matcher { return githubv4mock.NewQueryMatcher( struct { Viewer struct { - Login githubv4.String + ID githubv4.ID } `graphql:"viewer"` }{}, map[string]any{}, githubv4mock.DataResponse(map[string]any{ "viewer": map[string]any{ - "login": login, + "id": id, }, }), ) } -type getLatestPendingReviewQueryReview struct { - id string - state string - url string +type pendingReviewQueryReview struct { + id string + authorID string + authorField string } -type getLatestPendingReviewQueryParams struct { - author string - owner string - repo string - prNum int32 +type getPendingReviewsQueryParams struct { + owner string + repo string + prNum int32 - reviews []getLatestPendingReviewQueryReview + reviews []pendingReviewQueryReview } -func getLatestPendingReviewQuery(p getLatestPendingReviewQueryParams) githubv4mock.Matcher { - return githubv4mock.NewQueryMatcher( +func getPendingReviewsQuery(p getPendingReviewsQueryParams) githubv4mock.Matcher { + matcher := githubv4mock.NewQueryMatcher( struct { Repository struct { PullRequest struct { Reviews struct { Nodes []struct { - ID githubv4.ID - State githubv4.PullRequestReviewState - URL githubv4.URI + ID githubv4.ID + Author pendingReviewAuthor } - } `graphql:"reviews(first: 1, author: $author)"` + PageInfo struct { + HasNextPage githubv4.Boolean + EndCursor githubv4.String + } + } `graphql:"reviews(first: 100, after: $after, states: $states)"` } `graphql:"pullRequest(number: $prNum)"` } `graphql:"repository(owner: $owner, name: $name)"` }{}, map[string]any{ - "author": githubv4.String(p.author), + "after": (*githubv4.String)(nil), "owner": githubv4.String(p.owner), "name": githubv4.String(p.repo), "prNum": githubv4.Int(p.prNum), + "states": []githubv4.PullRequestReviewState{githubv4.PullRequestReviewStatePending}, }, - githubv4mock.DataResponse( - map[string]any{ - "repository": map[string]any{ - "pullRequest": map[string]any{ - "reviews": map[string]any{ - "nodes": []any{ - map[string]any{ - "id": p.reviews[0].id, - "state": p.reviews[0].state, - "url": p.reviews[0].url, - }, - }, - }, + githubv4mock.DataResponse(map[string]any{ + "repository": pendingReviewsData(p.reviews, false, "")["repository"], + }), + ) + matcher.Variables["states"] = []any{"PENDING"} + return matcher +} + +func pendingReviewsResponse(reviews []pendingReviewQueryReview, hasNextPage bool, endCursor string) map[string]any { + return map[string]any{ + "data": pendingReviewsData(reviews, hasNextPage, endCursor), + } +} + +func pendingReviewsData(reviews []pendingReviewQueryReview, hasNextPage bool, endCursor string) map[string]any { + nodes := make([]any, 0, len(reviews)) + for _, review := range reviews { + authorField := review.authorField + if authorField == "" { + authorField = "userId" + } + nodes = append(nodes, map[string]any{ + "id": review.id, + "author": map[string]any{ + authorField: review.authorID, + }, + }) + } + + return map[string]any{ + "repository": map[string]any{ + "pullRequest": map[string]any{ + "reviews": map[string]any{ + "nodes": nodes, + "pageInfo": map[string]any{ + "hasNextPage": hasNextPage, + "endCursor": endCursor, }, }, }, - ), - ) + }, + } } func TestAddReplyToPullRequestComment(t *testing.T) { @@ -4345,19 +4494,19 @@ func TestAddReplyToPullRequestComment(t *testing.T) { // Setup mock reply comment for success case mockReplyComment := &github.PullRequestComment{ - ID: github.Ptr(int64(456)), - Body: github.Ptr("This is a reply to the comment"), - InReplyTo: github.Ptr(int64(123)), - HTMLURL: github.Ptr("https://github.com/owner/repo/pull/42#discussion_r456"), + ID: new(int64(456)), + Body: new("This is a reply to the comment"), + InReplyTo: new(int64(123)), + HTMLURL: new("https://github.com/owner/repo/pull/42#discussion_r456"), User: &github.User{ - Login: github.Ptr("responder"), + Login: new("responder"), }, CreatedAt: &github.Timestamp{Time: time.Now()}, UpdatedAt: &github.Timestamp{Time: time.Now()}, } mockReaction := &github.Reaction{ - ID: github.Ptr(int64(789)), - Content: github.Ptr("rocket"), + ID: new(int64(789)), + Content: new("rocket"), } replyCreatedAfterReactionFailure := &atomic.Bool{} diff --git a/pkg/github/repositories.go b/pkg/github/repositories.go index 8e2dd25172..b884f4888d 100644 --- a/pkg/github/repositories.go +++ b/pkg/github/repositories.go @@ -12,22 +12,55 @@ import ( "strings" "time" - ghErrors "github.com/github/github-mcp-server/pkg/errors" - "github.com/github/github-mcp-server/pkg/ifc" - "github.com/github/github-mcp-server/pkg/inventory" - "github.com/github/github-mcp-server/pkg/octicons" - "github.com/github/github-mcp-server/pkg/sanitize" - "github.com/github/github-mcp-server/pkg/scopes" - "github.com/github/github-mcp-server/pkg/translations" - "github.com/github/github-mcp-server/pkg/utils" - "github.com/google/go-github/v89/github" + ghErrors "github.com/github/github-mcp-server/v2/pkg/errors" + "github.com/github/github-mcp-server/v2/pkg/ifc" + "github.com/github/github-mcp-server/v2/pkg/inventory" + "github.com/github/github-mcp-server/v2/pkg/octicons" + "github.com/github/github-mcp-server/v2/pkg/sanitize" + "github.com/github/github-mcp-server/v2/pkg/scopes" + "github.com/github/github-mcp-server/v2/pkg/translations" + "github.com/github/github-mcp-server/v2/pkg/utils" + "github.com/google/go-github/v92/github" "github.com/google/jsonschema-go/jsonschema" "github.com/modelcontextprotocol/go-sdk/mcp" "github.com/shurcooL/githubv4" ) +type GetCommitInput struct { + Owner string `json:"owner"` + Repo string `json:"repo"` + SHA string `json:"sha"` + Detail string `json:"detail,omitempty"` + Page *int `json:"page,omitempty"` + PerPage *int `json:"perPage,omitempty"` +} + func GetCommit(t translations.TranslationHelperFunc) inventory.ServerTool { - return NewTool( + schema := WithPagination(&jsonschema.Schema{ + Type: "object", + Properties: map[string]*jsonschema.Schema{ + "owner": { + Type: "string", + Description: "Repository owner", + }, + "repo": { + Type: "string", + Description: "Repository name", + }, + "sha": { + Type: "string", + Description: "Commit SHA, branch name, or tag name", + }, + "detail": { + Type: "string", + Enum: []any{"none", "stats", "full_patch"}, + Description: "Level of detail to include for changed files. \"none\" omits stats and files entirely. \"stats\" (default) includes per-file metadata: filename, status, and lines-of-code counts (additions, deletions, changes), with no patch content. \"full_patch\" additionally includes the unified diff content for each file and can be very large.", + Default: json.RawMessage(`"stats"`), + }, + }, + Required: []string{"owner", "repo", "sha"}, + }) + return NewToolWithSchemaOptions[GetCommitInput, MinimalCommit]( ToolsetMetadataRepos, mcp.Tool{ Name: "get_commit", @@ -36,56 +69,30 @@ func GetCommit(t translations.TranslationHelperFunc) inventory.ServerTool { Title: t("TOOL_GET_COMMITS_USER_TITLE", "Get commit details"), ReadOnlyHint: true, }, - InputSchema: WithPagination(&jsonschema.Schema{ - Type: "object", - Properties: map[string]*jsonschema.Schema{ - "owner": { - Type: "string", - Description: "Repository owner", - }, - "repo": { - Type: "string", - Description: "Repository name", - }, - "sha": { - Type: "string", - Description: "Commit SHA, branch name, or tag name", - }, - "detail": { - Type: "string", - Enum: []any{"none", "stats", "full_patch"}, - Description: "Level of detail to include for changed files. \"none\" omits stats and files entirely. \"stats\" (default) includes per-file metadata: filename, status, and lines-of-code counts (additions, deletions, changes), with no patch content. \"full_patch\" additionally includes the unified diff content for each file and can be very large.", - Default: json.RawMessage(`"stats"`), - }, - }, - Required: []string{"owner", "repo", "sha"}, - }), + InputSchema: schema, }, scopes.PublicRead(scopes.Repo), - func(ctx context.Context, deps ToolDependencies, _ *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 + inventory.TypedSchemaOptions{ValidationInputSchema: relaxedPaginationValidationSchema(schema)}, + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, input GetCommitInput) (*mcp.CallToolResult, MinimalCommit, error) { + if input.Owner == "" { + return utils.NewToolResultError("missing required parameter: owner"), MinimalCommit{}, nil } - repo, err := RequiredParam[string](args, "repo") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil + if input.Repo == "" { + return utils.NewToolResultError("missing required parameter: repo"), MinimalCommit{}, nil } - sha, err := RequiredParam[string](args, "sha") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil + if input.SHA == "" { + return utils.NewToolResultError("missing required parameter: sha"), MinimalCommit{}, nil } - detailRaw, err := OptionalParam[string](args, "detail") + detail, err := parseCommitDetail(input.Detail) if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil + return utils.NewToolResultError(err.Error()), MinimalCommit{}, nil } - detail, err := parseCommitDetail(detailRaw) - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil + pagination := PaginationParams{Page: 1, PerPage: 30} + if input.Page != nil { + pagination.Page = *input.Page } - pagination, err := OptionalPaginationParams(args) - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil + if input.PerPage != nil { + pagination.PerPage = *input.PerPage } opts := &github.ListOptions{ @@ -95,24 +102,24 @@ func GetCommit(t translations.TranslationHelperFunc) inventory.ServerTool { client, err := deps.GetClient(ctx) if err != nil { - return nil, nil, fmt.Errorf("failed to get GitHub client: %w", err) + return nil, MinimalCommit{}, fmt.Errorf("failed to get GitHub client: %w", err) } - commit, resp, err := client.Repositories.GetCommit(ctx, owner, repo, sha, opts) + commit, resp, err := client.Repositories.GetCommit(ctx, input.Owner, input.Repo, input.SHA, opts) if err != nil { return ghErrors.NewGitHubAPIErrorResponse(ctx, - fmt.Sprintf("failed to get commit: %s", sha), + fmt.Sprintf("failed to get commit: %s", input.SHA), resp, err, - ), nil, nil + ), MinimalCommit{}, nil } defer func() { _ = resp.Body.Close() }() if resp.StatusCode != 200 { body, err := io.ReadAll(resp.Body) if err != nil { - return nil, nil, fmt.Errorf("failed to read response body: %w", err) + return nil, MinimalCommit{}, fmt.Errorf("failed to read response body: %w", err) } - return ghErrors.NewGitHubAPIStatusErrorResponse(ctx, "failed to get commit", resp, body), nil, nil + return ghErrors.NewGitHubAPIStatusErrorResponse(ctx, "failed to get commit", resp, body), MinimalCommit{}, nil } // Convert to minimal commit @@ -120,7 +127,7 @@ func GetCommit(t translations.TranslationHelperFunc) inventory.ServerTool { r, err := json.Marshal(minimalCommit) if err != nil { - return nil, nil, fmt.Errorf("failed to marshal response: %w", err) + return nil, MinimalCommit{}, fmt.Errorf("failed to marshal response: %w", err) } result := utils.NewToolResultText(string(r)) @@ -128,12 +135,61 @@ func GetCommit(t translations.TranslationHelperFunc) inventory.ServerTool { // repos anyone can land it via a PR (untrusted), in private repos // only collaborators can (trusted). Confidentiality follows repo // visibility. - result = attachRepoVisibilityIFCLabel(ctx, deps, client, owner, repo, result, ifc.LabelCommitContents) - return result, nil, nil + result = attachRepoVisibilityIFCLabel(ctx, deps, client, input.Owner, input.Repo, result, ifc.LabelCommitContents) + return result, minimalCommit, nil }, + normalizeTypedReadArguments(nil, false), ) } +type ListCommitsInput struct { + Owner string `json:"owner"` + Repo string `json:"repo"` + SHA string `json:"sha,omitempty"` + Author string `json:"author,omitempty"` + Path string `json:"path,omitempty"` + Since string `json:"since,omitempty"` + Until string `json:"until,omitempty"` + Fields []string `json:"fields,omitempty"` + Page *int `json:"page,omitempty"` + PerPage *int `json:"perPage,omitempty"` +} + +type ListCommitOutput struct { + SHA *string `json:"sha,omitempty"` + HTMLURL *string `json:"html_url,omitempty"` + Commit *MinimalCommitInfo `json:"commit,omitempty"` + Author *MinimalUser `json:"author,omitempty"` + Committer *MinimalUser `json:"committer,omitempty"` +} + +func structuredListCommitsOutput(commits []MinimalCommit, fields []string) []ListCommitOutput { + output := make([]ListCommitOutput, 0, len(commits)) + selected := func(field string) bool { + return len(fields) == 0 || slices.Contains(fields, field) + } + for _, commit := range commits { + item := ListCommitOutput{} + if selected("sha") { + item.SHA = new(commit.SHA) + } + if selected("html_url") { + item.HTMLURL = new(commit.HTMLURL) + } + if selected("commit") { + item.Commit = commit.Commit + } + if selected("author") { + item.Author = commit.Author + } + if selected("committer") { + item.Committer = commit.Committer + } + output = append(output, item) + } + return output +} + // ListCommits creates a tool to get the list of commits of a branch in a GitHub // repository. func ListCommits(t translations.TranslationHelperFunc) inventory.ServerTool { @@ -177,7 +233,7 @@ func ListCommits(t translations.TranslationHelperFunc) inventory.ServerTool { ) WithPagination(schema) - return NewTool( + return NewToolWithSchemaOptions[ListCommitsInput, []ListCommitOutput]( ToolsetMetadataRepos, mcp.Tool{ Name: "list_commits", @@ -189,42 +245,20 @@ func ListCommits(t translations.TranslationHelperFunc) inventory.ServerTool { InputSchema: schema, }, scopes.PublicRead(scopes.Repo), - func(ctx context.Context, deps ToolDependencies, _ *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 - } - repo, err := RequiredParam[string](args, "repo") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - sha, err := OptionalParam[string](args, "sha") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil + inventory.TypedSchemaOptions{ValidationInputSchema: relaxedPaginationValidationSchema(schema)}, + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, input ListCommitsInput) (*mcp.CallToolResult, []ListCommitOutput, error) { + if input.Owner == "" { + return utils.NewToolResultError("missing required parameter: owner"), nil, nil } - author, err := OptionalParam[string](args, "author") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - path, err := OptionalParam[string](args, "path") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil + if input.Repo == "" { + return utils.NewToolResultError("missing required parameter: repo"), nil, nil } - fields, err := OptionalStringArrayParam(args, "fields") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil + pagination := PaginationParams{Page: 1, PerPage: 30} + if input.Page != nil { + pagination.Page = *input.Page } - sinceStr, err := OptionalParam[string](args, "since") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - untilStr, err := OptionalParam[string](args, "until") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - pagination, err := OptionalPaginationParams(args) - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil + if input.PerPage != nil { + pagination.PerPage = *input.PerPage } // Set default perPage to 30 if not provided perPage := pagination.PerPage @@ -232,23 +266,21 @@ func ListCommits(t translations.TranslationHelperFunc) inventory.ServerTool { perPage = 30 } opts := &github.CommitsListOptions{ - SHA: sha, - Path: path, - Author: author, - ListOptions: github.ListOptions{ - Page: pagination.Page, - PerPage: perPage, - }, + SHA: input.SHA, + Path: input.Path, + Author: input.Author, + Page: pagination.Page, + PerPage: perPage, } - if sinceStr != "" { - sinceTime, err := parseISOTimestamp(sinceStr) + if input.Since != "" { + sinceTime, err := parseISOTimestamp(input.Since) if err != nil { return utils.NewToolResultError(fmt.Sprintf("invalid since timestamp: %s", err)), nil, nil } opts.Since = sinceTime } - if untilStr != "" { - untilTime, err := parseISOTimestamp(untilStr) + if input.Until != "" { + untilTime, err := parseISOTimestamp(input.Until) if err != nil { return utils.NewToolResultError(fmt.Sprintf("invalid until timestamp: %s", err)), nil, nil } @@ -259,10 +291,10 @@ func ListCommits(t translations.TranslationHelperFunc) inventory.ServerTool { if err != nil { return nil, nil, fmt.Errorf("failed to get GitHub client: %w", err) } - commits, resp, err := client.Repositories.ListCommits(ctx, owner, repo, opts) + commits, resp, err := client.Repositories.ListCommits(ctx, input.Owner, input.Repo, opts) if err != nil { return ghErrors.NewGitHubAPIErrorResponse(ctx, - fmt.Sprintf("failed to list commits: %s", sha), + fmt.Sprintf("failed to list commits: %s", input.SHA), resp, err, ), nil, nil @@ -285,8 +317,8 @@ func ListCommits(t translations.TranslationHelperFunc) inventory.ServerTool { filtered := false var payload any = minimalCommits - if len(fields) > 0 { - filteredCommits, err := filterEachField(minimalCommits, fields) + if len(input.Fields) > 0 { + filteredCommits, err := filterEachField(minimalCommits, input.Fields) if err != nil { return utils.NewToolResultErrorFromErr("failed to filter commits", err), nil, nil } @@ -305,15 +337,24 @@ func ListCommits(t translations.TranslationHelperFunc) inventory.ServerTool { // Commit content is reachable from the repo's history; integrity // follows the same public-untrusted / private-trusted rule as file // contents. Confidentiality follows repo visibility. - result = attachRepoVisibilityIFCLabel(ctx, deps, client, owner, repo, result, ifc.LabelCommitContents) - return result, nil, nil + result = attachRepoVisibilityIFCLabel(ctx, deps, client, input.Owner, input.Repo, result, ifc.LabelCommitContents) + return result, structuredListCommitsOutput(minimalCommits, input.Fields), nil }, + normalizeTypedReadArguments(nil, false), + normalizeRepositoryFieldsArguments, ) } // ListBranches creates a tool to list branches in a GitHub repository. +type RepositoryListInput struct { + Owner string `json:"owner"` + Repo string `json:"repo"` + Page *int `json:"page,omitempty"` + PerPage *int `json:"perPage,omitempty"` +} + func ListBranches(t translations.TranslationHelperFunc) inventory.ServerTool { - return NewTool( + return NewTool[RepositoryListInput, []MinimalBranch]( ToolsetMetadataRepos, mcp.Tool{ Name: "list_branches", @@ -338,25 +379,24 @@ func ListBranches(t translations.TranslationHelperFunc) inventory.ServerTool { }), }, scopes.PublicRead(scopes.Repo), - func(ctx context.Context, deps ToolDependencies, _ *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 + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, input RepositoryListInput) (*mcp.CallToolResult, []MinimalBranch, error) { + if input.Owner == "" { + return utils.NewToolResultError("missing required parameter: owner"), nil, nil } - repo, err := RequiredParam[string](args, "repo") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil + if input.Repo == "" { + return utils.NewToolResultError("missing required parameter: repo"), nil, nil } - pagination, err := OptionalPaginationParams(args) - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil + pagination := PaginationParams{Page: 1, PerPage: 30} + if input.Page != nil { + pagination.Page = *input.Page + } + if input.PerPage != nil { + pagination.PerPage = *input.PerPage } opts := &github.BranchListOptions{ - ListOptions: github.ListOptions{ - Page: pagination.Page, - PerPage: pagination.PerPage, - }, + Page: pagination.Page, + PerPage: pagination.PerPage, } client, err := deps.GetClient(ctx) @@ -364,7 +404,7 @@ func ListBranches(t translations.TranslationHelperFunc) inventory.ServerTool { return nil, nil, fmt.Errorf("failed to get GitHub client: %w", err) } - branches, resp, err := client.Repositories.ListBranches(ctx, owner, repo, opts) + branches, resp, err := client.Repositories.ListBranches(ctx, input.Owner, input.Repo, opts) if err != nil { return ghErrors.NewGitHubAPIErrorResponse(ctx, "failed to list branches", @@ -397,15 +437,16 @@ func ListBranches(t translations.TranslationHelperFunc) inventory.ServerTool { // Branches are structural repo metadata that only collaborators // with push access can create, so integrity is trusted. // Confidentiality follows repo visibility. - result = attachRepoVisibilityIFCLabel(ctx, deps, client, owner, repo, result, ifc.LabelRepoMetadata) - return result, nil, nil + result = attachRepoVisibilityIFCLabel(ctx, deps, client, input.Owner, input.Repo, result, ifc.LabelRepoMetadata) + return result, minimalBranches, nil }, + normalizeTypedReadArguments(nil, false), ) } // CreateOrUpdateFile creates a tool to create or update a file in a GitHub repository. func CreateOrUpdateFile(t translations.TranslationHelperFunc) inventory.ServerTool { - tool := NewTool( + tool := NewTool[CreateOrUpdateFileInput, *MinimalFileContentResponse]( ToolsetMetadataRepos, mcp.Tool{ Name: "create_or_update_file", @@ -461,34 +502,34 @@ SHA MUST be provided for existing file updates. }, }, scopes.RequireAll(scopes.Repo), - func(ctx context.Context, deps ToolDependencies, _ *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 + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, input CreateOrUpdateFileInput) (*mcp.CallToolResult, *MinimalFileContentResponse, error) { + owner := input.Owner + if owner == "" { + return utils.NewToolResultError("missing required parameter: owner"), nil, nil } - repo, err := RequiredParam[string](args, "repo") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil + repo := input.Repo + if repo == "" { + return utils.NewToolResultError("missing required parameter: repo"), nil, nil } - path, err := RequiredParam[string](args, "path") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil + path := input.Path + if path == "" { + return utils.NewToolResultError("missing required parameter: path"), nil, nil } - path, err = validateRelativePath(path) + path, err := validateRelativePath(path) if err != nil { return utils.NewToolResultError(fmt.Sprintf("invalid path: %s", err)), nil, nil } - content, err := RequiredParam[string](args, "content") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil + content := input.Content + if content == "" { + return utils.NewToolResultError("missing required parameter: content"), nil, nil } - message, err := RequiredParam[string](args, "message") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil + message := input.Message + if message == "" { + return utils.NewToolResultError("missing required parameter: message"), nil, nil } - branch, err := RequiredParam[string](args, "branch") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil + branch := input.Branch + if branch == "" { + return utils.NewToolResultError("missing required parameter: branch"), nil, nil } // json.Marshal encodes byte arrays with base64, which is required for the API. @@ -496,24 +537,18 @@ SHA MUST be provided for existing file updates. // Create the file options opts := &github.RepositoryContentFileOptions{ - Message: github.Ptr(message), + Message: new(message), Content: contentBytes, - Branch: github.Ptr(branch), + Branch: new(branch), } // If SHA is provided, set it (for updates) - sha, err := OptionalParam[string](args, "sha") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } + sha := input.SHA if sha != "" { - opts.SHA = github.Ptr(sha) + opts.SHA = new(sha) } - allowSymlinkWrite, err := OptionalParam[bool](args, "allow_symlink_write") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } + allowSymlinkWrite := input.AllowSymlinkWrite // Create or update the file client, err := deps.GetClient(ctx) @@ -625,7 +660,7 @@ SHA MUST be provided for existing file updates. minimalResponse := convertToMinimalFileContentResponse(fileContent) - return MarshalledTextResult(minimalResponse), nil, nil + return MarshalledTextResult(minimalResponse), &minimalResponse, nil }, ) tool.ScopeAccess = scopes.DynamicChallenge( @@ -638,7 +673,7 @@ SHA MUST be provided for existing file updates. // CreateRepository creates a tool to create a new GitHub repository. func CreateRepository(t translations.TranslationHelperFunc) inventory.ServerTool { - return NewTool( + return NewTool[CreateRepositoryInput, *MinimalResponse]( ToolsetMetadataRepos, mcp.Tool{ Name: "create_repository", @@ -676,33 +711,24 @@ func CreateRepository(t translations.TranslationHelperFunc) inventory.ServerTool }, }, scopes.RequireAll(scopes.Repo), - func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, args map[string]any) (*mcp.CallToolResult, any, error) { - name, err := RequiredParam[string](args, "name") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - description, err := OptionalParam[string](args, "description") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, input CreateRepositoryInput) (*mcp.CallToolResult, *MinimalResponse, error) { + name := input.Name + if name == "" { + return utils.NewToolResultError("missing required parameter: name"), nil, nil } - organization, err := OptionalParam[string](args, "organization") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - private, err := OptionalBoolParamWithDefault(args, "private", true) - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - autoInit, err := OptionalParam[bool](args, "autoInit") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil + description := input.Description + organization := input.Organization + private := true + if input.Private != nil { + private = *input.Private } + autoInit := input.AutoInit repo := &github.Repository{ - Name: github.Ptr(name), - Description: github.Ptr(description), - Private: github.Ptr(private), - AutoInit: github.Ptr(autoInit), + Name: new(name), + Description: new(description), + Private: new(private), + AutoInit: new(autoInit), } client, err := deps.GetClient(ctx) @@ -738,7 +764,7 @@ func CreateRepository(t translations.TranslationHelperFunc) inventory.ServerTool return nil, nil, fmt.Errorf("failed to marshal response: %w", err) } - return utils.NewToolResultText(string(r)), nil, nil + return utils.NewToolResultText(string(r)), &minimalResponse, nil }, ) } @@ -760,7 +786,7 @@ type deleteRepositoryState struct { // DeleteRepository creates a tool that deletes a GitHub repository after the // user confirms its full name through elicitation. func DeleteRepository(t translations.TranslationHelperFunc) inventory.ServerTool { - tool := NewTool( + tool := NewTool[RepositoryInput, *RepositoryMessageOutput]( ToolsetMetadataRepos, mcp.Tool{ Name: DeleteRepositoryToolName, @@ -768,7 +794,7 @@ func DeleteRepository(t translations.TranslationHelperFunc) inventory.ServerTool Annotations: &mcp.ToolAnnotations{ Title: t("TOOL_DELETE_REPOSITORY_USER_TITLE", "Delete repository"), ReadOnlyHint: false, - DestructiveHint: github.Ptr(true), + DestructiveHint: new(true), }, InputSchema: &jsonschema.Schema{ Type: "object", @@ -786,14 +812,14 @@ func DeleteRepository(t translations.TranslationHelperFunc) inventory.ServerTool }, }, scopes.RequireAll(scopes.DeleteRepo, scopes.Repo), - func(ctx context.Context, deps ToolDependencies, req *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 + func(ctx context.Context, deps ToolDependencies, req *mcp.CallToolRequest, input RepositoryInput) (*mcp.CallToolResult, *RepositoryMessageOutput, error) { + owner := input.Owner + if owner == "" { + return utils.NewToolResultError("missing required parameter: owner"), nil, nil } - repo, err := RequiredParam[string](args, "repo") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil + repo := input.Repo + if repo == "" { + return utils.NewToolResultError("missing required parameter: repo"), nil, nil } fullName := owner + "/" + repo @@ -912,7 +938,8 @@ func DeleteRepository(t translations.TranslationHelperFunc) inventory.ServerTool return ghErrors.NewGitHubAPIStatusErrorResponse(ctx, "failed to delete repository", resp, body), nil, nil } - return utils.NewToolResultText(fmt.Sprintf("Repository %s was deleted.", fullName)), nil, nil + message := fmt.Sprintf("Repository %s was deleted.", fullName) + return utils.NewToolResultText(message), &RepositoryMessageOutput{Message: message}, nil }, ) tool.MinimumProtocolVersion = inventory.ProtocolVersionMultiRoundTrip @@ -984,11 +1011,12 @@ func GetFileContents(t translations.TranslationHelperFunc) inventory.ServerTool fileContentFieldEnum, ) - return NewTool( + return NewTool[GetFileContentsInput, *RepositoryContentsOutput]( ToolsetMetadataRepos, mcp.Tool{ - Name: "get_file_contents", - Description: t("TOOL_GET_FILE_CONTENTS_DESCRIPTION", "Get the contents of a file or directory from a GitHub repository"), + Name: "get_file_contents", + OutputSchema: repositoryContentsOutputSchema(), + Description: t("TOOL_GET_FILE_CONTENTS_DESCRIPTION", "Get the contents of a file or directory from a GitHub repository"), Annotations: &mcp.ToolAnnotations{ Title: t("TOOL_GET_FILE_CONTENTS_USER_TITLE", "Get file or directory contents"), ReadOnlyHint: true, @@ -996,37 +1024,25 @@ func GetFileContents(t translations.TranslationHelperFunc) inventory.ServerTool InputSchema: schema, }, scopes.PublicRead(scopes.Repo), - func(ctx context.Context, deps ToolDependencies, _ *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 + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, input GetFileContentsInput) (*mcp.CallToolResult, *RepositoryContentsOutput, error) { + owner := input.Owner + if owner == "" { + return utils.NewToolResultError("missing required parameter: owner"), nil, nil } - repo, err := RequiredParam[string](args, "repo") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil + repo := input.Repo + if repo == "" { + return utils.NewToolResultError("missing required parameter: repo"), nil, nil } - path, err := OptionalParam[string](args, "path") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } + path := input.Path path = strings.TrimPrefix(path, "/") - ref, err := OptionalParam[string](args, "ref") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } + ref := input.Ref originalRef := ref - sha, err := OptionalParam[string](args, "sha") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } + sha := input.SHA - fields, err := OptionalStringArrayParam(args, "fields") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } + fields := input.Fields client, err := deps.GetClient(ctx) if err != nil { @@ -1063,8 +1079,11 @@ func GetFileContents(t translations.TranslationHelperFunc) inventory.ServerTool // The path does not point to a file or directory. // Instead let's try to find it in the Git Tree by matching the end of the path. if err != nil || (fileContent == nil && dirContent == nil) { - res, data, err := matchFiles(ctx, client, owner, repo, ref, path, rawOpts, 0) - return attachIFC(res), data, err + res, _, err := matchFiles(ctx, client, owner, repo, ref, path, rawOpts, 0) + if err != nil { + return nil, nil, err + } + return repositoryContentResult(attachIFC(res)) } if fileContent != nil && fileContent.SHA != nil { @@ -1092,10 +1111,10 @@ func GetFileContents(t translations.TranslationHelperFunc) inventory.ServerTool return utils.NewToolResultError(fmt.Sprintf("failed to inspect repository file: %s", err)), nil, nil } if read.Metadata != nil && read.Metadata.Type == "submodule" { - return attachIFC(utils.NewToolResultText(marshalRepositoryPathMetadata(read.Metadata, "", successNote))), nil, nil + return repositoryContentResult(attachIFC(utils.NewToolResultText(marshalRepositoryPathMetadata(read.Metadata, "", successNote)))) } if read.Metadata != nil && fileContent.GetType() == "symlink" && !read.ContentAvailable { - return attachIFC(utils.NewToolResultText(marshalRepositoryPathMetadata(read.Metadata, "not_returned", successNote))), nil, nil + return repositoryContentResult(attachIFC(utils.NewToolResultText(marshalRepositoryPathMetadata(read.Metadata, "not_returned", successNote)))) } // Empty files (0 bytes) have no content to decode; return @@ -1111,7 +1130,7 @@ func GetFileContents(t translations.TranslationHelperFunc) inventory.ServerTool } message := fmt.Sprintf("successfully downloaded empty file (SHA: %s)%s", fileSHA, successNote) message = repositoryReadMessage(read, message, successNote) - return attachIFC(utils.NewToolResultResource(message, result)), nil, nil + return repositoryContentResult(attachIFC(utils.NewToolResultResource(message, result))) } // For files >= 1MB, return a ResourceLink instead of content @@ -1129,9 +1148,9 @@ func GetFileContents(t translations.TranslationHelperFunc) inventory.ServerTool resourceLink.Title = fmt.Sprintf("Dereferenced target %s via symlink %s", read.Metadata.ResolvedTargetPath, path) } message = repositoryReadMessage(read, message, successNote) - return attachIFC(utils.NewToolResultResourceLink( + return repositoryContentResult(attachIFC(utils.NewToolResultResourceLink( message, - resourceLink)), nil, nil + resourceLink))) } if !read.ContentAvailable { @@ -1159,7 +1178,7 @@ func GetFileContents(t translations.TranslationHelperFunc) inventory.ServerTool } message := fmt.Sprintf("successfully downloaded text file (SHA: %s)%s", fileSHA, successNote) message = repositoryReadMessage(read, message, successNote) - return attachIFC(utils.NewToolResultResource(message, result)), nil, nil + return repositoryContentResult(attachIFC(utils.NewToolResultResource(message, result))) } result := &mcp.ResourceContents{ @@ -1169,7 +1188,7 @@ func GetFileContents(t translations.TranslationHelperFunc) inventory.ServerTool } message := fmt.Sprintf("successfully downloaded binary file (SHA: %s)%s", fileSHA, successNote) message = repositoryReadMessage(read, message, successNote) - return attachIFC(utils.NewToolResultResource(message, result)), nil, nil + return repositoryContentResult(attachIFC(utils.NewToolResultResource(message, result))) } else if dirContent != nil { // file content or file SHA is nil which means it's a directory filtered := false @@ -1187,11 +1206,23 @@ func GetFileContents(t translations.TranslationHelperFunc) inventory.ServerTool return utils.NewToolResultError("failed to marshal response"), nil, nil } recordDirContentsFieldsUsage(ctx, deps, dirContent, filtered, len(r)) - return attachIFC(utils.NewToolResultText(string(r))), nil, nil + var output []*RepositoryDirectoryEntryOutput + if err := json.Unmarshal(r, &output); err != nil { + return nil, nil, fmt.Errorf("failed to decode typed directory contents: %w", err) + } + if len(fields) == 0 { + for _, entry := range output { + if entry != nil { + entry.URL, entry.GitURL = nil, nil + } + } + } + return attachIFC(utils.NewToolResultText(string(r))), &RepositoryContentsOutput{Directory: output}, nil } return utils.NewToolResultError("failed to get file contents"), nil, nil }, + normalizeRepositoryFieldsArguments, ) } @@ -1203,12 +1234,13 @@ func recordDirContentsFieldsUsage(ctx context.Context, deps ToolDependencies, fu // ForkRepository creates a tool to fork a repository. func ForkRepository(t translations.TranslationHelperFunc) inventory.ServerTool { - return NewTool( + return NewTool[ForkRepositoryInput, *ForkRepositoryOutput]( ToolsetMetadataRepos, mcp.Tool{ - Name: "fork_repository", - Description: t("TOOL_FORK_REPOSITORY_DESCRIPTION", "Fork a GitHub repository to your account or specified organization"), - Icons: octicons.Icons("repo-forked"), + Name: "fork_repository", + OutputSchema: forkRepositoryOutputSchema(), + Description: t("TOOL_FORK_REPOSITORY_DESCRIPTION", "Fork a GitHub repository to your account or specified organization"), + Icons: octicons.Icons("repo-forked"), Annotations: &mcp.ToolAnnotations{ Title: t("TOOL_FORK_REPOSITORY_USER_TITLE", "Fork repository"), ReadOnlyHint: false, @@ -1233,19 +1265,16 @@ func ForkRepository(t translations.TranslationHelperFunc) inventory.ServerTool { }, }, publicRepositoryWriteScopeAccess(), - func(ctx context.Context, deps ToolDependencies, _ *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 + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, input ForkRepositoryInput) (*mcp.CallToolResult, *ForkRepositoryOutput, error) { + owner := input.Owner + if owner == "" { + return utils.NewToolResultError("missing required parameter: owner"), nil, nil } - repo, err := RequiredParam[string](args, "repo") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - org, err := OptionalParam[string](args, "organization") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil + repo := input.Repo + if repo == "" { + return utils.NewToolResultError("missing required parameter: repo"), nil, nil } + org := input.Organization opts := &github.RepositoryCreateForkOptions{} if org != "" { @@ -1261,7 +1290,7 @@ func ForkRepository(t translations.TranslationHelperFunc) inventory.ServerTool { // Check if it's an acceptedError. An acceptedError indicates that the update is in progress, // and it's not a real error. if resp != nil && resp.StatusCode == http.StatusAccepted && isAcceptedError(err) { - return utils.NewToolResultText("Fork is in progress"), nil, nil + return utils.NewToolResultText("Fork is in progress"), &ForkRepositoryOutput{Message: &RepositoryMessageOutput{Message: "Fork is in progress"}}, nil } return ghErrors.NewGitHubAPIErrorResponse(ctx, "failed to fork repository", @@ -1290,7 +1319,7 @@ func ForkRepository(t translations.TranslationHelperFunc) inventory.ServerTool { return nil, nil, fmt.Errorf("failed to marshal response: %w", err) } - return utils.NewToolResultText(string(r)), nil, nil + return utils.NewToolResultText(string(r)), &ForkRepositoryOutput{Repository: &minimalResponse}, nil }, ) } @@ -1302,15 +1331,16 @@ func ForkRepository(t translations.TranslationHelperFunc) inventory.ServerTool { // The approach implemented here gets automatic commit signing when used with either the github-actions user or as an app, // both of which suit an LLM well. func DeleteFile(t translations.TranslationHelperFunc) inventory.ServerTool { - tool := NewTool( + tool := NewTool[DeleteFileInput, *DeleteFileOutput]( ToolsetMetadataRepos, mcp.Tool{ - Name: "delete_file", - Description: t("TOOL_DELETE_FILE_DESCRIPTION", "Delete a file from a GitHub repository"), + Name: "delete_file", + OutputSchema: deleteFileOutputSchema(), + Description: t("TOOL_DELETE_FILE_DESCRIPTION", "Delete a file from a GitHub repository"), Annotations: &mcp.ToolAnnotations{ Title: t("TOOL_DELETE_FILE_USER_TITLE", "Delete file"), ReadOnlyHint: false, - DestructiveHint: github.Ptr(true), + DestructiveHint: new(true), }, InputSchema: &jsonschema.Schema{ Type: "object", @@ -1340,30 +1370,30 @@ func DeleteFile(t translations.TranslationHelperFunc) inventory.ServerTool { }, }, scopes.RequireAll(scopes.Repo), - func(ctx context.Context, deps ToolDependencies, _ *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 + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, input DeleteFileInput) (*mcp.CallToolResult, *DeleteFileOutput, error) { + owner := input.Owner + if owner == "" { + return utils.NewToolResultError("missing required parameter: owner"), nil, nil } - repo, err := RequiredParam[string](args, "repo") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil + repo := input.Repo + if repo == "" { + return utils.NewToolResultError("missing required parameter: repo"), nil, nil } - path, err := RequiredParam[string](args, "path") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil + path := input.Path + if path == "" { + return utils.NewToolResultError("missing required parameter: path"), nil, nil } - path, err = validateRelativePath(path) + path, err := validateRelativePath(path) if err != nil { return utils.NewToolResultError(fmt.Sprintf("invalid path: %s", err)), nil, nil } - message, err := RequiredParam[string](args, "message") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil + message := input.Message + if message == "" { + return utils.NewToolResultError("missing required parameter: message"), nil, nil } - branch, err := RequiredParam[string](args, "branch") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil + branch := input.Branch + if branch == "" { + return utils.NewToolResultError("missing required parameter: branch"), nil, nil } client, err := deps.GetClient(ctx) @@ -1400,9 +1430,9 @@ func DeleteFile(t translations.TranslationHelperFunc) inventory.ServerTool { // Create a tree entry for the file deletion by setting SHA to nil treeEntries := []*github.TreeEntry{ { - Path: github.Ptr(path), - Mode: github.Ptr("100644"), // Regular file mode - Type: github.Ptr("blob"), + Path: new(path), + Mode: new("100644"), // Regular file mode + Type: new("blob"), SHA: nil, // Setting SHA to nil deletes the file }, } @@ -1428,7 +1458,7 @@ func DeleteFile(t translations.TranslationHelperFunc) inventory.ServerTool { // Create a new commit with the new tree commit := github.Commit{ - Message: github.Ptr(message), + Message: new(message), Tree: newTree, Parents: []*github.Commit{{SHA: baseCommit.SHA}}, } @@ -1454,7 +1484,7 @@ func DeleteFile(t translations.TranslationHelperFunc) inventory.ServerTool { ref.Object.SHA = newCommit.SHA _, resp, err = client.Git.UpdateRef(ctx, owner, repo, *ref.Ref, github.UpdateRef{ SHA: *newCommit.SHA, - Force: github.Ptr(false), + Force: new(false), }) if err != nil { return ghErrors.NewGitHubAPIErrorResponse(ctx, @@ -1474,17 +1504,17 @@ func DeleteFile(t translations.TranslationHelperFunc) inventory.ServerTool { } // Create a response similar to what the DeleteFile API would return - response := map[string]any{ - "commit": newCommit, - "content": nil, - } + response := struct { + Commit *github.Commit `json:"commit"` + Content *struct{} `json:"content"` + }{Commit: newCommit} 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 + return utils.NewToolResultText(string(r)), &DeleteFileOutput{Commit: repositoryGitCommitOutput(newCommit)}, nil }, ) tool.ScopeAccess = scopes.DynamicChallenge( @@ -1497,7 +1527,7 @@ func DeleteFile(t translations.TranslationHelperFunc) inventory.ServerTool { // CreateBranch creates a tool to create a new branch. func CreateBranch(t translations.TranslationHelperFunc) inventory.ServerTool { - return NewTool( + return NewTool[CreateBranchInput, *RepositoryReferenceOutput]( ToolsetMetadataRepos, mcp.Tool{ Name: "create_branch", @@ -1530,23 +1560,20 @@ func CreateBranch(t translations.TranslationHelperFunc) inventory.ServerTool { }, }, publicRepositoryWriteScopeAccess(), - func(ctx context.Context, deps ToolDependencies, _ *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 + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, input CreateBranchInput) (*mcp.CallToolResult, *RepositoryReferenceOutput, error) { + owner := input.Owner + if owner == "" { + return utils.NewToolResultError("missing required parameter: owner"), nil, nil } - repo, err := RequiredParam[string](args, "repo") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil + repo := input.Repo + if repo == "" { + return utils.NewToolResultError("missing required parameter: repo"), nil, nil } - branch, err := RequiredParam[string](args, "branch") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - fromBranch, err := OptionalParam[string](args, "from_branch") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil + branch := input.Branch + if branch == "" { + return utils.NewToolResultError("missing required parameter: branch"), nil, nil } + fromBranch := input.FromBranch client, err := deps.GetClient(ctx) if err != nil { @@ -1603,14 +1630,14 @@ func CreateBranch(t translations.TranslationHelperFunc) inventory.ServerTool { return nil, nil, fmt.Errorf("failed to marshal response: %w", err) } - return utils.NewToolResultText(string(r)), nil, nil + return utils.NewToolResultText(string(r)), repositoryReferenceOutput(createdRef), nil }, ) } // PushFiles creates a tool to push multiple files in a single commit to a GitHub repository. func PushFiles(t translations.TranslationHelperFunc) inventory.ServerTool { - tool := NewTool( + tool := NewTool[PushFilesInput, *RepositoryReferenceOutput]( ToolsetMetadataRepos, mcp.Tool{ Name: "push_files", @@ -1662,56 +1689,46 @@ func PushFiles(t translations.TranslationHelperFunc) inventory.ServerTool { }, }, publicRepositoryWriteScopeAccess(), - func(ctx context.Context, deps ToolDependencies, _ *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 + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, input PushFilesInput) (*mcp.CallToolResult, *RepositoryReferenceOutput, error) { + owner := input.Owner + if owner == "" { + return utils.NewToolResultError("missing required parameter: owner"), nil, nil } - repo, err := RequiredParam[string](args, "repo") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil + repo := input.Repo + if repo == "" { + return utils.NewToolResultError("missing required parameter: repo"), nil, nil } - branch, err := RequiredParam[string](args, "branch") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil + branch := input.Branch + if branch == "" { + return utils.NewToolResultError("missing required parameter: branch"), nil, nil } - message, err := RequiredParam[string](args, "message") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil + message := input.Message + if message == "" { + return utils.NewToolResultError("missing required parameter: message"), nil, nil } - // Parse files parameter - this should be an array of objects with path and content - filesObj, ok := args["files"].([]any) - if !ok { + if input.Files == nil { return utils.NewToolResultError("files parameter must be an array of objects with path and content"), nil, nil } - - entries := make([]*github.TreeEntry, 0, len(filesObj)) - for _, file := range filesObj { - fileMap, ok := file.(map[string]any) - if !ok { - return utils.NewToolResultError("each file must be an object with path and content"), nil, nil - } - - filePath, ok := fileMap["path"].(string) - if !ok || filePath == "" { + entries := make([]*github.TreeEntry, 0, len(input.Files)) + for _, file := range input.Files { + if file.Path == "" { return utils.NewToolResultError("each file must have a path"), nil, nil } - filePath, err = validateRelativePath(filePath) + filePath, err := validateRelativePath(file.Path) if err != nil { return utils.NewToolResultError(fmt.Sprintf("invalid file path: %s", err)), nil, nil } - - content, ok := fileMap["content"].(string) - if !ok { + if file.Content == nil { return utils.NewToolResultError("each file must have content"), nil, nil } + content := *file.Content entries = append(entries, &github.TreeEntry{ - Path: github.Ptr(filePath), - Mode: github.Ptr("100644"), - Type: github.Ptr("blob"), - Content: github.Ptr(content), + Path: new(filePath), + Mode: new("100644"), + Type: new("blob"), + Content: new(content), }) } @@ -1803,7 +1820,7 @@ func PushFiles(t translations.TranslationHelperFunc) inventory.ServerTool { // Create a new commit (baseCommit always has a value now) commit := github.Commit{ - Message: github.Ptr(message), + Message: new(message), Tree: newTree, Parents: []*github.Commit{{SHA: baseCommit.SHA}}, } @@ -1823,7 +1840,7 @@ func PushFiles(t translations.TranslationHelperFunc) inventory.ServerTool { ref.Object.SHA = newCommit.SHA updatedRef, resp, err := client.Git.UpdateRef(ctx, owner, repo, *ref.Ref, github.UpdateRef{ SHA: *newCommit.SHA, - Force: github.Ptr(false), + Force: new(false), }) if err != nil { return ghErrors.NewGitHubAPIErrorResponse(ctx, @@ -1839,8 +1856,9 @@ func PushFiles(t translations.TranslationHelperFunc) inventory.ServerTool { return nil, nil, fmt.Errorf("failed to marshal response: %w", err) } - return utils.NewToolResultText(string(r)), nil, nil + return utils.NewToolResultText(string(r)), repositoryReferenceOutput(updatedRef), nil }, + normalizePushFilesArguments, ) tool.ScopeAccess = scopes.DynamicChallenge( []scopes.Scope{scopes.Repo, scopes.Workflow}, @@ -1852,7 +1870,7 @@ func PushFiles(t translations.TranslationHelperFunc) inventory.ServerTool { // ListTags creates a tool to list tags in a GitHub repository. func ListTags(t translations.TranslationHelperFunc) inventory.ServerTool { - return NewTool( + return NewTool[RepositoryListInput, []MinimalTag]( ToolsetMetadataRepos, mcp.Tool{ Name: "list_tags", @@ -1877,18 +1895,19 @@ func ListTags(t translations.TranslationHelperFunc) inventory.ServerTool { }), }, scopes.PublicRead(scopes.Repo), - func(ctx context.Context, deps ToolDependencies, _ *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 + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, input RepositoryListInput) (*mcp.CallToolResult, []MinimalTag, error) { + if input.Owner == "" { + return utils.NewToolResultError("missing required parameter: owner"), nil, nil } - repo, err := RequiredParam[string](args, "repo") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil + if input.Repo == "" { + return utils.NewToolResultError("missing required parameter: repo"), nil, nil } - pagination, err := OptionalPaginationParams(args) - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil + pagination := PaginationParams{Page: 1, PerPage: 30} + if input.Page != nil { + pagination.Page = *input.Page + } + if input.PerPage != nil { + pagination.PerPage = *input.PerPage } opts := &github.ListOptions{ @@ -1901,7 +1920,7 @@ func ListTags(t translations.TranslationHelperFunc) inventory.ServerTool { return nil, nil, fmt.Errorf("failed to get GitHub client: %w", err) } - tags, resp, err := client.Repositories.ListTags(ctx, owner, repo, opts) + tags, resp, err := client.Repositories.ListTags(ctx, input.Owner, input.Repo, opts) if err != nil { return ghErrors.NewGitHubAPIErrorResponse(ctx, "failed to list tags", @@ -1935,19 +1954,21 @@ func ListTags(t translations.TranslationHelperFunc) inventory.ServerTool { // Tags are structural repo metadata created by collaborators with // push access, so integrity is trusted. Confidentiality follows // repo visibility. - result = attachRepoVisibilityIFCLabel(ctx, deps, client, owner, repo, result, ifc.LabelRepoMetadata) - return result, nil, nil + result = attachRepoVisibilityIFCLabel(ctx, deps, client, input.Owner, input.Repo, result, ifc.LabelRepoMetadata) + return result, minimalTags, nil }, + normalizeTypedReadArguments(nil, false), ) } // GetTag creates a tool to get details about a specific tag in a GitHub repository. func GetTag(t translations.TranslationHelperFunc) inventory.ServerTool { - return NewTool( + return NewTool[RepositoryTagInput, *RepositoryTagOutput]( ToolsetMetadataRepos, mcp.Tool{ - Name: "get_tag", - Description: t("TOOL_GET_TAG_DESCRIPTION", "Get details about a specific git tag in a GitHub repository"), + Name: "get_tag", + OutputSchema: repositoryTagOutputSchema(), + Description: t("TOOL_GET_TAG_DESCRIPTION", "Get details about a specific git tag in a GitHub repository"), Annotations: &mcp.ToolAnnotations{ Title: t("TOOL_GET_TAG_USER_TITLE", "Get tag details"), ReadOnlyHint: true, @@ -1972,18 +1993,18 @@ func GetTag(t translations.TranslationHelperFunc) inventory.ServerTool { }, }, scopes.PublicRead(scopes.Repo), - func(ctx context.Context, deps ToolDependencies, _ *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 + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, input RepositoryTagInput) (*mcp.CallToolResult, *RepositoryTagOutput, error) { + owner := input.Owner + if owner == "" { + return utils.NewToolResultError("missing required parameter: owner"), nil, nil } - repo, err := RequiredParam[string](args, "repo") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil + repo := input.Repo + if repo == "" { + return utils.NewToolResultError("missing required parameter: repo"), nil, nil } - tag, err := RequiredParam[string](args, "tag") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil + tag := input.Tag + if tag == "" { + return utils.NewToolResultError("missing required parameter: tag"), nil, nil } client, err := deps.GetClient(ctx) @@ -2018,7 +2039,7 @@ func GetTag(t translations.TranslationHelperFunc) inventory.ServerTool { } result := utils.NewToolResultText(string(r)) result = attachRepoVisibilityIFCLabel(ctx, deps, client, owner, repo, result, ifc.LabelRepoMetadata) - return result, nil, nil + return result, &RepositoryTagOutput{Reference: repositoryReferenceOutput(ref)}, nil } tagObj, resp, err := client.Git.GetTag(ctx, owner, repo, *ref.Object.SHA) @@ -2049,7 +2070,7 @@ func GetTag(t translations.TranslationHelperFunc) inventory.ServerTool { // collaborator with push access. Confidentiality follows repo // visibility. result = attachRepoVisibilityIFCLabel(ctx, deps, client, owner, repo, result, ifc.LabelRepoMetadata) - return result, nil, nil + return result, &RepositoryTagOutput{Tag: repositoryAnnotatedTagOutput(tagObj)}, nil }, ) } @@ -2076,7 +2097,7 @@ func ListReleases(t translations.TranslationHelperFunc) inventory.ServerTool { ) WithPagination(schema) - return NewTool( + return NewTool[ListReleasesInput, []ReleaseListOutput]( ToolsetMetadataRepos, mcp.Tool{ Name: "list_releases", @@ -2088,23 +2109,17 @@ func ListReleases(t translations.TranslationHelperFunc) inventory.ServerTool { InputSchema: schema, }, scopes.PublicRead(scopes.Repo), - func(ctx context.Context, deps ToolDependencies, _ *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 + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, input ListReleasesInput) (*mcp.CallToolResult, []ReleaseListOutput, error) { + owner := input.Owner + if owner == "" { + return utils.NewToolResultError("missing required parameter: owner"), nil, nil } - repo, err := RequiredParam[string](args, "repo") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - fields, err := OptionalStringArrayParam(args, "fields") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - pagination, err := OptionalPaginationParams(args) - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil + repo := input.Repo + if repo == "" { + return utils.NewToolResultError("missing required parameter: repo"), nil, nil } + fields := input.Fields + pagination := repositoryPagination(input.Page, input.PerPage) opts := &github.ListOptions{ Page: pagination.Page, @@ -2172,18 +2187,25 @@ func ListReleases(t translations.TranslationHelperFunc) inventory.ServerTool { func(isPrivate bool) ifc.SecurityLabel { return ifc.LabelRelease(isPrivate, hasDraft) }) - return result, nil, nil + var output []ReleaseListOutput + if err := json.Unmarshal(r, &output); err != nil { + return nil, nil, fmt.Errorf("failed to decode typed releases: %w", err) + } + return result, output, nil }, + normalizeRepositoryFieldsArguments, + normalizeRepositoryArguments, ) } // GetLatestRelease creates a tool to get the latest release in a GitHub repository. func GetLatestRelease(t translations.TranslationHelperFunc) inventory.ServerTool { - return NewTool( + return NewTool[RepositoryInput, *MinimalRelease]( ToolsetMetadataRepos, mcp.Tool{ - Name: "get_latest_release", - Description: t("TOOL_GET_LATEST_RELEASE_DESCRIPTION", "Get the latest release in a GitHub repository"), + Name: "get_latest_release", + OutputSchema: repositoryReleaseOutputSchema(), + Description: t("TOOL_GET_LATEST_RELEASE_DESCRIPTION", "Get the latest release in a GitHub repository"), Annotations: &mcp.ToolAnnotations{ Title: t("TOOL_GET_LATEST_RELEASE_USER_TITLE", "Get latest release"), ReadOnlyHint: true, @@ -2204,14 +2226,14 @@ func GetLatestRelease(t translations.TranslationHelperFunc) inventory.ServerTool }, }, scopes.PublicRead(scopes.Repo), - func(ctx context.Context, deps ToolDependencies, _ *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 + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, input RepositoryInput) (*mcp.CallToolResult, *MinimalRelease, error) { + owner := input.Owner + if owner == "" { + return utils.NewToolResultError("missing required parameter: owner"), nil, nil } - repo, err := RequiredParam[string](args, "repo") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil + repo := input.Repo + if repo == "" { + return utils.NewToolResultError("missing required parameter: repo"), nil, nil } client, err := deps.GetClient(ctx) @@ -2248,17 +2270,19 @@ func GetLatestRelease(t translations.TranslationHelperFunc) inventory.ServerTool func(isPrivate bool) ifc.SecurityLabel { return ifc.LabelRelease(isPrivate, release.GetDraft()) }) - return result, nil, nil + output := convertToMinimalRelease(release) + return result, &output, nil }, ) } func GetReleaseByTag(t translations.TranslationHelperFunc) inventory.ServerTool { - return NewTool( + return NewTool[RepositoryTagInput, *MinimalRelease]( ToolsetMetadataRepos, mcp.Tool{ - Name: "get_release_by_tag", - Description: t("TOOL_GET_RELEASE_BY_TAG_DESCRIPTION", "Get a specific release by its tag name in a GitHub repository"), + Name: "get_release_by_tag", + OutputSchema: repositoryReleaseOutputSchema(), + Description: t("TOOL_GET_RELEASE_BY_TAG_DESCRIPTION", "Get a specific release by its tag name in a GitHub repository"), Annotations: &mcp.ToolAnnotations{ Title: t("TOOL_GET_RELEASE_BY_TAG_USER_TITLE", "Get a release by tag name"), ReadOnlyHint: true, @@ -2283,18 +2307,18 @@ func GetReleaseByTag(t translations.TranslationHelperFunc) inventory.ServerTool }, }, scopes.PublicRead(scopes.Repo), - func(ctx context.Context, deps ToolDependencies, _ *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 + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, input RepositoryTagInput) (*mcp.CallToolResult, *MinimalRelease, error) { + owner := input.Owner + if owner == "" { + return utils.NewToolResultError("missing required parameter: owner"), nil, nil } - repo, err := RequiredParam[string](args, "repo") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil + repo := input.Repo + if repo == "" { + return utils.NewToolResultError("missing required parameter: repo"), nil, nil } - tag, err := RequiredParam[string](args, "tag") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil + tag := input.Tag + if tag == "" { + return utils.NewToolResultError("missing required parameter: tag"), nil, nil } client, err := deps.GetClient(ctx) @@ -2335,7 +2359,8 @@ func GetReleaseByTag(t translations.TranslationHelperFunc) inventory.ServerTool func(isPrivate bool) ifc.SecurityLabel { return ifc.LabelRelease(isPrivate, release.GetDraft()) }) - return result, nil, nil + output := convertToMinimalRelease(release) + return result, &output, nil }, ) } @@ -2345,16 +2370,16 @@ func sanitizeReleaseNameAndBody(release *github.RepositoryRelease) { return } if release.Name != nil { - release.Name = github.Ptr(sanitize.PlainText(*release.Name)) + release.Name = new(sanitize.PlainText(*release.Name)) } if release.Body != nil { - release.Body = github.Ptr(sanitize.Content(*release.Body)) + release.Body = new(sanitize.Content(*release.Body)) } } // ListStarredRepositories creates a tool to list starred repositories for the authenticated user or a specified user. func ListStarredRepositories(t translations.TranslationHelperFunc) inventory.ServerTool { - return NewTool( + return NewTool[ListStarredRepositoriesInput, []MinimalRepository]( ToolsetMetadataStargazers, mcp.Tool{ Name: "list_starred_repositories", @@ -2384,29 +2409,15 @@ func ListStarredRepositories(t translations.TranslationHelperFunc) inventory.Ser }), }, scopes.PublicRead(scopes.Repo), - func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, args map[string]any) (*mcp.CallToolResult, any, error) { - username, err := OptionalParam[string](args, "username") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - sort, err := OptionalParam[string](args, "sort") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - direction, err := OptionalParam[string](args, "direction") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - pagination, err := OptionalPaginationParams(args) - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, input ListStarredRepositoriesInput) (*mcp.CallToolResult, []MinimalRepository, error) { + username := input.Username + sort := input.Sort + direction := input.Direction + pagination := repositoryPagination(input.Page, input.PerPage) opts := &github.ActivityListStarredOptions{ - ListOptions: github.ListOptions{ - Page: pagination.Page, - PerPage: pagination.PerPage, - }, + Page: pagination.Page, + PerPage: pagination.PerPage, } if sort != "" { opts.Sort = sort @@ -2491,14 +2502,15 @@ func ListStarredRepositories(t translations.TranslationHelperFunc) inventory.Ser visibilities = append(visibilities, mr.Private) } result = attachJoinedIFCLabel(ctx, deps, result, visibilities, ifc.LabelSearchIssues) - return result, nil, nil + return result, minimalRepos, nil }, + normalizeRepositoryArguments, ) } // StarRepository creates a tool to star a repository. func StarRepository(t translations.TranslationHelperFunc) inventory.ServerTool { - return NewTool( + return NewTool[RepositoryInput, *RepositoryMessageOutput]( ToolsetMetadataStargazers, mcp.Tool{ Name: "star_repository", @@ -2524,14 +2536,14 @@ func StarRepository(t translations.TranslationHelperFunc) inventory.ServerTool { }, }, scopes.RequireAll(scopes.Repo), - func(ctx context.Context, deps ToolDependencies, _ *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 + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, input RepositoryInput) (*mcp.CallToolResult, *RepositoryMessageOutput, error) { + owner := input.Owner + if owner == "" { + return utils.NewToolResultError("missing required parameter: owner"), nil, nil } - repo, err := RequiredParam[string](args, "repo") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil + repo := input.Repo + if repo == "" { + return utils.NewToolResultError("missing required parameter: repo"), nil, nil } client, err := deps.GetClient(ctx) @@ -2557,14 +2569,15 @@ func StarRepository(t translations.TranslationHelperFunc) inventory.ServerTool { return ghErrors.NewGitHubAPIStatusErrorResponse(ctx, "failed to star repository", resp, body), nil, nil } - return utils.NewToolResultText(fmt.Sprintf("Successfully starred repository %s/%s", owner, repo)), nil, nil + message := fmt.Sprintf("Successfully starred repository %s/%s", owner, repo) + return utils.NewToolResultText(message), &RepositoryMessageOutput{Message: message}, nil }, ) } // UnstarRepository creates a tool to unstar a repository. func UnstarRepository(t translations.TranslationHelperFunc) inventory.ServerTool { - return NewTool( + return NewTool[RepositoryInput, *RepositoryMessageOutput]( ToolsetMetadataStargazers, mcp.Tool{ Name: "unstar_repository", @@ -2589,14 +2602,14 @@ func UnstarRepository(t translations.TranslationHelperFunc) inventory.ServerTool }, }, scopes.RequireAll(scopes.Repo), - func(ctx context.Context, deps ToolDependencies, _ *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 + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, input RepositoryInput) (*mcp.CallToolResult, *RepositoryMessageOutput, error) { + owner := input.Owner + if owner == "" { + return utils.NewToolResultError("missing required parameter: owner"), nil, nil } - repo, err := RequiredParam[string](args, "repo") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil + repo := input.Repo + if repo == "" { + return utils.NewToolResultError("missing required parameter: repo"), nil, nil } client, err := deps.GetClient(ctx) @@ -2622,7 +2635,8 @@ func UnstarRepository(t translations.TranslationHelperFunc) inventory.ServerTool return ghErrors.NewGitHubAPIStatusErrorResponse(ctx, "failed to unstar repository", resp, body), nil, nil } - return utils.NewToolResultText(fmt.Sprintf("Successfully unstarred repository %s/%s", owner, repo)), nil, nil + message := fmt.Sprintf("Successfully unstarred repository %s/%s", owner, repo) + return utils.NewToolResultText(message), &RepositoryMessageOutput{Message: message}, nil }, ) } @@ -2671,7 +2685,7 @@ type BlameAuthor struct { type BlameCommit struct { SHA string `json:"sha"` MessageHeadline string `json:"message_headline"` - CommittedDate string `json:"committed_date"` + CommittedDate string `json:"committed_date" jsonschema:"Commit timestamp in RFC3339 format."` Author BlameAuthor `json:"author"` } @@ -2681,9 +2695,9 @@ type BlameCommit struct { // touching the file (0 = newest), not an absolute time delta. See: // https://docs.github.com/en/graphql/reference/objects#blamerange type BlameRange struct { - StartingLine int `json:"starting_line"` - EndingLine int `json:"ending_line"` - Age int `json:"age"` + StartingLine int `json:"starting_line" jsonschema:"First line of the inclusive, one-based range."` + EndingLine int `json:"ending_line" jsonschema:"Last line of the inclusive, one-based range."` + Age int `json:"age" jsonschema:"Relative commit age among commits touching this file; 0 is newest."` CommitSHA string `json:"commit_sha"` } @@ -2698,8 +2712,8 @@ type BlameResult struct { Ranges []BlameRange `json:"ranges"` Commits map[string]BlameCommit `json:"commits"` PageInfo MinimalPageInfo `json:"pageInfo"` - TotalRanges int `json:"total_ranges"` - Truncated bool `json:"truncated,omitempty"` + TotalRanges int `json:"total_ranges" jsonschema:"Matching ranges before pagination or truncation."` + Truncated bool `json:"truncated,omitempty" jsonschema:"Whether the 1000-range safety limit was reached."` } // blameCommitFragment is the GraphQL selection for a Commit's blame data. @@ -2747,10 +2761,11 @@ func validateBlamePath(p string) error { } func GetFileBlame(t translations.TranslationHelperFunc) inventory.ServerTool { - st := NewTool( + st := NewTool[GetFileBlameInput, *RepositoryBlameOutput]( ToolsetMetadataRepos, mcp.Tool{ - Name: "get_file_blame", + Name: "get_file_blame", + OutputSchema: repositoryUnionSchema(&jsonschema.Schema{Type: "null"}, repositoryOutputSchema[BlameResult]()), Description: t("TOOL_GET_FILE_BLAME_DESCRIPTION", "Get git blame information for a file, showing the commit that last modified each line. "+ "Ranges share commit metadata via the top-level 'commits' map keyed by SHA. "+ @@ -2784,50 +2799,47 @@ func GetFileBlame(t translations.TranslationHelperFunc) inventory.ServerTool { "start_line": { Type: "number", Description: "Optional 1-based starting line of the window of interest. Only ranges overlapping [start_line, end_line] are returned, clamped to the window.", - Minimum: jsonschema.Ptr(1.0), + Minimum: new(1.0), }, "end_line": { Type: "number", Description: "Optional 1-based ending line of the window of interest. Must be >= start_line when both are provided.", - Minimum: jsonschema.Ptr(1.0), + Minimum: new(1.0), }, }, Required: []string{"owner", "repo", "path"}, }), }, scopes.PublicRead(scopes.Repo), - func(ctx context.Context, deps ToolDependencies, _ *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 + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, input GetFileBlameInput) (*mcp.CallToolResult, *RepositoryBlameOutput, error) { + owner := input.Owner + if owner == "" { + return utils.NewToolResultError("missing required parameter: owner"), nil, nil } - repo, err := RequiredParam[string](args, "repo") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil + repo := input.Repo + if repo == "" { + return utils.NewToolResultError("missing required parameter: repo"), nil, nil } - path, err := RequiredParam[string](args, "path") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil + path := input.Path + if path == "" { + return utils.NewToolResultError("missing required parameter: path"), nil, nil } if err := validateBlamePath(path); err != nil { return utils.NewToolResultError(err.Error()), nil, nil } - ref, err := OptionalParam[string](args, "ref") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - _, hasStartLine := args["start_line"] - startLine, err := OptionalIntParam(args, "start_line") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil + ref := input.Ref + hasStartLine := input.StartLine != nil + startLine := 0 + if hasStartLine { + startLine = *input.StartLine } if hasStartLine && startLine < 1 { return utils.NewToolResultError("start_line must be omitted or >= 1"), nil, nil } - _, hasEndLine := args["end_line"] - endLine, err := OptionalIntParam(args, "end_line") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil + hasEndLine := input.EndLine != nil + endLine := 0 + if hasEndLine { + endLine = *input.EndLine } if hasEndLine && endLine < 1 { return utils.NewToolResultError("end_line must be omitted or >= 1"), nil, nil @@ -2835,23 +2847,14 @@ func GetFileBlame(t translations.TranslationHelperFunc) inventory.ServerTool { if hasStartLine && hasEndLine && endLine < startLine { return utils.NewToolResultError("end_line must be >= start_line when both are provided"), nil, nil } - if _, hasPage := args["page"]; hasPage { - return utils.NewToolResultError("This tool uses cursor-based pagination. Use the 'after' parameter with the 'endCursor' value from the previous response instead of 'page'."), nil, nil - } - pagination, err := OptionalCursorPaginationParams(args) - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - if _, hasPerPage := args["perPage"]; hasPerPage { - perPage, err := OptionalIntParam(args, "perPage") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - if perPage < 1 || perPage > 100 { + pagination := CursorPaginationParams{After: input.After, PerPage: 30} + if input.PerPage != nil { + if *input.PerPage < 1 || *input.PerPage > 100 { return utils.NewToolResultError("perPage must be between 1 and 100 when provided"), nil, nil } - pagination.PerPage = perPage + pagination.PerPage = *input.PerPage } + afterOffset, err := decodeBlameCursor(pagination.After) if err != nil { return utils.NewToolResultError(err.Error()), nil, nil @@ -3041,8 +3044,11 @@ func GetFileBlame(t translations.TranslationHelperFunc) inventory.ServerTool { return nil, nil, fmt.Errorf("failed to marshal response: %w", err) } - return utils.NewToolResultText(string(payload)), nil, nil + callResult := utils.NewToolResultText(string(payload)) + callResult = attachRepoVisibilityIFCLabelLazy(ctx, deps, owner, repo, callResult, ifc.LabelCommitContents) + return callResult, &RepositoryBlameOutput{Result: &result}, nil }, + normalizeRepositoryBlameArguments, ) st.FeatureRule = featureEnabledRule(FeatureFlagFileBlame) return st @@ -3050,7 +3056,7 @@ func GetFileBlame(t translations.TranslationHelperFunc) inventory.ServerTool { // ListRepositoryCollaborators creates a tool to list collaborators of a GitHub repository. func ListRepositoryCollaborators(t translations.TranslationHelperFunc) inventory.ServerTool { - return NewTool( + return NewTool[ListRepositoryCollaboratorsInput, *RepositoryCollaboratorsOutput]( ToolsetMetadataRepos, mcp.Tool{ Name: "list_repository_collaborators", @@ -3085,23 +3091,17 @@ func ListRepositoryCollaborators(t translations.TranslationHelperFunc) inventory }(), }, scopes.PublicRead(scopes.Repo), - func(ctx context.Context, deps ToolDependencies, _ *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 + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, input ListRepositoryCollaboratorsInput) (*mcp.CallToolResult, *RepositoryCollaboratorsOutput, error) { + owner := input.Owner + if owner == "" { + return utils.NewToolResultError("missing required parameter: owner"), nil, nil } - repo, err := RequiredParam[string](args, "repo") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - affiliation, err := OptionalParam[string](args, "affiliation") - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil - } - pagination, err := OptionalPaginationParams(args) - if err != nil { - return utils.NewToolResultError(err.Error()), nil, nil + repo := input.Repo + if repo == "" { + return utils.NewToolResultError("missing required parameter: repo"), nil, nil } + affiliation := input.Affiliation + pagination := repositoryPagination(input.Page, input.PerPage) client, err := deps.GetClient(ctx) if err != nil { @@ -3110,10 +3110,8 @@ func ListRepositoryCollaborators(t translations.TranslationHelperFunc) inventory opts := &github.ListCollaboratorsOptions{ Affiliation: affiliation, - ListOptions: github.ListOptions{ - Page: pagination.Page, - PerPage: pagination.PerPage, - }, + Page: pagination.Page, + PerPage: pagination.PerPage, } collaborators, resp, err := client.Repositories.ListCollaborators(ctx, owner, repo, opts) @@ -3143,12 +3141,9 @@ func ListRepositoryCollaborators(t translations.TranslationHelperFunc) inventory }) } - response := map[string]any{ - "items": result, - "nextPage": resp.NextPage, - "prevPage": resp.PrevPage, - "firstPage": resp.FirstPage, - "lastPage": resp.LastPage, + response := &RepositoryCollaboratorsOutput{ + Items: result, NextPage: resp.NextPage, PrevPage: resp.PrevPage, + FirstPage: resp.FirstPage, LastPage: resp.LastPage, } callResult := MarshalledTextResult(response) @@ -3157,7 +3152,8 @@ func ListRepositoryCollaborators(t translations.TranslationHelperFunc) inventory // push access, so the roster is never world-readable — not even on // a public repo — hence always private confidentiality. callResult = attachStaticIFCLabel(ctx, deps, callResult, ifc.LabelCollaboratorRoster()) - return callResult, nil, nil + return callResult, response, nil }, + normalizeRepositoryArguments, ) } diff --git a/pkg/github/repositories_helper.go b/pkg/github/repositories_helper.go index 8859b4a2ba..fe1983252c 100644 --- a/pkg/github/repositories_helper.go +++ b/pkg/github/repositories_helper.go @@ -12,10 +12,10 @@ import ( "strings" "unicode/utf8" - ghErrors "github.com/github/github-mcp-server/pkg/errors" - "github.com/github/github-mcp-server/pkg/raw" - "github.com/github/github-mcp-server/pkg/utils" - "github.com/google/go-github/v89/github" + ghErrors "github.com/github/github-mcp-server/v2/pkg/errors" + "github.com/github/github-mcp-server/v2/pkg/raw" + "github.com/github/github-mcp-server/v2/pkg/utils" + "github.com/google/go-github/v92/github" "github.com/modelcontextprotocol/go-sdk/mcp" ) @@ -34,9 +34,9 @@ func initializeRepository(ctx context.Context, client *github.Client, owner, rep defaultBranch := repository.GetDefaultBranch() fileOpts := &github.RepositoryContentFileOptions{ - Message: github.Ptr("Initial commit"), + Message: new("Initial commit"), Content: []byte(""), - Branch: github.Ptr(defaultBranch), + Branch: new(defaultBranch), } // Create an initial empty commit to create the default branch @@ -214,7 +214,8 @@ func inspectRepositoryFile(ctx context.Context, client *github.Client, owner, re } func repositoryContentBytes(file *github.RepositoryContent) ([]byte, bool, error) { - if file.Content == nil { + // Files over 1 MB come back with encoding "none" and no content. + if file.Content == nil || file.GetEncoding() == "none" { return []byte{}, file.GetType() != "symlink" && file.GetSize() == 0, nil } content, err := file.GetContent() diff --git a/pkg/github/repositories_test.go b/pkg/github/repositories_test.go index 8194895afa..9b40c932ff 100644 --- a/pkg/github/repositories_test.go +++ b/pkg/github/repositories_test.go @@ -10,14 +10,14 @@ import ( "testing" "time" - "github.com/github/github-mcp-server/internal/githubv4mock" - "github.com/github/github-mcp-server/internal/requeststate" - "github.com/github/github-mcp-server/internal/toolsnaps" - "github.com/github/github-mcp-server/pkg/inventory" - "github.com/github/github-mcp-server/pkg/raw" - "github.com/github/github-mcp-server/pkg/translations" - "github.com/github/github-mcp-server/pkg/utils" - "github.com/google/go-github/v89/github" + "github.com/github/github-mcp-server/v2/internal/githubv4mock" + "github.com/github/github-mcp-server/v2/internal/requeststate" + "github.com/github/github-mcp-server/v2/internal/toolsnaps" + "github.com/github/github-mcp-server/v2/pkg/inventory" + "github.com/github/github-mcp-server/v2/pkg/raw" + "github.com/github/github-mcp-server/v2/pkg/translations" + "github.com/github/github-mcp-server/v2/pkg/utils" + "github.com/google/go-github/v92/github" "github.com/google/jsonschema-go/jsonschema" "github.com/modelcontextprotocol/go-sdk/mcp" "github.com/shurcooL/githubv4" @@ -92,7 +92,6 @@ func Test_GetFileContents(t *testing.T) { // Verify tool definition once serverTool := GetFileContents(translations.NullTranslationHelper) tool := serverTool.Tool - require.NoError(t, toolsnaps.Test(tool.Name, tool)) schema, ok := tool.InputSchema.(*jsonschema.Schema) require.True(t, ok, "InputSchema should be *jsonschema.Schema") @@ -113,19 +112,19 @@ func Test_GetFileContents(t *testing.T) { // Setup mock directory content for success case mockDirContent := []*github.RepositoryContent{ { - Type: github.Ptr("file"), - Name: github.Ptr("README.md"), - Path: github.Ptr("README.md"), - SHA: github.Ptr(gitBlobSHA(mockRawContent)), - Size: github.Ptr(42), - HTMLURL: github.Ptr("https://github.com/owner/repo/blob/main/README.md"), + Type: new("file"), + Name: new("README.md"), + Path: new("README.md"), + SHA: new(gitBlobSHA(mockRawContent)), + Size: new(42), + HTMLURL: new("https://github.com/owner/repo/blob/main/README.md"), }, { - Type: github.Ptr("dir"), - Name: github.Ptr("src"), - Path: github.Ptr("src"), - SHA: github.Ptr("def456"), - HTMLURL: github.Ptr("https://github.com/owner/repo/tree/main/src"), + Type: new("dir"), + Name: new("src"), + Path: new("src"), + SHA: new("def456"), + HTMLURL: new("https://github.com/owner/repo/tree/main/src"), }, } @@ -147,12 +146,12 @@ func Test_GetFileContents(t *testing.T) { GetReposContentsByOwnerByRepoByPath: func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) fileContent := &github.RepositoryContent{ - Name: github.Ptr("README.md"), - Path: github.Ptr("README.md"), - SHA: github.Ptr(gitBlobSHA(mockRawContent)), - Type: github.Ptr("file"), - Content: github.Ptr(string(mockRawContent)), - Size: github.Ptr(len(mockRawContent)), + Name: new("README.md"), + Path: new("README.md"), + SHA: new(gitBlobSHA(mockRawContent)), + Type: new("file"), + Content: new(string(mockRawContent)), + Size: new(len(mockRawContent)), } contentBytes, _ := json.Marshal(fileContent) _, _ = w.Write(contentBytes) @@ -183,13 +182,13 @@ func Test_GetFileContents(t *testing.T) { pngContent := []byte("\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01") encodedContent := base64.StdEncoding.EncodeToString(pngContent) fileContent := &github.RepositoryContent{ - Name: github.Ptr("test.png"), - Path: github.Ptr("test.png"), - SHA: github.Ptr(gitBlobSHA(pngContent)), - Type: github.Ptr("file"), - Content: github.Ptr(encodedContent), - Size: github.Ptr(len(pngContent)), - Encoding: github.Ptr("base64"), + Name: new("test.png"), + Path: new("test.png"), + SHA: new(gitBlobSHA(pngContent)), + Type: new("file"), + Content: new(encodedContent), + Size: new(len(pngContent)), + Encoding: new("base64"), } contentBytes, _ := json.Marshal(fileContent) _, _ = w.Write(contentBytes) @@ -219,13 +218,13 @@ func Test_GetFileContents(t *testing.T) { pdfContent := []byte("%PDF-1.4 fake pdf content") encodedContent := base64.StdEncoding.EncodeToString(pdfContent) fileContent := &github.RepositoryContent{ - Name: github.Ptr("document.pdf"), - Path: github.Ptr("document.pdf"), - SHA: github.Ptr(gitBlobSHA(pdfContent)), - Type: github.Ptr("file"), - Content: github.Ptr(encodedContent), - Size: github.Ptr(len(pdfContent)), - Encoding: github.Ptr("base64"), + Name: new("document.pdf"), + Path: new("document.pdf"), + SHA: new(gitBlobSHA(pdfContent)), + Type: new("file"), + Content: new(encodedContent), + Size: new(len(pdfContent)), + Encoding: new("base64"), } contentBytes, _ := json.Marshal(fileContent) _, _ = w.Write(contentBytes) @@ -274,13 +273,13 @@ func Test_GetFileContents(t *testing.T) { // Base64 encode the content as GitHub API does encodedContent := base64.StdEncoding.EncodeToString(mockRawContent) fileContent := &github.RepositoryContent{ - Name: github.Ptr("README.md"), - Path: github.Ptr("README.md"), - SHA: github.Ptr(gitBlobSHA(mockRawContent)), - Type: github.Ptr("file"), - Content: github.Ptr(encodedContent), - Size: github.Ptr(len(mockRawContent)), - Encoding: github.Ptr("base64"), + Name: new("README.md"), + Path: new("README.md"), + SHA: new(gitBlobSHA(mockRawContent)), + Type: new("file"), + Content: new(encodedContent), + Size: new(len(mockRawContent)), + Encoding: new("base64"), } contentBytes, _ := json.Marshal(fileContent) _, _ = w.Write(contentBytes) @@ -358,13 +357,13 @@ func Test_GetFileContents(t *testing.T) { // Base64 encode the content as GitHub API does encodedContent := base64.StdEncoding.EncodeToString(mockRawContent) fileContent := &github.RepositoryContent{ - Name: github.Ptr("README.md"), - Path: github.Ptr("README.md"), - SHA: github.Ptr(gitBlobSHA(mockRawContent)), - Type: github.Ptr("file"), - Content: github.Ptr(encodedContent), - Size: github.Ptr(len(mockRawContent)), - Encoding: github.Ptr("base64"), + Name: new("README.md"), + Path: new("README.md"), + SHA: new(gitBlobSHA(mockRawContent)), + Type: new("file"), + Content: new(encodedContent), + Size: new(len(mockRawContent)), + Encoding: new("base64"), } contentBytes, _ := json.Marshal(fileContent) _, _ = w.Write(contentBytes) @@ -391,22 +390,22 @@ func Test_GetFileContents(t *testing.T) { GetReposByOwnerByRepo: mockResponse(t, http.StatusOK, "{\"name\": \"repo\", \"default_branch\": \"main\"}"), "GET /repos/owner/repo/git/trees/refs/heads/main": mockResponse(t, http.StatusOK, &github.Tree{ Entries: []*github.TreeEntry{{ - Path: github.Ptr("large-file.bin"), - Mode: github.Ptr("100644"), - Type: github.Ptr("blob"), - SHA: github.Ptr(strings.Repeat("a", 40)), + Path: new("large-file.bin"), + Mode: new("100644"), + Type: new("blob"), + SHA: new(strings.Repeat("a", 40)), }}, }), GetReposContentsByOwnerByRepoByPath: func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) // File larger than 1MB - Contents API returns metadata but no content fileContent := &github.RepositoryContent{ - Name: github.Ptr("large-file.bin"), - Path: github.Ptr("large-file.bin"), - SHA: github.Ptr(strings.Repeat("a", 40)), - Type: github.Ptr("file"), - Size: github.Ptr(2 * 1024 * 1024), // 2MB - DownloadURL: github.Ptr("https://raw.githubusercontent.com/owner/repo/main/large-file.bin"), + Name: new("large-file.bin"), + Path: new("large-file.bin"), + SHA: new(strings.Repeat("a", 40)), + Type: new("file"), + Size: new(2 * 1024 * 1024), // 2MB + DownloadURL: new("https://raw.githubusercontent.com/owner/repo/main/large-file.bin"), } contentBytes, _ := json.Marshal(fileContent) _, _ = w.Write(contentBytes) @@ -433,13 +432,13 @@ func Test_GetFileContents(t *testing.T) { GetReposContentsByOwnerByRepoByPath: func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) fileContent := &github.RepositoryContent{ - Name: github.Ptr(".gitkeep"), - Path: github.Ptr(".gitkeep"), - SHA: github.Ptr(gitBlobSHA(nil)), - Type: github.Ptr("file"), + Name: new(".gitkeep"), + Path: new(".gitkeep"), + SHA: new(gitBlobSHA(nil)), + Type: new("file"), Content: nil, - Size: github.Ptr(0), - Encoding: github.Ptr("base64"), + Size: new(0), + Encoding: new("base64"), } contentBytes, _ := json.Marshal(fileContent) _, _ = w.Write(contentBytes) @@ -583,6 +582,67 @@ func Test_GetFileContents(t *testing.T) { } } +func Test_GetFileContents_UsesUTF8ResourceURI(t *testing.T) { + content := []byte("package example") + sha := strings.Repeat("a", 40) + result, _ := runRepositoryReadFixture(t, repositoryReadFixture{ + contents: &github.RepositoryContent{ + Name: new("Þfoo.go"), + Path: new("test/Þfoo.go"), + SHA: new(gitBlobSHA(content)), + Type: new("file"), + Content: new(string(content)), + Size: new(len(content)), + }, + }, map[string]any{ + "owner": "owner", + "repo": "repo", + "path": "test/Þfoo.go", + "sha": sha, + }) + + resource := getResourceResult(t, result) + require.Equal(t, "repo://owner/repo/sha/"+sha+"/contents/test/%C3%9Efoo.go", resource.URI) +} + +func Test_GetFileContents_LargeFileUsesUTF8ResourceURI(t *testing.T) { + sha := strings.Repeat("a", 40) + result, _ := runRepositoryReadFixture(t, repositoryReadFixture{ + contents: &github.RepositoryContent{ + Name: new("Þlarge.bin"), + Path: new("test/Þlarge.bin"), + SHA: new(sha), + Type: new("file"), + Size: new(2 * 1024 * 1024), + DownloadURL: new("https://raw.example.com/owner/repo/" + sha + "/test/%C3%9Elarge.bin"), + }, + trees: map[string]*github.Tree{ + sha: {Entries: []*github.TreeEntry{{ + Path: new("test"), + Mode: new("040000"), + Type: new("tree"), + SHA: new("b"), + }}}, + "b": {Entries: []*github.TreeEntry{{ + Path: new("Þlarge.bin"), + Mode: new("100644"), + Type: new("blob"), + SHA: new(sha), + }}}, + }, + }, map[string]any{ + "owner": "owner", + "repo": "repo", + "path": "test/Þlarge.bin", + "sha": sha, + }) + + require.Len(t, result.Content, 2) + resource, ok := result.Content[1].(*mcp.ResourceLink) + require.True(t, ok) + require.Equal(t, "repo://owner/repo/sha/"+sha+"/contents/test/%C3%9Elarge.bin", resource.URI) +} + func Test_GetFileContents_SymlinkDisclosure(t *testing.T) { commitSHA := strings.Repeat("c", 40) args := func(path string) map[string]any { @@ -593,8 +653,8 @@ func Test_GetFileContents_SymlinkDisclosure(t *testing.T) { content := []byte("ordinary content") result, requests := runRepositoryReadFixture(t, repositoryReadFixture{ contents: &github.RepositoryContent{ - Type: github.Ptr("file"), Path: github.Ptr("README.md"), SHA: github.Ptr(gitBlobSHA(content)), - Content: github.Ptr(string(content)), Size: github.Ptr(len(content)), + Type: new("file"), Path: new("README.md"), SHA: new(gitBlobSHA(content)), + Content: new(string(content)), Size: new(len(content)), }, }, args("README.md")) require.False(t, result.IsError) @@ -615,9 +675,9 @@ func Test_GetFileContents_SymlinkDisclosure(t *testing.T) { linkSHA := gitBlobSHA([]byte(target)) result, requests := runRepositoryReadFixture(t, repositoryReadFixture{ contents: &github.RepositoryContent{ - Type: github.Ptr("file"), Path: github.Ptr("docs/link"), SHA: github.Ptr(linkSHA), - Content: github.Ptr(base64.StdEncoding.EncodeToString(tc.content)), - Encoding: github.Ptr("base64"), Size: github.Ptr(len(tc.content)), + Type: new("file"), Path: new("docs/link"), SHA: new(linkSHA), + Content: new(base64.StdEncoding.EncodeToString(tc.content)), + Encoding: new("base64"), Size: new(len(tc.content)), }, blobs: map[string][]byte{linkSHA: []byte(target)}, }, args("docs/link")) @@ -644,8 +704,8 @@ func Test_GetFileContents_SymlinkDisclosure(t *testing.T) { target := "../../outside" result, requests := runRepositoryReadFixture(t, repositoryReadFixture{ contents: &github.RepositoryContent{ - Type: github.Ptr("symlink"), Path: github.Ptr("docs/link"), - SHA: github.Ptr(gitBlobSHA([]byte(target))), Target: github.Ptr(target), + Type: new("symlink"), Path: new("docs/link"), + SHA: new(gitBlobSHA([]byte(target))), Target: new(target), }, }, args("docs/link")) require.False(t, result.IsError) @@ -662,9 +722,9 @@ func Test_GetFileContents_SymlinkDisclosure(t *testing.T) { target, content := "target.txt", []byte("resolved") result, requests := runRepositoryReadFixture(t, repositoryReadFixture{ contents: &github.RepositoryContent{ - Type: github.Ptr("symlink"), Path: github.Ptr("docs/link"), - SHA: github.Ptr(gitBlobSHA([]byte(target))), Target: github.Ptr(target), - Content: github.Ptr(string(content)), Size: github.Ptr(len(content)), + Type: new("symlink"), Path: new("docs/link"), + SHA: new(gitBlobSHA([]byte(target))), Target: new(target), + Content: new(string(content)), Size: new(len(content)), }, }, args("docs/link")) require.False(t, result.IsError) @@ -676,8 +736,8 @@ func Test_GetFileContents_SymlinkDisclosure(t *testing.T) { t.Run("submodule is explicit", func(t *testing.T) { result, requests := runRepositoryReadFixture(t, repositoryReadFixture{ contents: &github.RepositoryContent{ - Type: github.Ptr("submodule"), Path: github.Ptr("vendor/module"), - SHA: github.Ptr(strings.Repeat("d", 40)), SubmoduleGitURL: github.Ptr("https://example.com/module.git"), + Type: new("submodule"), Path: new("vendor/module"), + SHA: new(strings.Repeat("d", 40)), SubmoduleGitURL: new("https://example.com/module.git"), }, }, args("vendor/module")) require.False(t, result.IsError) @@ -691,8 +751,8 @@ func Test_GetFileContents_SymlinkDisclosure(t *testing.T) { content := []byte("resolved") result, requests := runRepositoryReadFixture(t, repositoryReadFixture{ contents: &github.RepositoryContent{ - Type: github.Ptr("file"), Path: github.Ptr("bad"), SHA: github.Ptr("bad-sha"), - Content: github.Ptr(string(content)), Size: github.Ptr(len(content)), + Type: new("file"), Path: new("bad"), SHA: new("bad-sha"), + Content: new(string(content)), Size: new(len(content)), }, }, args("bad")) assert.Equal(t, 1, requests) @@ -702,8 +762,8 @@ func Test_GetFileContents_SymlinkDisclosure(t *testing.T) { pathSHA := gitBlobSHA(pathBlob) result, requests = runRepositoryReadFixture(t, repositoryReadFixture{ contents: &github.RepositoryContent{ - Type: github.Ptr("file"), Path: github.Ptr("bad"), SHA: github.Ptr(pathSHA), - Content: github.Ptr(string(content)), Size: github.Ptr(len(content)), + Type: new("file"), Path: new("bad"), SHA: new(pathSHA), + Content: new(string(content)), Size: new(len(content)), }, blobs: map[string][]byte{pathSHA: pathBlob}, }, args("bad")) @@ -723,10 +783,26 @@ func Test_GetFileContents_ContentlessRequestCounts(t *testing.T) { t.Run("normal large file", func(t *testing.T) { result, requests := runRepositoryReadFixture(t, repositoryReadFixture{ contents: &github.RepositoryContent{ - Type: github.Ptr("file"), Path: github.Ptr("large.bin"), SHA: github.Ptr(fileSHA), Size: github.Ptr(largeSize), + Type: new("file"), Path: new("large.bin"), SHA: new(fileSHA), Size: new(largeSize), + }, + trees: map[string]*github.Tree{commitSHA: {Entries: []*github.TreeEntry{ + {Path: new("large.bin"), Mode: new("100644"), Type: new("blob"), SHA: new(fileSHA)}, + }}}, + }, args("large.bin")) + require.False(t, result.IsError) + assert.Equal(t, 2, requests) + _, ok := result.Content[1].(*mcp.ResourceLink) + require.True(t, ok) + }) + + t.Run("large file with encoding none", func(t *testing.T) { + result, requests := runRepositoryReadFixture(t, repositoryReadFixture{ + contents: &github.RepositoryContent{ + Type: new("file"), Path: new("large.bin"), SHA: new(fileSHA), Size: new(largeSize), + Content: new(""), Encoding: new("none"), }, trees: map[string]*github.Tree{commitSHA: {Entries: []*github.TreeEntry{ - {Path: github.Ptr("large.bin"), Mode: github.Ptr("100644"), Type: github.Ptr("blob"), SHA: github.Ptr(fileSHA)}, + {Path: new("large.bin"), Mode: new("100644"), Type: new("blob"), SHA: new(fileSHA)}, }}}, }, args("large.bin")) require.False(t, result.IsError) @@ -740,15 +816,15 @@ func Test_GetFileContents_ContentlessRequestCounts(t *testing.T) { linkSHA := gitBlobSHA([]byte(target)) result, requests := runRepositoryReadFixture(t, repositoryReadFixture{ contents: &github.RepositoryContent{ - Type: github.Ptr("file"), Path: github.Ptr("docs/link"), SHA: github.Ptr(linkSHA), Size: github.Ptr(largeSize), + Type: new("file"), Path: new("docs/link"), SHA: new(linkSHA), Size: new(largeSize), }, blobs: map[string][]byte{linkSHA: []byte(target)}, trees: map[string]*github.Tree{ commitSHA: {Entries: []*github.TreeEntry{ - {Path: github.Ptr("docs"), Mode: github.Ptr("040000"), Type: github.Ptr("tree"), SHA: github.Ptr("docs-tree")}, + {Path: new("docs"), Mode: new("040000"), Type: new("tree"), SHA: new("docs-tree")}, }}, "docs-tree": {Entries: []*github.TreeEntry{ - {Path: github.Ptr("link"), Mode: github.Ptr(gitSymlinkMode), Type: github.Ptr("blob"), SHA: github.Ptr(linkSHA)}, + {Path: new("link"), Mode: new(gitSymlinkMode), Type: new("blob"), SHA: new(linkSHA)}, }}, }, inspect: func(r *http.Request) { @@ -767,9 +843,9 @@ func Test_GetFileContents_ContentlessRequestCounts(t *testing.T) { t.Run("truncated tree fails closed", func(t *testing.T) { result, requests := runRepositoryReadFixture(t, repositoryReadFixture{ contents: &github.RepositoryContent{ - Type: github.Ptr("file"), Path: github.Ptr("large.bin"), SHA: github.Ptr(fileSHA), Size: github.Ptr(largeSize), + Type: new("file"), Path: new("large.bin"), SHA: new(fileSHA), Size: new(largeSize), }, - trees: map[string]*github.Tree{commitSHA: {Truncated: github.Ptr(true)}}, + trees: map[string]*github.Tree{commitSHA: {Truncated: new(true)}}, }, args("large.bin")) assert.Equal(t, 2, requests) assert.Contains(t, getErrorResult(t, result).Text, "truncated") @@ -778,7 +854,7 @@ func Test_GetFileContents_ContentlessRequestCounts(t *testing.T) { t.Run("directory remains one request", func(t *testing.T) { result, requests := runRepositoryReadFixture(t, repositoryReadFixture{ contents: []*github.RepositoryContent{{ - Type: github.Ptr("file"), Path: github.Ptr("docs/readme"), SHA: github.Ptr(fileSHA), + Type: new("file"), Path: new("docs/readme"), SHA: new(fileSHA), }}, }, args("docs")) require.False(t, result.IsError) @@ -789,21 +865,21 @@ func Test_GetFileContents_ContentlessRequestCounts(t *testing.T) { func Test_GetFileContents_DirectoryFieldFiltering(t *testing.T) { mockDirContent := []*github.RepositoryContent{ { - Type: github.Ptr("file"), - Name: github.Ptr("README.md"), - Path: github.Ptr("README.md"), - SHA: github.Ptr("abc123"), - Size: github.Ptr(42), - URL: github.Ptr("https://api.github.com/repos/owner/repo/contents/README.md"), - HTMLURL: github.Ptr("https://github.com/owner/repo/blob/main/README.md"), - DownloadURL: github.Ptr("https://raw.githubusercontent.com/owner/repo/main/README.md"), + Type: new("file"), + Name: new("README.md"), + Path: new("README.md"), + SHA: new("abc123"), + Size: new(42), + URL: new("https://api.github.com/repos/owner/repo/contents/README.md"), + HTMLURL: new("https://github.com/owner/repo/blob/main/README.md"), + DownloadURL: new("https://raw.githubusercontent.com/owner/repo/main/README.md"), }, { - Type: github.Ptr("dir"), - Name: github.Ptr("src"), - Path: github.Ptr("src"), - SHA: github.Ptr("def456"), - HTMLURL: github.Ptr("https://github.com/owner/repo/tree/main/src"), + Type: new("dir"), + Name: new("src"), + Path: new("src"), + SHA: new("def456"), + HTMLURL: new("https://github.com/owner/repo/tree/main/src"), }, } @@ -852,14 +928,14 @@ func Test_GetFileContents_DirectoryFieldFiltering(t *testing.T) { func Test_GetFileContents_DirectoryFieldsTelemetry(t *testing.T) { mockDirContent := []*github.RepositoryContent{ { - Type: github.Ptr("file"), - Name: github.Ptr("README.md"), - Path: github.Ptr("README.md"), - SHA: github.Ptr("abc123"), - Size: github.Ptr(42), - URL: github.Ptr("https://api.github.com/repos/owner/repo/contents/README.md"), - HTMLURL: github.Ptr("https://github.com/owner/repo/blob/main/README.md"), - DownloadURL: github.Ptr("https://raw.githubusercontent.com/owner/repo/main/README.md"), + Type: new("file"), + Name: new("README.md"), + Path: new("README.md"), + SHA: new("abc123"), + Size: new(42), + URL: new("https://api.github.com/repos/owner/repo/contents/README.md"), + HTMLURL: new("https://github.com/owner/repo/blob/main/README.md"), + DownloadURL: new("https://raw.githubusercontent.com/owner/repo/main/README.md"), }, } @@ -919,13 +995,13 @@ func Test_GetFileContents_IFC_InsidersMode(t *testing.T) { w.WriteHeader(http.StatusOK) encodedContent := base64.StdEncoding.EncodeToString(mockRawContent) fileContent := &github.RepositoryContent{ - Name: github.Ptr("README.md"), - Path: github.Ptr("README.md"), - SHA: github.Ptr(gitBlobSHA(mockRawContent)), - Type: github.Ptr("file"), - Content: github.Ptr(encodedContent), - Size: github.Ptr(len(mockRawContent)), - Encoding: github.Ptr("base64"), + Name: new("README.md"), + Path: new("README.md"), + SHA: new(gitBlobSHA(mockRawContent)), + Type: new("file"), + Content: new(encodedContent), + Size: new(len(mockRawContent)), + Encoding: new("base64"), } contentBytes, _ := json.Marshal(fileContent) _, _ = w.Write(contentBytes) @@ -1012,13 +1088,13 @@ func Test_GetFileContents_IFC_InsidersMode(t *testing.T) { w.WriteHeader(http.StatusOK) encodedContent := base64.StdEncoding.EncodeToString(mockRawContent) fileContent := &github.RepositoryContent{ - Name: github.Ptr("README.md"), - Path: github.Ptr("README.md"), - SHA: github.Ptr(gitBlobSHA(mockRawContent)), - Type: github.Ptr("file"), - Content: github.Ptr(encodedContent), - Size: github.Ptr(len(mockRawContent)), - Encoding: github.Ptr("base64"), + Name: new("README.md"), + Path: new("README.md"), + SHA: new(gitBlobSHA(mockRawContent)), + Type: new("file"), + Content: new(encodedContent), + Size: new(len(mockRawContent)), + Encoding: new("base64"), } contentBytes, _ := json.Marshal(fileContent) _, _ = w.Write(contentBytes) @@ -1048,8 +1124,8 @@ func Test_GetFileContents_IFC_InsidersMode(t *testing.T) { GetReposGitRefByOwnerByRepoByRef: mockResponse(t, http.StatusOK, "{\"ref\": \"refs/heads/main\", \"object\": {\"sha\": \"\"}}"), GetReposByOwnerByRepo: mockResponse(t, http.StatusOK, map[string]any{"private": false}), GetReposContentsByOwnerByRepoByPath: mockResponse(t, http.StatusOK, &github.RepositoryContent{ - Type: github.Ptr("file"), Path: github.Ptr("link"), SHA: github.Ptr(linkSHA), - Content: github.Ptr(string(content)), Size: github.Ptr(len(content)), + Type: new("file"), Path: new("link"), SHA: new(linkSHA), + Content: new(string(content)), Size: new(len(content)), }), GetReposGitBlobsByOwnerByRepoByFileSHA: func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write(target) @@ -1081,9 +1157,9 @@ func Test_GetCommit_IFC_FeatureFlag(t *testing.T) { serverTool := GetCommit(translations.NullTranslationHelper) mockCommit := &github.RepositoryCommit{ - SHA: github.Ptr("abc123def456"), - Commit: &github.Commit{Message: github.Ptr("First commit")}, - HTMLURL: github.Ptr("https://github.com/owner/repo/commit/abc123def456"), + SHA: new("abc123def456"), + Commit: &github.Commit{Message: new("First commit")}, + HTMLURL: new("https://github.com/owner/repo/commit/abc123def456"), } makeMockClient := func(isPrivate bool) *http.Client { @@ -1193,7 +1269,6 @@ func Test_ForkRepository(t *testing.T) { // Verify tool definition once serverTool := ForkRepository(translations.NullTranslationHelper) tool := serverTool.Tool - require.NoError(t, toolsnaps.Test(tool.Name, tool)) schema, ok := tool.InputSchema.(*jsonschema.Schema) require.True(t, ok, "InputSchema should be *jsonschema.Schema") @@ -1207,16 +1282,16 @@ func Test_ForkRepository(t *testing.T) { // Setup mock forked repo for success case mockForkedRepo := &github.Repository{ - ID: github.Ptr(int64(123456)), - Name: github.Ptr("repo"), - FullName: github.Ptr("new-owner/repo"), + ID: new(int64(123456)), + Name: new("repo"), + FullName: new("new-owner/repo"), Owner: &github.User{ - Login: github.Ptr("new-owner"), + Login: new("new-owner"), }, - HTMLURL: github.Ptr("https://github.com/new-owner/repo"), - DefaultBranch: github.Ptr("main"), - Fork: github.Ptr(true), - ForksCount: github.Ptr(0), + HTMLURL: new("https://github.com/new-owner/repo"), + DefaultBranch: new("main"), + Fork: new(true), + ForksCount: new(0), } tests := []struct { @@ -1295,7 +1370,6 @@ func Test_CreateBranch(t *testing.T) { // Verify tool definition once serverTool := CreateBranch(translations.NullTranslationHelper) tool := serverTool.Tool - require.NoError(t, toolsnaps.Test(tool.Name, tool)) schema, ok := tool.InputSchema.(*jsonschema.Schema) require.True(t, ok, "InputSchema should be *jsonschema.Schema") @@ -1310,22 +1384,22 @@ func Test_CreateBranch(t *testing.T) { // Setup mock repository for default branch test mockRepo := &github.Repository{ - DefaultBranch: github.Ptr("main"), + DefaultBranch: new("main"), } // Setup mock reference for from_branch tests mockSourceRef := &github.Reference{ - Ref: github.Ptr("refs/heads/main"), + Ref: new("refs/heads/main"), Object: &github.GitObject{ - SHA: github.Ptr("abc123def456"), + SHA: new("abc123def456"), }, } // Setup mock created reference mockCreatedRef := &github.Reference{ - Ref: github.Ptr("refs/heads/new-feature"), + Ref: new("refs/heads/new-feature"), Object: &github.GitObject{ - SHA: github.Ptr("abc123def456"), + SHA: new("abc123def456"), }, } @@ -1508,7 +1582,6 @@ func Test_GetCommit(t *testing.T) { // Verify tool definition once serverTool := GetCommit(translations.NullTranslationHelper) tool := serverTool.Tool - require.NoError(t, toolsnaps.Test(tool.Name, tool)) schema, ok := tool.InputSchema.(*jsonschema.Schema) require.True(t, ok, "InputSchema should be *jsonschema.Schema") @@ -1521,32 +1594,32 @@ func Test_GetCommit(t *testing.T) { assert.ElementsMatch(t, schema.Required, []string{"owner", "repo", "sha"}) mockCommit := &github.RepositoryCommit{ - SHA: github.Ptr("abc123def456"), + SHA: new("abc123def456"), Commit: &github.Commit{ - Message: github.Ptr("First commit"), + Message: new("First commit"), Author: &github.CommitAuthor{ - Name: github.Ptr("Test User"), - Email: github.Ptr("test@example.com"), + Name: new("Test User"), + Email: new("test@example.com"), Date: &github.Timestamp{Time: time.Now().Add(-48 * time.Hour)}, }, }, Author: &github.User{ - Login: github.Ptr("testuser"), + Login: new("testuser"), }, - HTMLURL: github.Ptr("https://github.com/owner/repo/commit/abc123def456"), + HTMLURL: new("https://github.com/owner/repo/commit/abc123def456"), Stats: &github.CommitStats{ - Additions: github.Ptr(10), - Deletions: github.Ptr(2), - Total: github.Ptr(12), + Additions: new(10), + Deletions: new(2), + Total: new(12), }, Files: []*github.CommitFile{ { - Filename: github.Ptr("file1.go"), - Status: github.Ptr("modified"), - Additions: github.Ptr(10), - Deletions: github.Ptr(2), - Changes: github.Ptr(12), - Patch: github.Ptr("@@ -1,2 +1,10 @@"), + Filename: new("file1.go"), + Status: new("modified"), + Additions: new(10), + Deletions: new(2), + Changes: new(12), + Patch: new("@@ -1,2 +1,10 @@"), }, }, } @@ -1635,24 +1708,24 @@ func Test_GetCommit(t *testing.T) { func Test_GetCommit_Detail(t *testing.T) { mockCommit := &github.RepositoryCommit{ - SHA: github.Ptr("abc123def456"), - HTMLURL: github.Ptr("https://github.com/owner/repo/commit/abc123def456"), + SHA: new("abc123def456"), + HTMLURL: new("https://github.com/owner/repo/commit/abc123def456"), Commit: &github.Commit{ - Message: github.Ptr("First commit"), + Message: new("First commit"), }, Stats: &github.CommitStats{ - Additions: github.Ptr(10), - Deletions: github.Ptr(2), - Total: github.Ptr(12), + Additions: new(10), + Deletions: new(2), + Total: new(12), }, Files: []*github.CommitFile{ { - Filename: github.Ptr("file1.go"), - Status: github.Ptr("modified"), - Additions: github.Ptr(10), - Deletions: github.Ptr(2), - Changes: github.Ptr(12), - Patch: github.Ptr("@@ -1,2 +1,10 @@\n+new line"), + Filename: new("file1.go"), + Status: new("modified"), + Additions: new(10), + Deletions: new(2), + Changes: new(12), + Patch: new("@@ -1,2 +1,10 @@\n+new line"), }, }, } @@ -1751,7 +1824,6 @@ func Test_ListCommits(t *testing.T) { // Verify tool definition once serverTool := ListCommits(translations.NullTranslationHelper) tool := serverTool.Tool - require.NoError(t, toolsnaps.Test(tool.Name, tool)) schema, ok := tool.InputSchema.(*jsonschema.Schema) require.True(t, ok, "InputSchema should be *jsonschema.Schema") @@ -1773,73 +1845,73 @@ func Test_ListCommits(t *testing.T) { // Setup mock commits for success case mockCommits := []*github.RepositoryCommit{ { - SHA: github.Ptr("abc123def456"), + SHA: new("abc123def456"), Commit: &github.Commit{ - Message: github.Ptr("First commit"), + Message: new("First commit"), Author: &github.CommitAuthor{ - Name: github.Ptr("Test User"), - Email: github.Ptr("test@example.com"), + Name: new("Test User"), + Email: new("test@example.com"), Date: &github.Timestamp{Time: time.Now().Add(-48 * time.Hour)}, }, }, Author: &github.User{ - Login: github.Ptr("testuser"), - ID: github.Ptr(int64(12345)), - HTMLURL: github.Ptr("https://github.com/testuser"), - AvatarURL: github.Ptr("https://github.com/testuser.png"), + Login: new("testuser"), + ID: new(int64(12345)), + HTMLURL: new("https://github.com/testuser"), + AvatarURL: new("https://github.com/testuser.png"), }, - HTMLURL: github.Ptr("https://github.com/owner/repo/commit/abc123def456"), + HTMLURL: new("https://github.com/owner/repo/commit/abc123def456"), Stats: &github.CommitStats{ - Additions: github.Ptr(10), - Deletions: github.Ptr(5), - Total: github.Ptr(15), + Additions: new(10), + Deletions: new(5), + Total: new(15), }, Files: []*github.CommitFile{ { - Filename: github.Ptr("src/main.go"), - Status: github.Ptr("modified"), - Additions: github.Ptr(8), - Deletions: github.Ptr(3), - Changes: github.Ptr(11), + Filename: new("src/main.go"), + Status: new("modified"), + Additions: new(8), + Deletions: new(3), + Changes: new(11), }, { - Filename: github.Ptr("README.md"), - Status: github.Ptr("added"), - Additions: github.Ptr(2), - Deletions: github.Ptr(2), - Changes: github.Ptr(4), + Filename: new("README.md"), + Status: new("added"), + Additions: new(2), + Deletions: new(2), + Changes: new(4), }, }, }, { - SHA: github.Ptr("def456abc789"), + SHA: new("def456abc789"), Commit: &github.Commit{ - Message: github.Ptr("Second commit"), + Message: new("Second commit"), Author: &github.CommitAuthor{ - Name: github.Ptr("Another User"), - Email: github.Ptr("another@example.com"), + Name: new("Another User"), + Email: new("another@example.com"), Date: &github.Timestamp{Time: time.Now().Add(-24 * time.Hour)}, }, }, Author: &github.User{ - Login: github.Ptr("anotheruser"), - ID: github.Ptr(int64(67890)), - HTMLURL: github.Ptr("https://github.com/anotheruser"), - AvatarURL: github.Ptr("https://github.com/anotheruser.png"), + Login: new("anotheruser"), + ID: new(int64(67890)), + HTMLURL: new("https://github.com/anotheruser"), + AvatarURL: new("https://github.com/anotheruser.png"), }, - HTMLURL: github.Ptr("https://github.com/owner/repo/commit/def456abc789"), + HTMLURL: new("https://github.com/owner/repo/commit/def456abc789"), Stats: &github.CommitStats{ - Additions: github.Ptr(20), - Deletions: github.Ptr(10), - Total: github.Ptr(30), + Additions: new(20), + Deletions: new(10), + Total: new(30), }, Files: []*github.CommitFile{ { - Filename: github.Ptr("src/utils.go"), - Status: github.Ptr("added"), - Additions: github.Ptr(20), - Deletions: github.Ptr(10), - Changes: github.Ptr(30), + Filename: new("src/utils.go"), + Status: new("added"), + Additions: new(20), + Deletions: new(10), + Changes: new(30), }, }, }, @@ -2053,7 +2125,6 @@ func Test_CreateOrUpdateFile(t *testing.T) { // Verify tool definition once serverTool := CreateOrUpdateFile(translations.NullTranslationHelper) tool := serverTool.Tool - require.NoError(t, toolsnaps.Test(tool.Name, tool)) schema, ok := tool.InputSchema.(*jsonschema.Schema) require.True(t, ok, "InputSchema should be *jsonschema.Schema") @@ -2077,23 +2148,21 @@ func Test_CreateOrUpdateFile(t *testing.T) { // Setup mock file content response mockFileResponse := &github.RepositoryContentResponse{ Content: &github.RepositoryContent{ - Name: github.Ptr("example.md"), - Path: github.Ptr("docs/example.md"), - SHA: github.Ptr("abc123def456"), - Size: github.Ptr(42), - HTMLURL: github.Ptr("https://github.com/owner/repo/blob/main/docs/example.md"), - DownloadURL: github.Ptr("https://raw.githubusercontent.com/owner/repo/main/docs/example.md"), - }, - Commit: github.Commit{ - SHA: github.Ptr("def456abc789"), - Message: github.Ptr("Add example file"), - Author: &github.CommitAuthor{ - Name: github.Ptr("Test User"), - Email: github.Ptr("test@example.com"), - Date: &github.Timestamp{Time: time.Now()}, - }, - HTMLURL: github.Ptr("https://github.com/owner/repo/commit/def456abc789"), - }, + Name: new("example.md"), + Path: new("docs/example.md"), + SHA: new("abc123def456"), + Size: new(42), + HTMLURL: new("https://github.com/owner/repo/blob/main/docs/example.md"), + DownloadURL: new("https://raw.githubusercontent.com/owner/repo/main/docs/example.md"), + }, + SHA: new("def456abc789"), + Message: new("Add example file"), + Author: &github.CommitAuthor{ + Name: new("Test User"), + Email: new("test@example.com"), + Date: &github.Timestamp{Time: time.Now()}, + }, + HTMLURL: new("https://github.com/owner/repo/commit/def456abc789"), } symlinkTarget := []byte("other.md") symlinkSHA := gitBlobSHA(symlinkTarget) @@ -2105,10 +2174,10 @@ func Test_CreateOrUpdateFile(t *testing.T) { tree = &github.Tree{ Entries: []*github.TreeEntry{ { - Path: github.Ptr("docs"), - Mode: github.Ptr("040000"), - Type: github.Ptr("tree"), - SHA: github.Ptr("docs-tree"), + Path: new("docs"), + Mode: new("040000"), + Type: new("tree"), + SHA: new("docs-tree"), }, }, } @@ -2120,10 +2189,10 @@ func Test_CreateOrUpdateFile(t *testing.T) { tree = &github.Tree{ Entries: []*github.TreeEntry{ { - Path: github.Ptr("example.md"), - Mode: github.Ptr(mode), - Type: github.Ptr("blob"), - SHA: github.Ptr(entrySHA), + Path: new("example.md"), + Mode: new(mode), + Type: new("blob"), + SHA: new(entrySHA), }, }, } @@ -2180,12 +2249,12 @@ func Test_CreateOrUpdateFile(t *testing.T) { mockedClient: MockHTTPClientWithHandlers(map[string]http.HandlerFunc{ GetReposGitTreesByOwnerByRepoByTree: mockPathTree("100644"), "GET /repos/owner/repo/contents/docs/example.md": mockResponse(t, http.StatusOK, &github.RepositoryContent{ - SHA: github.Ptr("abc123def456"), - Type: github.Ptr("file"), + SHA: new("abc123def456"), + Type: new("file"), }), "GET /repos/{owner}/{repo}/contents/{path:.*}": mockResponse(t, http.StatusOK, &github.RepositoryContent{ - SHA: github.Ptr("abc123def456"), - Type: github.Ptr("file"), + SHA: new("abc123def456"), + Type: new("file"), }), PutReposContentsByOwnerByRepoByPath: expectRequestBody(t, map[string]any{ "message": "Update example file", @@ -2246,12 +2315,12 @@ func Test_CreateOrUpdateFile(t *testing.T) { mockedClient: MockHTTPClientWithHandlers(map[string]http.HandlerFunc{ GetReposGitTreesByOwnerByRepoByTree: mockPathTree("100644"), "GET /repos/owner/repo/contents/docs/example.md": mockResponse(t, http.StatusOK, &github.RepositoryContent{ - SHA: github.Ptr("abc123def456"), - Type: github.Ptr("file"), + SHA: new("abc123def456"), + Type: new("file"), }), "GET /repos/{owner}/{repo}/contents/{path:.*}": mockResponse(t, http.StatusOK, &github.RepositoryContent{ - SHA: github.Ptr("abc123def456"), - Type: github.Ptr("file"), + SHA: new("abc123def456"), + Type: new("file"), }), PutReposContentsByOwnerByRepoByPath: expectRequestBody(t, map[string]any{ "message": "Update example file", @@ -2291,12 +2360,12 @@ func Test_CreateOrUpdateFile(t *testing.T) { _, _ = w.Write(symlinkTarget) }, "GET /repos/owner/repo/contents/docs/example.md": mockResponse(t, http.StatusOK, &github.RepositoryContent{ - SHA: github.Ptr("abc123def456"), - Type: github.Ptr("file"), + SHA: new("abc123def456"), + Type: new("file"), }), "GET /repos/{owner}/{repo}/contents/{path:.*}": mockResponse(t, http.StatusOK, &github.RepositoryContent{ - SHA: github.Ptr("abc123def456"), - Type: github.Ptr("file"), + SHA: new("abc123def456"), + Type: new("file"), }), }), requestArgs: map[string]any{ @@ -2331,12 +2400,12 @@ func Test_CreateOrUpdateFile(t *testing.T) { _, _ = w.Write(symlinkTarget) }, "GET /repos/owner/repo/contents/docs/example.md": mockResponse(t, http.StatusOK, &github.RepositoryContent{ - SHA: github.Ptr("abc123def456"), - Type: github.Ptr("file"), + SHA: new("abc123def456"), + Type: new("file"), }), "GET /repos/{owner}/{repo}/contents/{path:.*}": mockResponse(t, http.StatusOK, &github.RepositoryContent{ - SHA: github.Ptr("abc123def456"), - Type: github.Ptr("file"), + SHA: new("abc123def456"), + Type: new("file"), }), }), requestArgs: map[string]any{ @@ -2356,12 +2425,12 @@ func Test_CreateOrUpdateFile(t *testing.T) { name: "allows intentional symbolic link update with explicit opt-in", mockedClient: MockHTTPClientWithHandlers(map[string]http.HandlerFunc{ "GET /repos/owner/repo/contents/docs/example.md": mockResponse(t, http.StatusOK, &github.RepositoryContent{ - SHA: github.Ptr("abc123def456"), - Type: github.Ptr("file"), + SHA: new("abc123def456"), + Type: new("file"), }), "GET /repos/{owner}/{repo}/contents/{path:.*}": mockResponse(t, http.StatusOK, &github.RepositoryContent{ - SHA: github.Ptr("abc123def456"), - Type: github.Ptr("file"), + SHA: new("abc123def456"), + Type: new("file"), }), PutReposContentsByOwnerByRepoByPath: expectRequestBody(t, map[string]any{ "message": "Change link target", @@ -2398,14 +2467,14 @@ func Test_CreateOrUpdateFile(t *testing.T) { name: "rejects explicit symbolic link response without tree inspection", mockedClient: MockHTTPClientWithHandlers(map[string]http.HandlerFunc{ "GET /repos/owner/repo/contents/docs/example.md": mockResponse(t, http.StatusOK, &github.RepositoryContent{ - SHA: github.Ptr("abc123def456"), - Type: github.Ptr("symlink"), - Target: github.Ptr("../../outside"), + SHA: new("abc123def456"), + Type: new("symlink"), + Target: new("../../outside"), }), "GET /repos/{owner}/{repo}/contents/{path:.*}": mockResponse(t, http.StatusOK, &github.RepositoryContent{ - SHA: github.Ptr("abc123def456"), - Type: github.Ptr("symlink"), - Target: github.Ptr("../../outside"), + SHA: new("abc123def456"), + Type: new("symlink"), + Target: new("../../outside"), }), }), requestArgs: map[string]any{ @@ -2430,15 +2499,15 @@ func Test_CreateOrUpdateFile(t *testing.T) { name: "fails closed when git tree is truncated", mockedClient: MockHTTPClientWithHandlers(map[string]http.HandlerFunc{ GetReposGitTreesByOwnerByRepoByTree: mockResponse(t, http.StatusOK, &github.Tree{ - Truncated: github.Ptr(true), + Truncated: new(true), }), "GET /repos/owner/repo/contents/docs/example.md": mockResponse(t, http.StatusOK, &github.RepositoryContent{ - SHA: github.Ptr("abc123def456"), - Type: github.Ptr("file"), + SHA: new("abc123def456"), + Type: new("file"), }), "GET /repos/{owner}/{repo}/contents/{path:.*}": mockResponse(t, http.StatusOK, &github.RepositoryContent{ - SHA: github.Ptr("abc123def456"), - Type: github.Ptr("file"), + SHA: new("abc123def456"), + Type: new("file"), }), }), requestArgs: map[string]any{ @@ -2460,16 +2529,16 @@ func Test_CreateOrUpdateFile(t *testing.T) { "GET /repos/owner/repo/contents/docs/example.md": expectQueryParams(t, map[string]string{ "ref": "main", }).andThen(mockResponse(t, http.StatusOK, &github.RepositoryContent{ - SHA: github.Ptr(symlinkSHA), - Type: github.Ptr("symlink"), - Target: github.Ptr(string(symlinkTarget)), + SHA: new(symlinkSHA), + Type: new("symlink"), + Target: new(string(symlinkTarget)), })), "GET /repos/{owner}/{repo}/contents/{path:.*}": expectQueryParams(t, map[string]string{ "ref": "main", }).andThen(mockResponse(t, http.StatusOK, &github.RepositoryContent{ - SHA: github.Ptr(symlinkSHA), - Type: github.Ptr("symlink"), - Target: github.Ptr(string(symlinkTarget)), + SHA: new(symlinkSHA), + Type: new("symlink"), + Target: new(string(symlinkTarget)), })), }), requestArgs: map[string]any{ @@ -2558,14 +2627,14 @@ func Test_CreateOrUpdateFile(t *testing.T) { "GET /repos/owner/repo/contents/docs/example.md": expectQueryParams(t, map[string]string{ "ref": "release/#candidate", }).andThen(mockResponse(t, http.StatusOK, &github.RepositoryContent{ - SHA: github.Ptr("existing123"), - Type: github.Ptr("file"), + SHA: new("existing123"), + Type: new("file"), })), "GET /repos/{owner}/{repo}/contents/{path:.*}": expectQueryParams(t, map[string]string{ "ref": "release/#candidate", }).andThen(mockResponse(t, http.StatusOK, &github.RepositoryContent{ - SHA: github.Ptr("existing123"), - Type: github.Ptr("file"), + SHA: new("existing123"), + Type: new("file"), })), }), requestArgs: map[string]any{ @@ -2733,7 +2802,6 @@ func Test_CreateRepository(t *testing.T) { // Verify tool definition once serverTool := CreateRepository(translations.NullTranslationHelper) tool := serverTool.Tool - require.NoError(t, toolsnaps.Test(tool.Name, tool)) schema, ok := tool.InputSchema.(*jsonschema.Schema) require.True(t, ok, "InputSchema should be *jsonschema.Schema") @@ -2749,13 +2817,13 @@ func Test_CreateRepository(t *testing.T) { // Setup mock repository response mockRepo := &github.Repository{ - Name: github.Ptr("test-repo"), - Description: github.Ptr("Test repository"), - Private: github.Ptr(true), - HTMLURL: github.Ptr("https://github.com/testuser/test-repo"), + Name: new("test-repo"), + Description: new("Test repository"), + Private: new(true), + HTMLURL: new("https://github.com/testuser/test-repo"), CreatedAt: &github.Timestamp{Time: time.Now()}, Owner: &github.User{ - Login: github.Ptr("testuser"), + Login: new("testuser"), }, } @@ -2923,7 +2991,6 @@ func Test_PushFiles(t *testing.T) { // Verify tool definition once serverTool := PushFiles(translations.NullTranslationHelper) tool := serverTool.Tool - require.NoError(t, toolsnaps.Test(tool.Name, tool)) schema, ok := tool.InputSchema.(*jsonschema.Schema) require.True(t, ok, "InputSchema should be *jsonschema.Schema") @@ -2939,35 +3006,35 @@ func Test_PushFiles(t *testing.T) { // Setup mock objects mockRef := &github.Reference{ - Ref: github.Ptr("refs/heads/main"), + Ref: new("refs/heads/main"), Object: &github.GitObject{ - SHA: github.Ptr("abc123"), - URL: github.Ptr("https://api.github.com/repos/owner/repo/git/trees/abc123"), + SHA: new("abc123"), + URL: new("https://api.github.com/repos/owner/repo/git/trees/abc123"), }, } mockCommit := &github.Commit{ - SHA: github.Ptr("abc123"), + SHA: new("abc123"), Tree: &github.Tree{ - SHA: github.Ptr("def456"), + SHA: new("def456"), }, } mockTree := &github.Tree{ - SHA: github.Ptr("ghi789"), + SHA: new("ghi789"), } mockNewCommit := &github.Commit{ - SHA: github.Ptr("jkl012"), - Message: github.Ptr("Update multiple files"), - HTMLURL: github.Ptr("https://github.com/owner/repo/commit/jkl012"), + SHA: new("jkl012"), + Message: new("Update multiple files"), + HTMLURL: new("https://github.com/owner/repo/commit/jkl012"), } mockUpdatedRef := &github.Reference{ - Ref: github.Ptr("refs/heads/main"), + Ref: new("refs/heads/main"), Object: &github.GitObject{ - SHA: github.Ptr("jkl012"), - URL: github.Ptr("https://api.github.com/repos/owner/repo/git/trees/jkl012"), + SHA: new("jkl012"), + URL: new("https://api.github.com/repos/owner/repo/git/trees/jkl012"), }, } @@ -3250,7 +3317,7 @@ func Test_PushFiles(t *testing.T) { WithRequestMatch( GetReposByOwnerByRepo, &github.Repository{ - DefaultBranch: github.Ptr("main"), + DefaultBranch: new("main"), }, ), // Create initial file using Contents API @@ -3264,7 +3331,7 @@ func Test_PushFiles(t *testing.T) { require.Equal(t, "main", body["branch"]) w.WriteHeader(http.StatusCreated) response := &github.RepositoryContentResponse{ - Commit: github.Commit{SHA: github.Ptr("abc123")}, + SHA: new("abc123"), } b, _ := json.Marshal(response) _, _ = w.Write(b) @@ -3328,8 +3395,8 @@ func Test_PushFiles(t *testing.T) { // Second call: returns the updated reference after first file creation w.WriteHeader(http.StatusOK) b, _ := json.Marshal(&github.Reference{ - Ref: github.Ptr("refs/heads/main"), - Object: &github.GitObject{SHA: github.Ptr("init456")}, + Ref: new("refs/heads/main"), + Object: &github.GitObject{SHA: new("init456")}, }) _, _ = w.Write(b) } @@ -3340,7 +3407,7 @@ func Test_PushFiles(t *testing.T) { WithRequestMatch( GetReposByOwnerByRepo, &github.Repository{ - DefaultBranch: github.Ptr("main"), + DefaultBranch: new("main"), }, ), // Create initial empty README.md file using Contents API to initialize repo @@ -3358,13 +3425,11 @@ func Test_PushFiles(t *testing.T) { w.WriteHeader(http.StatusCreated) response := &github.RepositoryContentResponse{ Content: &github.RepositoryContent{ - SHA: github.Ptr("readme123"), + SHA: new("readme123"), }, - Commit: github.Commit{ - SHA: github.Ptr("init456"), - Tree: &github.Tree{ - SHA: github.Ptr("tree456"), - }, + SHA: new("init456"), + Tree: &github.Tree{ + SHA: new("tree456"), }, } b, _ := json.Marshal(response) @@ -3377,9 +3442,9 @@ func Test_PushFiles(t *testing.T) { http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) response := &github.Commit{ - SHA: github.Ptr("init456"), + SHA: new("init456"), Tree: &github.Tree{ - SHA: github.Ptr("tree456"), + SHA: new("tree456"), }, } b, _ := json.Marshal(response) @@ -3479,7 +3544,7 @@ func Test_PushFiles(t *testing.T) { WithRequestMatch( GetReposByOwnerByRepo, &github.Repository{ - DefaultBranch: github.Ptr("main"), + DefaultBranch: new("main"), }, ), // Fail to create initial file using Contents API @@ -3532,15 +3597,15 @@ func Test_PushFiles(t *testing.T) { WithRequestMatch( GetReposByOwnerByRepo, &github.Repository{ - DefaultBranch: github.Ptr("main"), + DefaultBranch: new("main"), }, ), // Create initial file using Contents API WithRequestMatch( PutReposContentsByOwnerByRepoByPath, &github.RepositoryContentResponse{ - Content: &github.RepositoryContent{SHA: github.Ptr("readme123")}, - Commit: github.Commit{SHA: github.Ptr("init456")}, + Content: &github.RepositoryContent{SHA: new("readme123")}, + SHA: new("init456"), }, ), ), @@ -3578,15 +3643,15 @@ func Test_PushFiles(t *testing.T) { WithRequestMatch( GetReposByOwnerByRepo, &github.Repository{ - DefaultBranch: github.Ptr("main"), + DefaultBranch: new("main"), }, ), // Create initial file using Contents API WithRequestMatch( PutReposContentsByOwnerByRepoByPath, &github.RepositoryContentResponse{ - Content: &github.RepositoryContent{SHA: github.Ptr("readme123")}, - Commit: github.Commit{SHA: github.Ptr("init456")}, + Content: &github.RepositoryContent{SHA: new("readme123")}, + SHA: new("init456"), }, ), // Fail to get commit @@ -3668,7 +3733,6 @@ func Test_PushFiles(t *testing.T) { func Test_DeleteRepository(t *testing.T) { serverTool := DeleteRepository(translations.NullTranslationHelper) tool := serverTool.Tool - require.NoError(t, toolsnaps.Test(tool.Name, tool)) schema, ok := tool.InputSchema.(*jsonschema.Schema) require.True(t, ok, "InputSchema should be *jsonschema.Schema") @@ -4122,12 +4186,12 @@ func Test_ListBranches(t *testing.T) { // Setup mock branches for success case mockBranches := []*github.Branch{ { - Name: github.Ptr("main"), - Commit: &github.RepositoryCommit{SHA: github.Ptr("abc123")}, + Name: new("main"), + Commit: &github.RepositoryCommit{SHA: new("abc123")}, }, { - Name: github.Ptr("develop"), - Commit: &github.RepositoryCommit{SHA: github.Ptr("def456")}, + Name: new("develop"), + Commit: &github.RepositoryCommit{SHA: new("def456")}, }, } @@ -4224,7 +4288,6 @@ func Test_DeleteFile(t *testing.T) { // Verify tool definition once serverTool := DeleteFile(translations.NullTranslationHelper) tool := serverTool.Tool - require.NoError(t, toolsnaps.Test(tool.Name, tool)) schema, ok := tool.InputSchema.(*jsonschema.Schema) require.True(t, ok, "InputSchema should be *jsonschema.Schema") @@ -4241,27 +4304,27 @@ func Test_DeleteFile(t *testing.T) { // Setup mock objects for Git Data API mockRef := &github.Reference{ - Ref: github.Ptr("refs/heads/main"), + Ref: new("refs/heads/main"), Object: &github.GitObject{ - SHA: github.Ptr("abc123"), + SHA: new("abc123"), }, } mockCommit := &github.Commit{ - SHA: github.Ptr("abc123"), + SHA: new("abc123"), Tree: &github.Tree{ - SHA: github.Ptr("def456"), + SHA: new("def456"), }, } mockTree := &github.Tree{ - SHA: github.Ptr("ghi789"), + SHA: new("ghi789"), } mockNewCommit := &github.Commit{ - SHA: github.Ptr("jkl012"), - Message: github.Ptr("Delete example file"), - HTMLURL: github.Ptr("https://github.com/owner/repo/commit/jkl012"), + SHA: new("jkl012"), + Message: new("Delete example file"), + HTMLURL: new("https://github.com/owner/repo/commit/jkl012"), } tests := []struct { @@ -4321,9 +4384,9 @@ func Test_DeleteFile(t *testing.T) { "force": false, }).andThen( mockResponse(t, http.StatusOK, &github.Reference{ - Ref: github.Ptr("refs/heads/main"), + Ref: new("refs/heads/main"), Object: &github.GitObject{ - SHA: github.Ptr("jkl012"), + SHA: new("jkl012"), }, }), ), @@ -4422,22 +4485,22 @@ func Test_ListTags(t *testing.T) { // Setup mock tags for success case mockTags := []*github.RepositoryTag{ { - Name: github.Ptr("v1.0.0"), + Name: new("v1.0.0"), Commit: &github.Commit{ - SHA: github.Ptr("v1.0.0-tag-sha"), - URL: github.Ptr("https://api.github.com/repos/owner/repo/commits/abc123"), + SHA: new("v1.0.0-tag-sha"), + URL: new("https://api.github.com/repos/owner/repo/commits/abc123"), }, - ZipballURL: github.Ptr("https://github.com/owner/repo/zipball/v1.0.0"), - TarballURL: github.Ptr("https://github.com/owner/repo/tarball/v1.0.0"), + ZipballURL: new("https://github.com/owner/repo/zipball/v1.0.0"), + TarballURL: new("https://github.com/owner/repo/tarball/v1.0.0"), }, { - Name: github.Ptr("v0.9.0"), + Name: new("v0.9.0"), Commit: &github.Commit{ - SHA: github.Ptr("v0.9.0-tag-sha"), - URL: github.Ptr("https://api.github.com/repos/owner/repo/commits/def456"), + SHA: new("v0.9.0-tag-sha"), + URL: new("https://api.github.com/repos/owner/repo/commits/def456"), }, - ZipballURL: github.Ptr("https://github.com/owner/repo/zipball/v0.9.0"), - TarballURL: github.Ptr("https://github.com/owner/repo/tarball/v0.9.0"), + ZipballURL: new("https://github.com/owner/repo/zipball/v0.9.0"), + TarballURL: new("https://github.com/owner/repo/tarball/v0.9.0"), }, } @@ -4538,7 +4601,6 @@ func Test_GetTag(t *testing.T) { // Verify tool definition once serverTool := GetTag(translations.NullTranslationHelper) tool := serverTool.Tool - require.NoError(t, toolsnaps.Test(tool.Name, tool)) schema, ok := tool.InputSchema.(*jsonschema.Schema) require.True(t, ok, "InputSchema should be *jsonschema.Schema") @@ -4551,28 +4613,28 @@ func Test_GetTag(t *testing.T) { assert.ElementsMatch(t, schema.Required, []string{"owner", "repo", "tag"}) mockAnnotatedTagRef := &github.Reference{ - Ref: github.Ptr("refs/tags/v1.0.0"), + Ref: new("refs/tags/v1.0.0"), Object: &github.GitObject{ - Type: github.Ptr("tag"), - SHA: github.Ptr("v1.0.0-tag-sha"), + Type: new("tag"), + SHA: new("v1.0.0-tag-sha"), }, } mockLightweightTagRef := &github.Reference{ - Ref: github.Ptr("refs/tags/v1.0.1"), + Ref: new("refs/tags/v1.0.1"), Object: &github.GitObject{ - Type: github.Ptr("commit"), - SHA: github.Ptr("abc123"), + Type: new("commit"), + SHA: new("abc123"), }, } mockTagObj := &github.Tag{ - SHA: github.Ptr("v1.0.0-tag-sha"), - Tag: github.Ptr("v1.0.0"), - Message: github.Ptr("Release v1.0.0"), + SHA: new("v1.0.0-tag-sha"), + Tag: new("v1.0.0"), + Message: new("Release v1.0.0"), Object: &github.GitObject{ - Type: github.Ptr("commit"), - SHA: github.Ptr("abc123"), + Type: new("commit"), + SHA: new("abc123"), }, } @@ -4740,7 +4802,6 @@ func Test_GetTag(t *testing.T) { func Test_ListReleases(t *testing.T) { serverTool := ListReleases(translations.NullTranslationHelper) tool := serverTool.Tool - require.NoError(t, toolsnaps.Test(tool.Name, tool)) schema, ok := tool.InputSchema.(*jsonschema.Schema) require.True(t, ok, "InputSchema should be *jsonschema.Schema") @@ -4756,12 +4817,12 @@ func Test_ListReleases(t *testing.T) { { ID: 1, TagName: "v1.0.0", - Name: github.Ptr("First Release"), + Name: new("First Release"), }, { ID: 2, TagName: "v0.9.0", - Name: github.Ptr("Beta Release"), + Name: new("Beta Release"), }, } @@ -4840,7 +4901,6 @@ func Test_ListReleases(t *testing.T) { func Test_GetLatestRelease(t *testing.T) { serverTool := GetLatestRelease(translations.NullTranslationHelper) tool := serverTool.Tool - require.NoError(t, toolsnaps.Test(tool.Name, tool)) schema, ok := tool.InputSchema.(*jsonschema.Schema) require.True(t, ok, "InputSchema should be *jsonschema.Schema") @@ -4854,8 +4914,8 @@ func Test_GetLatestRelease(t *testing.T) { mockRelease := &github.RepositoryRelease{ ID: 1, TagName: "v1.0.0", - Name: github.Ptr("can't \"quote\" AT&T\u200B"), - Body: github.Ptr("