Skip to content
Open
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
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1413,8 +1413,9 @@ For negotiated supported protocol versions `2026-07-28` or newer, the consolidat
- `branch`: Branch to delete the file from (string, required)
- `message`: Commit message (string, required)
- `owner`: Repository owner (username or organization) (string, required)
- `path`: Path to the file to delete (string, required)
- `path`: Path to the file to delete. A directory path is rejected; pass a single file path. (string, required)
- `repo`: Repository name (string, required)
- `sha`: Blob SHA of the file, as returned by get_file_contents. When set, the delete is rejected if another writer changed the file since it was read. Omit to delete whatever is at the path. (string, optional)

- **delete_repository** - Delete repository
- **OAuth Challenge Scopes**: `delete_repo`, `repo`
Expand Down
6 changes: 5 additions & 1 deletion pkg/github/__toolsnaps__/delete_file.snap
Original file line number Diff line number Diff line change
Expand Up @@ -34,13 +34,17 @@
"x-mcp-header": "owner"
},
"path": {
"description": "Path to the file to delete",
"description": "Path to the file to delete. A directory path is rejected; pass a single file path.",
"type": "string"
},
"repo": {
"description": "Repository name",
"type": "string",
"x-mcp-header": "repo"
},
"sha": {
"description": "Blob SHA of the file, as returned by get_file_contents. When set, the delete is rejected if another writer changed the file since it was read. Omit to delete whatever is at the path.",
"type": "string"
}
},
"required": [
Expand Down
40 changes: 39 additions & 1 deletion pkg/github/repositories.go
Original file line number Diff line number Diff line change
Expand Up @@ -1355,7 +1355,7 @@ func DeleteFile(t translations.TranslationHelperFunc) inventory.ServerTool {
},
"path": {
Type: "string",
Description: "Path to the file to delete",
Description: "Path to the file to delete. A directory path is rejected; pass a single file path.",
},
"message": {
Type: "string",
Expand All @@ -1365,6 +1365,10 @@ func DeleteFile(t translations.TranslationHelperFunc) inventory.ServerTool {
Type: "string",
Description: "Branch to delete the file from",
},
"sha": {
Type: "string",
Description: "Blob SHA of the file, as returned by get_file_contents. When set, the delete is rejected if another writer changed the file since it was read. Omit to delete whatever is at the path.",
},
Comment on lines +1368 to +1371

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 674d55d: pkg/github/toolsnaps/delete_file.snap now records the new path description and the sha property. Regenerating on this Windows checkout rewrites the embedded icon bytes with CRLF, so the icon lines were kept as the Unix LF values to match what CI generates.

},
Required: []string{"owner", "repo", "path", "message", "branch"},
},
Expand Down Expand Up @@ -1427,6 +1431,40 @@ func DeleteFile(t translations.TranslationHelperFunc) inventory.ServerTool {
return ghErrors.NewGitHubAPIStatusErrorResponse(ctx, "failed to get commit", resp, body), nil, nil
}

// Look up what is actually at the path before deleting it. The tree
// entry below deletes a whole subtree when the path is a directory, and
// carries no precondition, so this is the only place to notice that the
// requested blob is missing or that the caller holds a stale sha.
//
// Pin the lookup to the commit the tree is built from: a branch can be
// rewound between this read and the tree creation, and then the check
// would validate a different tree than the deletion modifies.
fileContent, dirContent, contentsResp, err := client.Repositories.GetContents(ctx, owner, repo, path, &github.RepositoryContentGetOptions{Ref: baseCommit.GetSHA()})
if err != nil {
return ghErrors.NewGitHubAPIErrorResponse(ctx,
fmt.Sprintf("failed to get contents of %s on branch %s", path, branch),
contentsResp,
err,
), nil, nil
}
// Close this response independently: the defers above capture resp,
// and a transport failure here can leave contentsResp nil.
if contentsResp != nil {
defer func() { _ = contentsResp.Body.Close() }()
}
if dirContent != nil {
return utils.NewToolResultError(fmt.Sprintf("path %q is a directory; delete_file only removes a single file", path)), nil, nil
}
if fileContent == nil {
return utils.NewToolResultError(fmt.Sprintf("path %q was not found on branch %s", path, branch)), nil, nil
}
if input.Sha != "" && fileContent.GetSHA() != input.Sha {
return utils.NewToolResultError(fmt.Sprintf(
"sha mismatch for %s: requested %s but the file is at %s; re-read the file and retry",
path, input.Sha, fileContent.GetSHA(),
)), nil, nil
}

