Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1576,11 +1576,13 @@ For negotiated supported protocol versions `2026-07-28` or newer, the consolidat
- **get_secret_scanning_alert** - Get secret scanning alert
- **OAuth Challenge Scopes**: `security_events`
- `alertNumber`: The number of the alert. (number, required)
- `hide_secret`: Whether to exclude the secret value from the response. Defaults to false. (boolean, optional)
- `owner`: The owner of the repository. (string, required)
- `repo`: The name of the repository. (string, required)

- **list_secret_scanning_alerts** - List secret scanning alerts
- **OAuth Challenge Scopes**: `security_events`
- `hide_secret`: Whether to exclude secret values from the response. Defaults to false. (boolean, optional)
- `owner`: The owner of the repository. (string, required)
- `page`: Page number for pagination (min 1) (number, optional)
- `perPage`: Results per page for pagination (min 1, max 100) (number, optional)
Expand Down
4 changes: 4 additions & 0 deletions pkg/github/__toolsnaps__/get_secret_scanning_alert.snap
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@
"description": "The number of the alert.",
"type": "number"
},
"hide_secret": {
"description": "Whether to exclude the secret value from the response. Defaults to false.",
"type": "boolean"
},
"owner": {
"description": "The owner of the repository.",
"type": "string"
Expand Down
4 changes: 4 additions & 0 deletions pkg/github/__toolsnaps__/list_secret_scanning_alerts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@
"description": "List secret scanning alerts in a GitHub repository.",
"inputSchema": {
"properties": {
"hide_secret": {
"description": "Whether to exclude secret values from the response. Defaults to false.",
"type": "boolean"
},
"owner": {
"description": "The owner of the repository.",
"type": "string"
Expand Down
67 changes: 51 additions & 16 deletions pkg/github/secret_scanning.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import (
"fmt"
"io"
"net/http"
"net/url"
"strconv"

ghErrors "github.com/github/github-mcp-server/v2/pkg/errors"
"github.com/github/github-mcp-server/v2/pkg/ifc"
Expand All @@ -19,7 +21,7 @@ import (
)

func GetSecretScanningAlert(t translations.TranslationHelperFunc) inventory.ServerTool {
return NewTool[GetSecurityAlertInput, *SecretScanningAlertOutput](
return NewTool[GetSecretScanningAlertInput, *SecretScanningAlertOutput](
ToolsetMetadataSecretProtection,
mcp.Tool{
Name: "get_secret_scanning_alert",
Expand All @@ -43,12 +45,16 @@ func GetSecretScanningAlert(t translations.TranslationHelperFunc) inventory.Serv
Type: "number",
Description: "The number of the alert.",
},
"hide_secret": {
Type: "boolean",
Description: "Whether to exclude the secret value from the response. Defaults to false.",
},
},
Required: []string{"owner", "repo", "alertNumber"},
},
},
scopes.RequireAll(scopes.SecurityEvents),
func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, args GetSecurityAlertInput) (*mcp.CallToolResult, *SecretScanningAlertOutput, error) {
func(ctx context.Context, deps ToolDependencies, _ *mcp.CallToolRequest, args GetSecretScanningAlertInput) (*mcp.CallToolResult, *SecretScanningAlertOutput, error) {
if args.Owner == "" {
return utils.NewToolResultError("missing required parameter: owner"), nil, nil
}
Expand All @@ -64,16 +70,26 @@ func GetSecretScanningAlert(t translations.TranslationHelperFunc) inventory.Serv
return nil, nil, fmt.Errorf("failed to get GitHub client: %w", err)
}

alert, resp, err := client.SecretScanning.GetAlert(ctx, args.Owner, args.Repo, int64(args.AlertNumber))
apiURL := fmt.Sprintf("repos/%s/%s/secret-scanning/alerts/%d", url.PathEscape(args.Owner), url.PathEscape(args.Repo), args.AlertNumber)
if args.HideSecret != nil {
apiURL += "?hide_secret=" + strconv.FormatBool(*args.HideSecret)
}
req, err := client.NewRequest(ctx, http.MethodGet, apiURL, nil)
if err != nil {
return utils.NewToolResultErrorFromErr("failed to create request", err), nil, nil
}
var alert *github.SecretScanningAlert
resp, err := client.Do(req, &alert)
if resp != nil {
defer func() { _ = resp.Body.Close() }()
}
if err != nil {
return ghErrors.NewGitHubAPIErrorResponse(ctx,
fmt.Sprintf("failed to get alert with number '%d'", args.AlertNumber),
resp,
err,
), nil, nil
}
defer func() { _ = resp.Body.Close() }()

if resp.StatusCode != http.StatusOK {
body, err := io.ReadAll(resp.Body)
if err != nil {
Expand Down Expand Up @@ -124,6 +140,10 @@ func ListSecretScanningAlerts(t translations.TranslationHelperFunc) inventory.Se
Description: "Filter by resolution",
Enum: []any{"false_positive", "wont_fix", "revoked", "pattern_edited", "pattern_deleted", "used_in_tests"},
},
"hide_secret": {
Type: "boolean",
Description: "Whether to exclude secret values from the response. Defaults to false.",
},
},
Required: []string{"owner", "repo"},
}
Expand Down Expand Up @@ -154,24 +174,39 @@ func ListSecretScanningAlerts(t translations.TranslationHelperFunc) inventory.Se
if err != nil {
return nil, nil, fmt.Errorf("failed to get GitHub client: %w", err)
}
alerts, resp, err := client.SecretScanning.ListAlertsForRepo(ctx, args.Owner, args.Repo, &github.SecretScanningAlertListOptions{
State: args.State,
SecretType: args.SecretType,
Resolution: args.Resolution,
ListOptions: github.ListOptions{
Page: pagination.Page,
PerPage: pagination.PerPage,
},
})
query := url.Values{
"page": {strconv.Itoa(pagination.Page)},
"per_page": {strconv.Itoa(pagination.PerPage)},
}
if args.State != "" {
query.Set("state", args.State)
}
if args.SecretType != "" {
query.Set("secret_type", args.SecretType)
}
if args.Resolution != "" {
query.Set("resolution", args.Resolution)
}
if args.HideSecret != nil {
query.Set("hide_secret", strconv.FormatBool(*args.HideSecret))
}
apiURL := fmt.Sprintf("repos/%s/%s/secret-scanning/alerts?%s", url.PathEscape(args.Owner), url.PathEscape(args.Repo), query.Encode())
req, err := client.NewRequest(ctx, http.MethodGet, apiURL, nil)
if err != nil {
return utils.NewToolResultErrorFromErr("failed to create request", err), nil, nil
}
var alerts []*github.SecretScanningAlert
resp, err := client.Do(req, &alerts)
if resp != nil {
defer func() { _ = resp.Body.Close() }()
}
if err != nil {
return ghErrors.NewGitHubAPIErrorResponse(ctx,
fmt.Sprintf("failed to list alerts for repository '%s/%s'", args.Owner, args.Repo),
resp,
err,
), nil, nil
}
defer func() { _ = resp.Body.Close() }()

if resp.StatusCode != http.StatusOK {
body, err := io.ReadAll(resp.Body)
if err != nil {
Expand Down
113 changes: 113 additions & 0 deletions pkg/github/secret_scanning_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,117 @@ package github
import (
"context"
"encoding/json"
"maps"
"net/http"
"testing"

"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/google/go-github/v92/github"
"github.com/google/jsonschema-go/jsonschema"
"github.com/modelcontextprotocol/go-sdk/mcp"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func Test_GetSecretScanningAlertHideSecret(t *testing.T) {
testSecretScanningHideSecret(t, GetSecretScanningAlert(translations.NullTranslationHelper),
GetReposSecretScanningAlertsByOwnerByRepoByAlertNumber,
map[string]any{"owner": "owner", "repo": "repo", "alertNumber": 42},
map[string]string{},
func(alert string) string { return alert })
}

func Test_ListSecretScanningAlertsHideSecret(t *testing.T) {
testSecretScanningHideSecret(t, ListSecretScanningAlerts(translations.NullTranslationHelper),
GetReposSecretScanningAlertsByOwnerByRepo,
map[string]any{
"owner": "owner", "repo": "repo", "page": 2, "perPage": 50,
"state": "resolved", "secret_type": "test_secret", "resolution": "revoked",
},
map[string]string{
"page": "2", "per_page": "50", "state": "resolved",
"secret_type": "test_secret", "resolution": "revoked",
},
func(alert string) string { return "[" + alert + "]" })
}

func testSecretScanningHideSecret(t *testing.T, tool inventory.ServerTool, endpoint string, args map[string]any, query map[string]string, wrap func(string) string) {
t.Helper()
const visible = `{"number":42,"state":"resolved","secret_type":"test_secret","secret":"synthetic-test-secret"}`
const hidden = `{"number":42,"state":"resolved","secret_type":"test_secret"}`
for _, tc := range []struct {
name string
option *bool
response string
}{
{name: "absent", response: visible},
{name: "false", option: new(false), response: visible},
{name: "true", option: new(true), response: hidden},
} {
t.Run(tc.name, func(t *testing.T) {
for _, protocol := range []string{"direct", "2025-11-25", inventory.ProtocolVersionMultiRoundTrip} {
t.Run(protocol, func(t *testing.T) {
requestArgs := make(map[string]any, len(args)+1)
maps.Copy(requestArgs, args)
expectedQuery := make(map[string][]string, len(query)+1)
for key, value := range query {
expectedQuery[key] = []string{value}
}
if tc.option != nil {
requestArgs["hide_secret"] = *tc.option
expectedQuery["hide_secret"] = []string{tc.name}
}
response := wrap(tc.response)
calls := 0
deps := BaseDeps{
Client: mustNewGHClient(t, MockHTTPClientWithHandlers(map[string]http.HandlerFunc{
endpoint: func(w http.ResponseWriter, r *http.Request) {
calls++
assert.Equal(t, http.MethodGet, r.Method)
assert.EqualValues(t, expectedQuery, r.URL.Query())
mockResponse(t, http.StatusOK, json.RawMessage(response))(w, r)
},
})),
featureChecker: featureCheckerFor(FeatureFlagIFCLabels),
}
ctx := ContextWithDeps(context.Background(), deps)
var result *mcp.CallToolResult
var err error
if protocol == "direct" {
request := createMCPRequest(requestArgs)
result, err = tool.Handler(deps)(ctx, &request)
} else {
server := mcp.NewServer(&mcp.Implementation{Name: "secret-hiding-test", Version: "v1"}, nil)
server.AddReceivingMiddleware(InjectDepsMiddleware(deps))
tool.RegisterFunc(server, deps)
session := connectCommentVisibilityClient(t, server, protocol)
result, err = session.CallTool(ctx, &mcp.CallToolParams{Name: tool.Tool.Name, Arguments: requestArgs})
}
require.NoError(t, err)
require.False(t, result.IsError)
assert.Equal(t, 1, calls, "must make only the requested REST call")
assert.JSONEq(t, mustMarshalJSON(t, ifc.LabelSecurityAlert()), mustMarshalJSON(t, result.Meta["ifc"]))
assert.JSONEq(t, response, getTextResult(t, result).Text)
if protocol != inventory.ProtocolVersionMultiRoundTrip {
assert.Nil(t, result.StructuredContent)
return
}
require.NotNil(t, result.StructuredContent)
structuredJSON := mustMarshalJSON(t, result.StructuredContent)
assert.JSONEq(t, response, structuredJSON)
var structured any
require.NoError(t, json.Unmarshal([]byte(structuredJSON), &structured))
resolved, err := securityOutputSchema(t, tool.Tool.Name).Resolve(nil)
require.NoError(t, err)
require.NoError(t, resolved.Validate(structured))
})
}
})
}
}

func Test_GetSecretScanningAlert(t *testing.T) {
toolDef := GetSecretScanningAlert(translations.NullTranslationHelper)

Expand Down Expand Up @@ -215,6 +316,18 @@ func Test_ListSecretScanningAlerts(t *testing.T) {
expectError: false,
expectedAlerts: []*github.SecretScanningAlert{&openAlert},
},
{
name: "direct caller zero pagination uses defaults",
mockedClient: MockHTTPClientWithHandlers(map[string]http.HandlerFunc{
GetReposSecretScanningAlertsByOwnerByRepo: expectQueryParams(t, map[string]string{"page": "1", "per_page": "30"}).andThen(
mockResponse(t, http.StatusOK, []*github.SecretScanningAlert{&openAlert}),
),
}),
requestArgs: map[string]any{
"owner": "owner", "repo": "repo", "page": 0, "perPage": 0,
},
expectedAlerts: []*github.SecretScanningAlert{&openAlert},
},
{
name: "alerts listing fails",
mockedClient: MockHTTPClientWithHandlers(map[string]http.HandlerFunc{
Expand Down
8 changes: 8 additions & 0 deletions pkg/github/security_outputs.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,13 @@ type GetSecurityAlertInput struct {
AlertNumber int `json:"alertNumber"`
}

type GetSecretScanningAlertInput struct {
Owner string `json:"owner"`
Repo string `json:"repo"`
AlertNumber int `json:"alertNumber"`
HideSecret *bool `json:"hide_secret,omitempty"`
}

type ListCodeScanningAlertsInput struct {
Owner string `json:"owner"`
Repo string `json:"repo"`
Expand All @@ -41,6 +48,7 @@ type ListSecretScanningAlertsInput struct {
State string `json:"state,omitempty"`
SecretType string `json:"secret_type,omitempty"`
Resolution string `json:"resolution,omitempty"`
HideSecret *bool `json:"hide_secret,omitempty"`
Page *int `json:"page,omitempty"`
PerPage *int `json:"perPage,omitempty"`
}
Expand Down
Loading