diff --git a/README.md b/README.md index 166dbe0c9c..d8caa6245f 100644 --- a/README.md +++ b/README.md @@ -1489,7 +1489,7 @@ For negotiated supported protocol versions `2026-07-28` or newer, the consolidat - **get_file_contents** - Get file or directory contents - **OAuth Challenge Scopes**: `repo` - - `fields`: Subset of fields to return for each entry when the path is a directory. If omitted, all fields are returned. Ignored when the path is a single file. Use this to reduce response size when listing directories and you only need specific fields, e.g. just 'name' and 'type'. (string[], optional) + - `fields`: Subset of fields to return for each entry when the path is a directory. 'download_url' is omitted by default; request it explicitly in 'fields' when needed. Ignored when the path is a single file. Use this to reduce response size when listing directories and you only need specific fields, e.g. just 'name' and 'type'. (string[], optional) - `owner`: Repository owner (username or organization) (string, required) - `path`: Path to file/directory (string, optional) - `ref`: Accepts optional git refs such as `refs/tags/{tag}`, `refs/heads/{branch}` or `refs/pull/{pr_number}/head` (string, optional) diff --git a/pkg/github/__toolsnaps__/get_file_contents.snap b/pkg/github/__toolsnaps__/get_file_contents.snap index fa845c7d50..460e150fc7 100644 --- a/pkg/github/__toolsnaps__/get_file_contents.snap +++ b/pkg/github/__toolsnaps__/get_file_contents.snap @@ -20,7 +20,7 @@ "inputSchema": { "properties": { "fields": { - "description": "Subset of fields to return for each entry when the path is a directory. If omitted, all fields are returned. Ignored when the path is a single file. Use this to reduce response size when listing directories and you only need specific fields, e.g. just 'name' and 'type'.", + "description": "Subset of fields to return for each entry when the path is a directory. 'download_url' is omitted by default; request it explicitly in 'fields' when needed. Ignored when the path is a single file. Use this to reduce response size when listing directories and you only need specific fields, e.g. just 'name' and 'type'.", "items": { "enum": [ "type", diff --git a/pkg/github/repositories.go b/pkg/github/repositories.go index b884f4888d..eb347b8816 100644 --- a/pkg/github/repositories.go +++ b/pkg/github/repositories.go @@ -1007,7 +1007,7 @@ func GetFileContents(t translations.TranslationHelperFunc) inventory.ServerTool Required: []string{"owner", "repo"}, } schema.Properties["fields"] = fieldsSchemaProperty( - "Subset of fields to return for each entry when the path is a directory. If omitted, all fields are returned. Ignored when the path is a single file. Use this to reduce response size when listing directories and you only need specific fields, e.g. just 'name' and 'type'.", + "Subset of fields to return for each entry when the path is a directory. 'download_url' is omitted by default; request it explicitly in 'fields' when needed. Ignored when the path is a single file. Use this to reduce response size when listing directories and you only need specific fields, e.g. just 'name' and 'type'.", fileContentFieldEnum, ) @@ -1192,7 +1192,8 @@ func GetFileContents(t translations.TranslationHelperFunc) inventory.ServerTool } else if dirContent != nil { // file content or file SHA is nil which means it's a directory filtered := false - var payload any = dirContent + defaultEntries := cloneDirectoryEntriesWithoutDownloadURLs(dirContent) + var payload any = defaultEntries if len(fields) > 0 { filteredEntries, err := filterEachField(dirContent, fields) if err != nil { @@ -1205,7 +1206,7 @@ func GetFileContents(t translations.TranslationHelperFunc) inventory.ServerTool if err != nil { return utils.NewToolResultError("failed to marshal response"), nil, nil } - recordDirContentsFieldsUsage(ctx, deps, dirContent, filtered, len(r)) + recordDirContentsFieldsUsage(ctx, deps, defaultEntries, filtered, len(r)) var output []*RepositoryDirectoryEntryOutput if err := json.Unmarshal(r, &output); err != nil { return nil, nil, fmt.Errorf("failed to decode typed directory contents: %w", err) @@ -1226,8 +1227,25 @@ func GetFileContents(t translations.TranslationHelperFunc) inventory.ServerTool ) } +// cloneDirectoryEntriesWithoutDownloadURLs returns directory entries without +// download URLs while leaving the API response untouched. +func cloneDirectoryEntriesWithoutDownloadURLs(entries []*github.RepositoryContent) []*github.RepositoryContent { + cloned := make([]*github.RepositoryContent, len(entries)) + for i, entry := range entries { + if entry == nil { + continue + } + entryCopy := *entry + entryCopy.DownloadURL = nil + cloned[i] = &entryCopy + } + return cloned +} + // recordDirContentsFieldsUsage emits fields telemetry for a get_file_contents // directory listing. sentBytes is the size of the payload actually returned. +// full is the default listing, which omits download URLs, so a request that +// opts in to download_url can send more bytes than the baseline. func recordDirContentsFieldsUsage(ctx context.Context, deps ToolDependencies, full []*github.RepositoryContent, filtered bool, sentBytes int) { recordFieldsUsageFor(ctx, deps, "get_file_contents", full, filtered, sentBytes) } diff --git a/pkg/github/repositories_test.go b/pkg/github/repositories_test.go index 9b40c932ff..c96eb7ce74 100644 --- a/pkg/github/repositories_test.go +++ b/pkg/github/repositories_test.go @@ -925,7 +925,55 @@ func Test_GetFileContents_DirectoryFieldFiltering(t *testing.T) { assert.NotContains(t, textContent.Text, "download_url") } +// Test_GetFileContents_DirectoryOmitsDownloadURLByDefault verifies that directory +// listings omit bearer-token URLs from the model-visible text by default. +func Test_GetFileContents_DirectoryOmitsDownloadURLByDefault(t *testing.T) { + const tokenizedURL = "https://raw.githubusercontent.com/owner/private-repo/main/.env.example?token=GHSAT0AAAAA_SECRET_TOKEN" //nolint:gosec // G101: Synthetic tokenized download URL fixture verifies default omission; it cannot authenticate. + result, requests := runRepositoryReadFixture(t, repositoryReadFixture{ + contents: []*github.RepositoryContent{{ + Type: new("file"), + Name: new(".env.example"), + Path: new(".env.example"), + SHA: new("abc123"), + Size: new(42), + HTMLURL: new("https://github.com/owner/private-repo/blob/main/.env.example"), + DownloadURL: new(tokenizedURL), + }}, + }, map[string]any{ + "owner": "owner", + "repo": "private-repo", + "path": "src/", + "sha": strings.Repeat("a", 40), + }) + + require.False(t, result.IsError) + assert.Equal(t, 1, requests) + textContent := getTextResult(t, result) + assert.NotContains(t, textContent.Text, "download_url") + assert.NotContains(t, textContent.Text, "GHSAT0AAAAA_SECRET_TOKEN") + assert.Contains(t, textContent.Text, ".env.example") + assert.Contains(t, textContent.Text, "html_url") +} + +func TestCloneDirectoryEntriesWithoutDownloadURLs(t *testing.T) { + const tokenizedURL = "https://raw.githubusercontent.com/owner/private-repo/main/.env.example?token=GHSAT0AAAAA_SECRET_TOKEN" //nolint:gosec // G101: Synthetic tokenized download URL fixture verifies default omission; it cannot authenticate. + entry := &github.RepositoryContent{Name: new(".env.example"), DownloadURL: new(tokenizedURL)} + original := []*github.RepositoryContent{entry, nil} + + cloned := cloneDirectoryEntriesWithoutDownloadURLs(original) + + require.Len(t, cloned, 2) + require.NotNil(t, cloned[0]) + assert.NotSame(t, entry, cloned[0]) + assert.Nil(t, cloned[0].DownloadURL) + assert.Equal(t, ".env.example", cloned[0].GetName()) + assert.Nil(t, cloned[1]) + require.NotNil(t, entry.DownloadURL) + assert.Equal(t, tokenizedURL, *entry.DownloadURL) +} + func Test_GetFileContents_DirectoryFieldsTelemetry(t *testing.T) { + const tokenizedURL = "https://raw.githubusercontent.com/owner/repo/main/README.md?token=GHSAT0AAAAA_SECRET_TOKEN" //nolint:gosec // G101: Synthetic tokenized download URL fixture sizes the telemetry baseline; it cannot authenticate. mockDirContent := []*github.RepositoryContent{ { Type: new("file"), @@ -935,45 +983,64 @@ func Test_GetFileContents_DirectoryFieldsTelemetry(t *testing.T) { 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"), + DownloadURL: new(tokenizedURL), }, } + // The baseline is the default listing, which omits download_url. + defaultPayload, err := json.Marshal(cloneDirectoryEntriesWithoutDownloadURLs(mockDirContent)) + require.NoError(t, err) + require.NotContains(t, string(defaultPayload), "download_url") serverTool := GetFileContents(translations.NullTranslationHelper) - client := mustNewGHClient(t, MockHTTPClientWithHandlers(map[string]http.HandlerFunc{ - GetReposByOwnerByRepo: mockResponse(t, http.StatusOK, "{\"name\": \"repo\", \"default_branch\": \"main\"}"), - GetReposGitRefByOwnerByRepoByRef: mockResponse(t, http.StatusOK, "{\"ref\": \"refs/heads/main\", \"object\": {\"sha\": \"\"}}"), - GetReposContentsByOwnerByRepoByPath: expectQueryParams(t, map[string]string{}).andThen( - mockResponse(t, http.StatusOK, mockDirContent), - ), - GetRawReposContentsByOwnerByRepoByPath: expectQueryParams(t, map[string]string{"branch": "main"}).andThen( - mockResponse(t, http.StatusNotFound, nil), - ), - })) - deps, rec := depsWithRecordingMetrics(t, BaseDeps{Client: client}) - handler := serverTool.Handler(deps) + record := func(t *testing.T, fields ...any) (full, sent int64) { + t.Helper() + client := mustNewGHClient(t, MockHTTPClientWithHandlers(map[string]http.HandlerFunc{ + GetReposByOwnerByRepo: mockResponse(t, http.StatusOK, "{\"name\": \"repo\", \"default_branch\": \"main\"}"), + GetReposGitRefByOwnerByRepoByRef: mockResponse(t, http.StatusOK, "{\"ref\": \"refs/heads/main\", \"object\": {\"sha\": \"\"}}"), + GetReposContentsByOwnerByRepoByPath: expectQueryParams(t, map[string]string{}).andThen( + mockResponse(t, http.StatusOK, mockDirContent), + ), + GetRawReposContentsByOwnerByRepoByPath: expectQueryParams(t, map[string]string{"branch": "main"}).andThen( + mockResponse(t, http.StatusNotFound, nil), + ), + })) + deps, rec := depsWithRecordingMetrics(t, BaseDeps{Client: client}) + handler := serverTool.Handler(deps) - request := createMCPRequest(map[string]any{ - "owner": "owner", - "repo": "repo", - "path": "src/", - "fields": []any{"name", "type"}, - }) + request := createMCPRequest(map[string]any{ + "owner": "owner", + "repo": "repo", + "path": "src/", + "fields": fields, + }) - result, err := handler(ContextWithDeps(context.Background(), deps), &request) - require.NoError(t, err) - require.False(t, result.IsError) + result, err := handler(ContextWithDeps(context.Background(), deps), &request) + require.NoError(t, err) + require.False(t, result.IsError) - call, ok := rec.increment(metricFieldsToolCall) - require.True(t, ok) - assert.Equal(t, "get_file_contents", call.tags["tool"]) - assert.Equal(t, "true", call.tags["filtered"]) + call, ok := rec.increment(metricFieldsToolCall) + require.True(t, ok) + assert.Equal(t, "get_file_contents", call.tags["tool"]) + assert.Equal(t, "true", call.tags["filtered"]) - full, ok := rec.counter(metricFieldsBytesFull) - require.True(t, ok) - sent, ok := rec.counter(metricFieldsBytesSent) - require.True(t, ok) - assert.Greater(t, full.value, sent.value, "filtering should remove bytes") + fullCounter, ok := rec.counter(metricFieldsBytesFull) + require.True(t, ok) + sentCounter, ok := rec.counter(metricFieldsBytesSent) + require.True(t, ok) + return fullCounter.value, sentCounter.value + } + + t.Run("filtering removes bytes from the default listing", func(t *testing.T) { + full, sent := record(t, "name", "type") + assert.Equal(t, int64(len(defaultPayload)), full) + assert.Greater(t, full, sent, "filtering should remove bytes") + }) + + t.Run("opting in to download_url keeps the default baseline", func(t *testing.T) { + full, sent := record(t, "name", "download_url") + assert.Equal(t, int64(len(defaultPayload)), full) + assert.Greater(t, sent, int64(len(tokenizedURL))) + }) } func Test_GetFileContents_IFC_InsidersMode(t *testing.T) { diff --git a/pkg/github/typed_compatibility_test.go b/pkg/github/typed_compatibility_test.go index d1e68a6b1f..e74fbb5ce1 100644 --- a/pkg/github/typed_compatibility_test.go +++ b/pkg/github/typed_compatibility_test.go @@ -268,6 +268,42 @@ func TestTypedCompatibilityDirectoryProjection(t *testing.T) { } } +// TestTypedCompatibilityDirectoryDownloadURL verifies that download URLs are +// omitted from default directory listings across protocols and remain opt-in. +func TestTypedCompatibilityDirectoryDownloadURL(t *testing.T) { + tool := GetFileContents(translations.NullTranslationHelper) + for _, protocol := range []string{"2025-11-25", inventory.ProtocolVersionMultiRoundTrip} { + t.Run(protocol+"/default", func(t *testing.T) { + session := connectTypedSearchClient(t, tool, typedRepositoryDeps(t), protocol) + result, err := session.CallTool(context.Background(), &mcp.CallToolParams{ + Name: tool.Tool.Name, Arguments: map[string]any{"owner": "owner", "repo": "repo", "path": "directory"}, + }) + require.NoError(t, err) + require.False(t, result.IsError) + assert.NotContains(t, getTextResult(t, result).Text, "download_url") + if protocol == inventory.ProtocolVersionMultiRoundTrip { + require.NotNil(t, result.StructuredContent) + assert.NotContains(t, mustMarshalJSON(t, result.StructuredContent), "download_url") + } + }) + t.Run(protocol+"/explicit opt-in", func(t *testing.T) { + session := connectTypedSearchClient(t, tool, typedRepositoryDeps(t), protocol) + result, err := session.CallTool(context.Background(), &mcp.CallToolParams{ + Name: tool.Tool.Name, Arguments: map[string]any{ + "owner": "owner", "repo": "repo", "path": "directory", "fields": []string{"download_url"}, + }, + }) + require.NoError(t, err) + require.False(t, result.IsError) + assert.JSONEq(t, `[{"download_url":"https://raw.githubusercontent.com/owner/repo/main/file"}]`, getTextResult(t, result).Text) + if protocol == inventory.ProtocolVersionMultiRoundTrip { + require.NotNil(t, result.StructuredContent) + assert.Contains(t, mustMarshalJSON(t, result.StructuredContent), "download_url") + } + }) + } +} + func TestTypedCompatibilityBlameIFC(t *testing.T) { for _, private := range []bool{false, true} { for _, protocol := range []string{"2025-11-25", inventory.ProtocolVersionMultiRoundTrip} {