diff --git a/README.md b/README.md index ab7377f127..4a80f72c0e 100644 --- a/README.md +++ b/README.md @@ -1584,6 +1584,7 @@ For negotiated supported protocol versions `2026-07-28` or newer, the consolidat - **search_commits** - Search commits - **OAuth Challenge Scopes**: `repo` + - `fields`: Subset of fields to return for each commit search result. If omitted, all fields are returned. Use this to reduce response size when you only need specific fields; omitting 'commit' in particular drops the largest per-result data. (string[], optional) - `order`: Sort order (string, optional) - `page`: Page number for pagination (min 1) (number, optional) - `perPage`: Results per page for pagination (min 1, max 100) (number, optional) @@ -1592,6 +1593,7 @@ For negotiated supported protocol versions `2026-07-28` or newer, the consolidat - **search_repositories** - Search repositories - **OAuth Challenge Scopes**: `repo` + - `fields`: Subset of fields to return for each repository search result. If omitted, all fields are returned. Use this to reduce response size when you only need specific fields (e.g. 'full_name', 'html_url', 'language'). (string[], optional) - `minimal_output`: Return minimal repository information (default: true). When false, modern clients receive additional curated repository details, not the complete GitHub API object. Legacy clients retain full GitHub API repository objects. (boolean, optional) - `order`: Sort order (string, optional) - `page`: Page number for pagination (min 1) (number, optional) diff --git a/pkg/github/__toolsnaps__/search_commits.snap b/pkg/github/__toolsnaps__/search_commits.snap index b9be295c88..5f0af1afee 100644 --- a/pkg/github/__toolsnaps__/search_commits.snap +++ b/pkg/github/__toolsnaps__/search_commits.snap @@ -7,6 +7,21 @@ "description": "Search for commits across GitHub repositories using GitHub's commit search syntax. Useful for finding specific changes, authors, or messages across one or many repositories. Searches the default branch only.", "inputSchema": { "properties": { + "fields": { + "description": "Subset of fields to return for each commit search result. If omitted, all fields are returned. Use this to reduce response size when you only need specific fields; omitting 'commit' in particular drops the largest per-result data.", + "items": { + "enum": [ + "sha", + "html_url", + "commit", + "author", + "committer", + "repository" + ], + "type": "string" + }, + "type": "array" + }, "order": { "description": "Sort order", "enum": [ @@ -294,42 +309,12 @@ "object" ] }, - "files": { - "items": { - "additionalProperties": false, - "properties": { - "additions": { - "type": "integer" - }, - "changes": { - "type": "integer" - }, - "deletions": { - "type": "integer" - }, - "filename": { - "type": "string" - }, - "patch": { - "type": "string" - }, - "status": { - "type": "string" - } - }, - "required": [ - "filename" - ], - "type": "object" - }, + "html_url": { "type": [ "null", - "array" + "string" ] }, - "html_url": { - "type": "string" - }, "repository": { "additionalProperties": false, "properties": { @@ -352,31 +337,12 @@ ] }, "sha": { - "type": "string" - }, - "stats": { - "additionalProperties": false, - "properties": { - "additions": { - "type": "integer" - }, - "deletions": { - "type": "integer" - }, - "total": { - "type": "integer" - } - }, "type": [ "null", - "object" + "string" ] } }, - "required": [ - "sha", - "html_url" - ], "type": "object" }, "type": [ diff --git a/pkg/github/__toolsnaps__/search_repositories.snap b/pkg/github/__toolsnaps__/search_repositories.snap index 6c64889860..407e4c1ccf 100644 --- a/pkg/github/__toolsnaps__/search_repositories.snap +++ b/pkg/github/__toolsnaps__/search_repositories.snap @@ -7,6 +7,31 @@ "description": "Find GitHub repositories by name, description, readme, topics, or other metadata. Perfect for discovering projects, finding examples, or locating specific repositories across GitHub.", "inputSchema": { "properties": { + "fields": { + "description": "Subset of fields to return for each repository search result. If omitted, all fields are returned. Use this to reduce response size when you only need specific fields (e.g. 'full_name', 'html_url', 'language').", + "items": { + "enum": [ + "id", + "name", + "full_name", + "description", + "html_url", + "language", + "stargazers_count", + "forks_count", + "open_issues_count", + "updated_at", + "created_at", + "topics", + "private", + "fork", + "archived", + "default_branch" + ], + "type": "string" + }, + "type": "array" + }, "minimal_output": { "default": true, "description": "Return minimal repository information (default: true). When false, modern clients receive additional curated repository details, not the complete GitHub API object. Legacy clients retain full GitHub API repository objects.", @@ -63,7 +88,10 @@ "additionalProperties": false, "properties": { "archived": { - "type": "boolean" + "type": [ + "null", + "boolean" + ] }, "created_at": { "type": "string" @@ -82,13 +110,22 @@ ] }, "fork": { - "type": "boolean" + "type": [ + "null", + "boolean" + ] }, "forks_count": { - "type": "integer" + "type": [ + "null", + "integer" + ] }, "full_name": { - "type": "string" + "type": [ + "null", + "string" + ] }, "has_discussions": { "type": [ @@ -119,10 +156,16 @@ "type": "string" }, "html_url": { - "type": "string" + "type": [ + "null", + "string" + ] }, "id": { - "type": "integer" + "type": [ + "null", + "integer" + ] }, "is_template": { "description": "Whether the repository is a template", @@ -155,10 +198,16 @@ ] }, "name": { - "type": "string" + "type": [ + "null", + "string" + ] }, "open_issues_count": { - "type": "integer" + "type": [ + "null", + "integer" + ] }, "permissions": { "additionalProperties": false, @@ -201,7 +250,10 @@ ] }, "private": { - "type": "boolean" + "type": [ + "null", + "boolean" + ] }, "pushed_at": { "description": "Last push time as an ISO 8601 UTC timestamp", @@ -215,7 +267,10 @@ ] }, "stargazers_count": { - "type": "integer" + "type": [ + "null", + "integer" + ] }, "topics": { "items": { @@ -246,18 +301,6 @@ ] } }, - "required": [ - "id", - "name", - "full_name", - "html_url", - "stargazers_count", - "forks_count", - "open_issues_count", - "private", - "fork", - "archived" - ], "type": "object" }, "type": [ diff --git a/pkg/github/fields_filtering_test.go b/pkg/github/fields_filtering_test.go index b54480252f..8296c36da3 100644 --- a/pkg/github/fields_filtering_test.go +++ b/pkg/github/fields_filtering_test.go @@ -266,6 +266,154 @@ func Test_SearchIssues_FieldsTelemetry(t *testing.T) { map[string]any{"query": "bug"}) } +// --- search_repositories -------------------------------------------------- + +func mockRepositoriesSearchResult() *github.RepositoriesSearchResult { + return &github.RepositoriesSearchResult{ + Total: github.Ptr(1), + IncompleteResults: github.Ptr(false), + Repositories: []*github.Repository{ + { + ID: github.Ptr(int64(42)), + Name: github.Ptr("my-repo"), + FullName: github.Ptr("octocat/my-repo"), + Description: github.Ptr("A very long repository description that inflates context size."), + HTMLURL: github.Ptr("https://github.com/octocat/my-repo"), + Language: github.Ptr("Go"), + StargazersCount: github.Ptr(100), + ForksCount: github.Ptr(10), + OpenIssuesCount: github.Ptr(5), + Private: github.Ptr(false), + Fork: github.Ptr(false), + Archived: github.Ptr(false), + DefaultBranch: github.Ptr("main"), + Topics: []string{"mcp", "go"}, + }, + }, + } +} + +func Test_SearchRepositories_FieldFiltering(t *testing.T) { + for _, tc := range []struct { + name string + minimalOutput bool + }{ + {name: "minimal_output=true", minimalOutput: true}, + {name: "minimal_output=false", minimalOutput: false}, + } { + t.Run(tc.name, func(t *testing.T) { + serverTool := SearchRepositories(translations.NullTranslationHelper) + client := mustNewGHClient(t, MockHTTPClientWithHandlers(map[string]http.HandlerFunc{ + GetSearchRepositories: mockResponse(t, http.StatusOK, mockRepositoriesSearchResult()), + })) + deps := BaseDeps{Client: client} + handler := serverTool.Handler(deps) + + request := createMCPRequest(map[string]any{ + "query": "org:octocat", + "minimal_output": tc.minimalOutput, + "fields": []any{"full_name", "html_url"}, + }) + result, err := handler(ContextWithDeps(context.Background(), deps), &request) + require.NoError(t, err) + require.False(t, result.IsError) + + textContent := getTextResult(t, result) + var parsed struct { + TotalCount int `json:"total_count"` + IncompleteResults bool `json:"incomplete_results"` + Items []map[string]any `json:"items"` + } + require.NoError(t, json.Unmarshal([]byte(textContent.Text), &parsed)) + require.Equal(t, 1, parsed.TotalCount) + require.Len(t, parsed.Items, 1) + assert.Equal(t, map[string]any{ + "full_name": "octocat/my-repo", + "html_url": "https://github.com/octocat/my-repo", + }, parsed.Items[0]) + }) + } +} + +func Test_SearchRepositories_FieldsTelemetry(t *testing.T) { + serverTool := SearchRepositories(translations.NullTranslationHelper) + client := mustNewGHClient(t, MockHTTPClientWithHandlers(map[string]http.HandlerFunc{ + GetSearchRepositories: mockResponse(t, http.StatusOK, mockRepositoriesSearchResult()), + })) + + assertFieldsTelemetry(t, serverTool, client, "search_repositories", + map[string]any{"query": "org:octocat", "fields": []any{"full_name", "html_url"}}, + map[string]any{"query": "org:octocat"}) +} + +// --- search_commits ------------------------------------------------------- + +func mockCommitsSearchResult() *github.CommitsSearchResult { + return &github.CommitsSearchResult{ + Total: github.Ptr(1), + IncompleteResults: github.Ptr(false), + Commits: []*github.CommitResult{ + { + SHA: github.Ptr("abc123def456"), + HTMLURL: github.Ptr("https://github.com/octocat/my-repo/commit/abc123def456"), + Commit: &github.Commit{ + Message: github.Ptr("fix: handle edge case in parser with a detailed explanation"), + }, + Author: &github.User{ + Login: github.Ptr("octocat"), + }, + Repository: &github.Repository{ + FullName: github.Ptr("octocat/my-repo"), + HTMLURL: github.Ptr("https://github.com/octocat/my-repo"), + Private: github.Ptr(false), + }, + }, + }, + } +} + +func Test_SearchCommits_FieldFiltering(t *testing.T) { + serverTool := SearchCommits(translations.NullTranslationHelper) + client := mustNewGHClient(t, MockHTTPClientWithHandlers(map[string]http.HandlerFunc{ + GetSearchCommits: mockResponse(t, http.StatusOK, mockCommitsSearchResult()), + })) + deps := BaseDeps{Client: client} + handler := serverTool.Handler(deps) + + request := createMCPRequest(map[string]any{ + "query": "repo:octocat/my-repo fix", + "fields": []any{"sha", "html_url"}, + }) + result, err := handler(ContextWithDeps(context.Background(), deps), &request) + require.NoError(t, err) + require.False(t, result.IsError) + + textContent := getTextResult(t, result) + var parsed struct { + TotalCount int `json:"total_count"` + IncompleteResults bool `json:"incomplete_results"` + Items []map[string]any `json:"items"` + } + require.NoError(t, json.Unmarshal([]byte(textContent.Text), &parsed)) + require.Equal(t, 1, parsed.TotalCount) + require.Len(t, parsed.Items, 1) + assert.Equal(t, map[string]any{ + "sha": "abc123def456", + "html_url": "https://github.com/octocat/my-repo/commit/abc123def456", + }, parsed.Items[0]) +} + +func Test_SearchCommits_FieldsTelemetry(t *testing.T) { + serverTool := SearchCommits(translations.NullTranslationHelper) + client := mustNewGHClient(t, MockHTTPClientWithHandlers(map[string]http.HandlerFunc{ + GetSearchCommits: mockResponse(t, http.StatusOK, mockCommitsSearchResult()), + })) + + assertFieldsTelemetry(t, serverTool, client, "search_commits", + map[string]any{"query": "repo:octocat/my-repo fix", "fields": []any{"sha", "html_url"}}, + map[string]any{"query": "repo:octocat/my-repo fix"}) +} + // --- list_issues (GraphQL) ------------------------------------------------ // listIssuesFieldsQuery and listIssuesFieldsVars mirror the exact GraphQL query diff --git a/pkg/github/minimal_types.go b/pkg/github/minimal_types.go index d355eb1a2e..66f9907bf1 100644 --- a/pkg/github/minimal_types.go +++ b/pkg/github/minimal_types.go @@ -93,6 +93,25 @@ var searchPullRequestsItemFieldEnum = []any{ "closed_by", "pull_request", "repository_url", } +// searchRepositoriesItemFieldEnum lists the selectable fields for +// search_repositories result items, matching the JSON field names of +// MinimalRepository. The description and topics fields are typically the +// heaviest, so omitting them shrinks large result sets. +var searchRepositoriesItemFieldEnum = []any{ + "id", "name", "full_name", "description", "html_url", "language", + "stargazers_count", "forks_count", "open_issues_count", + "updated_at", "created_at", "topics", "private", "fork", "archived", + "default_branch", +} + +// searchCommitsItemFieldEnum lists the selectable fields for search_commits +// result items, matching the JSON field names of MinimalCommitSearchItem. +// The commit field (message plus author/committer metadata) is the heaviest, +// so omitting it is the main lever for shrinking large result sets. +var searchCommitsItemFieldEnum = []any{ + "sha", "html_url", "commit", "author", "committer", "repository", +} + // filterFields marshals v to a JSON object and returns a map containing only the // requested fields. Fields that are unknown or absent from the JSON (for example // empty values dropped via omitempty) are skipped. diff --git a/pkg/github/search.go b/pkg/github/search.go index 6caaf389d5..290a509f77 100644 --- a/pkg/github/search.go +++ b/pkg/github/search.go @@ -46,6 +46,10 @@ func SearchRepositories(t translations.TranslationHelperFunc) inventory.ServerTo }, Required: []string{"query"}, } + schema.Properties["fields"] = fieldsSchemaProperty( + "Subset of fields to return for each repository search result. If omitted, all fields are returned. Use this to reduce response size when you only need specific fields (e.g. 'full_name', 'html_url', 'language').", + searchRepositoriesItemFieldEnum, + ) WithPagination(schema) return NewTool[SearchRepositoriesInput, *SearchRepositoriesOutput]( @@ -100,6 +104,8 @@ func SearchRepositories(t translations.TranslationHelperFunc) inventory.ServerTo // Return either minimal or full response based on parameter var r []byte + var fullPayload any + filtered := false output = &SearchRepositoriesOutput{ TotalCount: result.GetTotal(), IncompleteResults: result.GetIncompleteResults(), @@ -110,7 +116,7 @@ func SearchRepositories(t translations.TranslationHelperFunc) inventory.ServerTo for _, repo := range result.Repositories { minimalRepo := minimalSearchRepository(repo) minimalRepos = append(minimalRepos, minimalRepo) - output.Items = append(output.Items, SearchRepository{MinimalRepository: minimalRepo}) + output.Items = append(output.Items, projectSearchRepository(searchRepositoryFromMinimal(minimalRepo), input.Fields)) } minimalResult := &MinimalSearchRepositoriesResult{ @@ -118,21 +124,53 @@ func SearchRepositories(t translations.TranslationHelperFunc) inventory.ServerTo IncompleteResults: result.GetIncompleteResults(), Items: minimalRepos, } + fullPayload = minimalResult + + var payload any = minimalResult + if len(input.Fields) > 0 { + filteredItems, err := filterEachField(minimalRepos, input.Fields) + if err != nil { + return utils.NewToolResultErrorFromErr("failed to filter repository search results", err), nil, nil + } + payload = map[string]any{ + "total_count": minimalResult.TotalCount, + "incomplete_results": minimalResult.IncompleteResults, + "items": filteredItems, + } + filtered = true + } - r, err = json.Marshal(minimalResult) + r, err = json.Marshal(payload) if err != nil { return utils.NewToolResultErrorFromErr("failed to marshal minimal response", err), nil, nil } } else { - r, err = json.Marshal(result) + fullPayload = result + var payload any = result + if len(input.Fields) > 0 { + filteredItems, err := filterEachField(result.Repositories, input.Fields) + if err != nil { + return utils.NewToolResultErrorFromErr("failed to filter repository search results", err), nil, nil + } + payload = map[string]any{ + "total_count": result.GetTotal(), + "incomplete_results": result.GetIncompleteResults(), + "items": filteredItems, + } + filtered = true + } + + r, err = json.Marshal(payload) if err != nil { return utils.NewToolResultErrorFromErr("failed to marshal full response", err), nil, nil } for _, repo := range result.Repositories { - output.Items = append(output.Items, fullSearchRepository(repo)) + output.Items = append(output.Items, projectSearchRepository(fullSearchRepository(repo), input.Fields)) } } + recordFieldsUsageFor(ctx, deps, "search_repositories", fullPayload, filtered, len(r)) + callResult := utils.NewToolResultText(string(r)) attachSearchRepositoriesIFCLabel(ctx, deps, result.Repositories, callResult) return callResult, output, nil @@ -591,9 +629,13 @@ func SearchCommits(t translations.TranslationHelperFunc) inventory.ServerTool { }, Required: []string{"query"}, } + schema.Properties["fields"] = fieldsSchemaProperty( + "Subset of fields to return for each commit search result. If omitted, all fields are returned. Use this to reduce response size when you only need specific fields; omitting 'commit' in particular drops the largest per-result data.", + searchCommitsItemFieldEnum, + ) WithPagination(schema) - return NewTool[SearchCommitsInput, *MinimalSearchCommitsResult]( + return NewTool[SearchCommitsInput, *SearchCommitsOutput]( ToolsetMetadataRepos, mcp.Tool{ Name: "search_commits", @@ -605,7 +647,7 @@ func SearchCommits(t translations.TranslationHelperFunc) inventory.ServerTool { InputSchema: schema, }, scopes.PublicRead(scopes.Repo), - func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, input SearchCommitsInput) (*mcp.CallToolResult, *MinimalSearchCommitsResult, error) { + func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, input SearchCommitsInput) (*mcp.CallToolResult, *SearchCommitsOutput, error) { if input.Query == "" { return utils.NewToolResultError("missing required parameter: query"), nil, nil } @@ -652,11 +694,28 @@ func SearchCommits(t translations.TranslationHelperFunc) inventory.ServerTool { Items: minimalCommits, } - r, err := json.Marshal(minimalResult) + filtered := false + var payload any = minimalResult + if len(input.Fields) > 0 { + filteredItems, err := filterEachField(minimalCommits, input.Fields) + if err != nil { + return utils.NewToolResultErrorFromErr("failed to filter commit search results", err), nil, nil + } + payload = map[string]any{ + "total_count": minimalResult.TotalCount, + "incomplete_results": minimalResult.IncompleteResults, + "items": filteredItems, + } + filtered = true + } + + r, err := json.Marshal(payload) if err != nil { return utils.NewToolResultErrorFromErr("failed to marshal response", err), nil, nil } + recordFieldsUsageFor(ctx, deps, "search_commits", minimalResult, filtered, len(r)) + callResult := utils.NewToolResultText(string(r)) // Commit search spans repositories; the IFC label is the conservative // join across every matched repository's visibility, read directly @@ -668,7 +727,7 @@ func SearchCommits(t translations.TranslationHelperFunc) inventory.ServerTool { } } callResult = attachJoinedIFCLabel(ctx, deps, callResult, visibilities, ifc.LabelSearchIssues) - return callResult, minimalResult, nil + return callResult, structuredSearchCommitsOutput(minimalResult, input.Fields), nil }, normalizeSearchArguments(false), ) diff --git a/pkg/github/search_tool_types.go b/pkg/github/search_tool_types.go index 855841186e..13ca138844 100644 --- a/pkg/github/search_tool_types.go +++ b/pkg/github/search_tool_types.go @@ -2,6 +2,7 @@ package github import ( "encoding/json" + "slices" "github.com/google/go-github/v92/github" "github.com/google/jsonschema-go/jsonschema" @@ -17,10 +18,14 @@ type SearchAccountsInput struct { type SearchRepositoriesInput struct { SearchAccountsInput - MinimalOutput *bool `json:"minimal_output,omitempty"` + MinimalOutput *bool `json:"minimal_output,omitempty"` + Fields []string `json:"fields,omitempty"` } -type SearchCommitsInput = SearchAccountsInput +type SearchCommitsInput struct { + SearchAccountsInput + Fields []string `json:"fields,omitempty"` +} // SearchRepositoriesOutput is the structured repository search result. Minimal // output reuses MinimalRepository; full output adds a compact set of @@ -31,8 +36,72 @@ type SearchRepositoriesOutput struct { Items []SearchRepository `json:"items"` } +type SearchCommitsOutput struct { + TotalCount int `json:"total_count"` + IncompleteResults bool `json:"incomplete_results"` + Items []SearchCommitOutputItem `json:"items"` +} + +type SearchCommitOutputItem 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"` + Repository *MinimalRepoRef `json:"repository,omitempty"` +} + +func structuredSearchCommitsOutput(result *MinimalSearchCommitsResult, fields []string) *SearchCommitsOutput { + output := &SearchCommitsOutput{ + TotalCount: result.TotalCount, + IncompleteResults: result.IncompleteResults, + Items: make([]SearchCommitOutputItem, 0, len(result.Items)), + } + selected := func(field string) bool { + return len(fields) == 0 || slices.Contains(fields, field) + } + for _, commit := range result.Items { + item := SearchCommitOutputItem{} + 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 + } + if selected("repository") { + item.Repository = commit.Repository + } + output.Items = append(output.Items, item) + } + return output +} + type SearchRepository struct { - MinimalRepository + ID *int64 `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + FullName *string `json:"full_name,omitempty"` + Description string `json:"description,omitempty"` + HTMLURL *string `json:"html_url,omitempty"` + Language string `json:"language,omitempty"` + Stars *int `json:"stargazers_count,omitempty"` + Forks *int `json:"forks_count,omitempty"` + OpenIssues *int `json:"open_issues_count,omitempty"` + UpdatedAt string `json:"updated_at,omitempty"` + CreatedAt string `json:"created_at,omitempty"` + Topics []string `json:"topics,omitempty"` + Private *bool `json:"private,omitempty"` + Fork *bool `json:"fork,omitempty"` + Archived *bool `json:"archived,omitempty"` + DefaultBranch string `json:"default_branch,omitempty"` Homepage string `json:"homepage,omitempty" jsonschema:"Repository homepage URL"` Visibility string `json:"visibility,omitempty" jsonschema:"Repository visibility"` PushedAt string `json:"pushed_at,omitempty" jsonschema:"Last push time as an ISO 8601 UTC timestamp"` @@ -101,20 +170,98 @@ func minimalSearchRepository(repo *github.Repository) MinimalRepository { return minimalRepo } -func fullSearchRepository(repo *github.Repository) SearchRepository { - out := SearchRepository{ - MinimalRepository: minimalSearchRepository(repo), - Homepage: repo.GetHomepage(), - Visibility: repo.GetVisibility(), - WatchersCount: repo.WatchersCount, - Size: repo.Size, - Disabled: repo.Disabled, - IsTemplate: repo.IsTemplate, - HasIssues: repo.HasIssues, - HasProjects: repo.HasProjects, - HasWiki: repo.HasWiki, - HasDiscussions: repo.HasDiscussions, +func searchRepositoryFromMinimal(minimal MinimalRepository) SearchRepository { + return SearchRepository{ + ID: new(minimal.ID), + Name: new(minimal.Name), + FullName: new(minimal.FullName), + Description: minimal.Description, + HTMLURL: new(minimal.HTMLURL), + Language: minimal.Language, + Stars: new(minimal.Stars), + Forks: new(minimal.Forks), + OpenIssues: new(minimal.OpenIssues), + UpdatedAt: minimal.UpdatedAt, + CreatedAt: minimal.CreatedAt, + Topics: minimal.Topics, + Private: new(minimal.Private), + Fork: new(minimal.Fork), + Archived: new(minimal.Archived), + DefaultBranch: minimal.DefaultBranch, + } +} + +func projectSearchRepository(repo SearchRepository, fields []string) SearchRepository { + if len(fields) == 0 { + return repo + } + selected := func(field string) bool { + return slices.Contains(fields, field) + } + var out SearchRepository + if selected("id") { + out.ID = repo.ID + } + if selected("name") { + out.Name = repo.Name } + if selected("full_name") { + out.FullName = repo.FullName + } + if selected("description") { + out.Description = repo.Description + } + if selected("html_url") { + out.HTMLURL = repo.HTMLURL + } + if selected("language") { + out.Language = repo.Language + } + if selected("stargazers_count") { + out.Stars = repo.Stars + } + if selected("forks_count") { + out.Forks = repo.Forks + } + if selected("open_issues_count") { + out.OpenIssues = repo.OpenIssues + } + if selected("updated_at") { + out.UpdatedAt = repo.UpdatedAt + } + if selected("created_at") { + out.CreatedAt = repo.CreatedAt + } + if selected("topics") { + out.Topics = repo.Topics + } + if selected("private") { + out.Private = repo.Private + } + if selected("fork") { + out.Fork = repo.Fork + } + if selected("archived") { + out.Archived = repo.Archived + } + if selected("default_branch") { + out.DefaultBranch = repo.DefaultBranch + } + return out +} + +func fullSearchRepository(repo *github.Repository) SearchRepository { + out := searchRepositoryFromMinimal(minimalSearchRepository(repo)) + out.Homepage = repo.GetHomepage() + out.Visibility = repo.GetVisibility() + out.WatchersCount = repo.WatchersCount + out.Size = repo.Size + out.Disabled = repo.Disabled + out.IsTemplate = repo.IsTemplate + out.HasIssues = repo.HasIssues + out.HasProjects = repo.HasProjects + out.HasWiki = repo.HasWiki + out.HasDiscussions = repo.HasDiscussions if repo.PushedAt != nil { out.PushedAt = repo.PushedAt.Format("2006-01-02T15:04:05Z") } @@ -152,6 +299,17 @@ func normalizeSearchArguments(minimalOutput bool) func(json.RawMessage) (json.Ra return nil, err } } + if fields, present := args["fields"]; present && fields == nil { + delete(args, "fields") + var err error + raw, err = json.Marshal(args) + if err != nil { + return nil, err + } + } + if _, err := OptionalStringArrayParam(args, "fields"); err != nil { + return nil, err + } return normalizeRepositoryArguments(raw) } } diff --git a/pkg/github/typed_account_repository_search_test.go b/pkg/github/typed_account_repository_search_test.go index 64d32b2973..6bbb017980 100644 --- a/pkg/github/typed_account_repository_search_test.go +++ b/pkg/github/typed_account_repository_search_test.go @@ -179,10 +179,18 @@ func TestTypedAccountRepositorySearchOutputs(t *testing.T) { } for _, args := range []map[string]any{ {}, {"page": 0, "perPage": 0}, {"page": "0", "perPage": "0"}, - {"page": "0e0", "perPage": "-0"}, {"fields": []string{"id"}}, + {"page": "0e0", "perPage": "-0"}, } { check(args, fixture.text) } + switch tool.Tool.Name { + case "search_repositories": + check(map[string]any{"fields": []string{"id"}}, `{"incomplete_results":false,"items":[{"id":7}],"total_count":1}`) + case "search_commits": + check(map[string]any{"fields": []string{"sha"}}, `{"incomplete_results":false,"items":[{"sha":"abc"},{"sha":"def"}],"total_count":2}`) + default: + check(map[string]any{"fields": []string{"id"}}, fixture.text) + } page, perPage, order = "2", "7", "asc" switch tool.Tool.Name { case "search_repositories": @@ -333,5 +341,5 @@ func TestSearchOutputsHaveNoUntypedFields(t *testing.T) { } check(reflect.TypeFor[SearchRepositoriesOutput]()) check(reflect.TypeFor[MinimalSearchUsersResult]()) - check(reflect.TypeFor[MinimalSearchCommitsResult]()) + check(reflect.TypeFor[SearchCommitsOutput]()) }