// Create a tree entry for the file deletion by setting SHA to nil
treeEntries := []*github.TreeEntry{
{
Expand Down
165 changes: 164 additions & 1 deletion pkg/github/repositories_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4299,7 +4299,8 @@ func Test_DeleteFile(t *testing.T) {
assert.Contains(t, schema.Properties, "path")
assert.Contains(t, schema.Properties, "message")
assert.Contains(t, schema.Properties, "branch")
// SHA is no longer required since we're using Git Data API
// sha is an optional precondition; the call still works without it
assert.Contains(t, schema.Properties, "sha")
assert.ElementsMatch(t, schema.Required, []string{"owner", "repo", "path", "message", "branch"})

// Setup mock objects for Git Data API
Expand Down Expand Up @@ -4348,6 +4349,15 @@ func Test_DeleteFile(t *testing.T) {
GetReposGitCommitsByOwnerByRepoByCommitSHA,
mockCommit,
),
// Get contents of the path being deleted
WithRequestMatch(
contentsRoute,
&github.RepositoryContent{
Type: new("file"),
Path: new("docs/example.md"),
SHA: new("blob123"),
},
),
// Create tree
WithRequestMatchHandler(
PostReposGitTreesByOwnerByRepo,
Expand Down Expand Up @@ -4467,6 +4477,159 @@ func Test_DeleteFile(t *testing.T) {
}
}

// contentsRoute matches the contents endpoint for paths with slashes; the plain
// {path} placeholder only matches a single URL segment.
const contentsRoute EndpointPattern = "GET /repos/{owner}/{repo}/contents/{path:.*}"

func Test_DeleteFile_Precondition(t *testing.T) {
serverTool := DeleteFile(translations.NullTranslationHelper)

mockRef := &github.Reference{
Ref: new("refs/heads/main"),
Object: &github.GitObject{SHA: new("abc123")},
}
mockCommit := &github.Commit{
SHA: new("abc123"),
Tree: &github.Tree{SHA: new("def456")},
}

tests := []struct {
name string
contents any
status int
args map[string]any
expectedText string
}{
{
name: "rejects a stale sha",
contents: &github.RepositoryContent{
Type: new("file"),
Path: new("docs/example.md"),
SHA: new("blob-current"),
},
status: http.StatusOK,
args: map[string]any{"owner": "owner", "repo": "repo", "path": "docs/example.md", "message": "Delete", "branch": "main", "sha": "blob-stale"},
expectedText: "sha mismatch",
},
{
name: "rejects a directory path",
contents: []*github.RepositoryContent{
{Type: new("file"), Path: new("docs"), SHA: new("blob-a")},
{Type: new("file"), Path: new("docs/sub"), SHA: new("blob-b")},
},
status: http.StatusOK,
args: map[string]any{"owner": "owner", "repo": "repo", "path": "docs", "message": "Delete", "branch": "main"},
expectedText: "is a directory",
},
{
name: "reports a missing path instead of committing nothing",
contents: map[string]string{"message": "Not Found"},
status: http.StatusNotFound,
args: map[string]any{"owner": "owner", "repo": "repo", "path": "docs/gone.md", "message": "Delete", "branch": "main"},
expectedText: "failed to get contents",
},
}

for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
client := mustNewGHClient(t, NewMockedHTTPClient(
WithRequestMatch(GetReposGitRefByOwnerByRepoByRef, mockRef),
WithRequestMatch(GetReposGitCommitsByOwnerByRepoByCommitSHA, mockCommit),
WithRequestMatchHandler(contentsRoute,
mockResponse(t, tc.status, tc.contents),
),
))
deps := BaseDeps{Client: client}
handler := serverTool.Handler(deps)
request := createMCPRequest(tc.args)

result, err := handler(ContextWithDeps(context.Background(), deps), &request)
require.NoError(t, err)
require.NotNil(t, result)
require.True(t, result.IsError)
assert.Contains(t, getTextResult(t, result).Text, tc.expectedText)
})
}
}

func Test_DeleteFile_AcceptsMatchingSha(t *testing.T) {
serverTool := DeleteFile(translations.NullTranslationHelper)

mockRef := &github.Reference{
Ref: new("refs/heads/main"),
Object: &github.GitObject{SHA: new("abc123")},
}
mockCommit := &github.Commit{
SHA: new("abc123"),
Tree: &github.Tree{SHA: new("def456")},
}
mockTree := &github.Tree{SHA: new("ghi789")}
mockNewCommit := &github.Commit{
SHA: new("jkl012"),
Message: new("Delete example file"),
HTMLURL: new("https://github.com/owner/repo/commit/jkl012"),
}

client := mustNewGHClient(t, NewMockedHTTPClient(
WithRequestMatch(GetReposGitRefByOwnerByRepoByRef, mockRef),
WithRequestMatch(GetReposGitCommitsByOwnerByRepoByCommitSHA, mockCommit),
WithRequestMatch(contentsRoute, &github.RepositoryContent{
Type: new("file"),
Path: new("docs/example.md"),
SHA: new("blob123"),
}),
WithRequestMatchHandler(PostReposGitTreesByOwnerByRepo,
expectRequestBody(t, map[string]any{
"base_tree": "def456",
"tree": []any{
map[string]any{
"path": "docs/example.md",
"mode": "100644",
"type": "blob",
"sha": nil,
},
},
}).andThen(mockResponse(t, http.StatusCreated, mockTree)),
),
WithRequestMatchHandler(PostReposGitCommitsByOwnerByRepo,
expectRequestBody(t, map[string]any{
"message": "Delete example file",
"tree": "ghi789",
"parents": []any{"abc123"},
}).andThen(mockResponse(t, http.StatusCreated, mockNewCommit)),
),
WithRequestMatchHandler(PatchReposGitRefsByOwnerByRepoByRef,
expectRequestBody(t, map[string]any{
"sha": "jkl012",
"force": false,
}).andThen(mockResponse(t, http.StatusOK, &github.Reference{
Ref: new("refs/heads/main"),
Object: &github.GitObject{SHA: new("jkl012")},
})),
),
))

deps := BaseDeps{Client: client}
handler := serverTool.Handler(deps)
request := createMCPRequest(map[string]any{
"owner": "owner",
"repo": "repo",
"path": "docs/example.md",
"message": "Delete example file",
"branch": "main",
"sha": "blob123",
})

result, err := handler(ContextWithDeps(context.Background(), deps), &request)
require.NoError(t, err)
require.False(t, result.IsError)
var response map[string]any
require.NoError(t, json.Unmarshal([]byte(getTextResult(t, result).Text), &response))
commit, ok := response["commit"].(map[string]any)
require.True(t, ok)
assert.Equal(t, "jkl012", commit["sha"])
}

func Test_ListTags(t *testing.T) {
// Verify tool definition once
serverTool := ListTags(translations.NullTranslationHelper)
Expand Down
3 changes: 3 additions & 0 deletions pkg/github/repository_tool_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,9 @@ type DeleteFileInput struct {
Path string `json:"path"`
Message string `json:"message"`
Branch string `json:"branch"`
// Sha, when set, is the blob SHA the caller expects; the delete is rejected
// if the file has changed since it was read.
Sha string `json:"sha,omitempty"`
}

type CreateBranchInput struct {
Expand Down