Skip to content

Commit 5a3c558

Browse files
dylanpulverSamMorrowDrumsCopilot
authored
fix(repos): give create_or_update_file callers a SHA they can actually get (#3131)
* fix(repos): give create_or_update_file callers a SHA they can actually get The create_or_update_file tool description and both of its SHA errors told the caller to run `git rev-parse <branch>:<path>`. The caller is an MCP client talking to the GitHub API, and the same description tells it not to use this tool for local file operations, so it has no working tree to run that command against. Point the description at get_file_contents instead, which returns the blob SHA over the API. In the already-exists error the server has just fetched the file, so return that SHA directly rather than asking for a round trip. The stale-SHA error already interpolates the current SHA, so it only needed the impossible instruction removed. * fix(repos): stop disclosing the blob SHA when no sha was supplied The already-exists path is reached only when the caller sent no sha, so it has not read the file. Returning the current blob SHA there let it overwrite content it never saw on the next call, which is the race the SHA gate exists to prevent. Send the caller to get_file_contents for the path and ref instead, so obtaining the SHA still requires reading the file. The stale-SHA path is unaffected: the caller did supply a sha, and that message already reported the current SHA before this change. Only its recovery step moved off git rev-parse, and it is now imperative rather than conditional, since a stale SHA means the file definitely changed. Assert the already-exists error does not contain the blob SHA so the gate cannot be loosened again without a test failing. * fix(repos): make SHA recovery guidance actionable Map create_or_update_file branch arguments to get_file_contents ref arguments, identify where the requested path SHA is returned, and cover symlink, branch, and API error behavior. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --------- Co-authored-by: Dylan Pulver <dylanpulver@users.noreply.github.com> Co-authored-by: Sam Morrow <info@sam-morrow.com> Co-authored-by: Sam Morrow <sammorrowdrums@github.com> Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
1 parent febc329 commit 5a3c558

5 files changed

Lines changed: 109 additions & 24 deletions

File tree

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1272,7 +1272,7 @@ The following sets of tools are available:
12721272
- `owner`: Repository owner (username or organization) (string, required)
12731273
- `path`: Path where to create/update the file (string, required)
12741274
- `repo`: Repository name (string, required)
1275-
- `sha`: The blob SHA of the file being replaced. Required if the file already exists. (string, optional)
1275+
- `sha`: The blob SHA of the file being replaced. Required if the file already exists. Retrieve it with get_file_contents using the same owner, repo, and path, with ref set to this tool's branch value. (string, optional)
12761276

12771277
- **create_repository** - Create repository
12781278
- **OAuth Challenge Scopes**: `repo`

‎docs/feature-flags.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -357,7 +357,7 @@ runtime behavior (such as output formatting) won't appear here.
357357
### `thread_resolution_reason`
358358

359359
- **pull_request_review_write** - Write operations (create, submit, delete) on pull request reviews
360-
- **Required OAuth Scopes**: `repo`
360+
- **OAuth Challenge Scopes**: `repo`
361361
- `body`: Review comment text (string, optional)
362362
- `commitID`: SHA of commit to review (string, optional)
363363
- `event`: Review action to perform. (string, optional)

‎pkg/github/__toolsnaps__/create_or_update_file.snap‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
"readOnlyHint": false,
55
"title": "Create or update file"
66
},
7-
"description": "Create or update a single file in a GitHub repository. \nIf updating, you should provide the SHA of the file you want to update. Use this tool to create or update a file in a GitHub repository remotely; do not use it for local file operations.\n\nIn order to obtain the SHA of original file version before updating, use the following git command:\ngit rev-parse \u003cbranch\u003e:\u003cpath to file\u003e\n\nSHA MUST be provided for existing file updates.\n",
7+
"description": "Create or update a single file in a GitHub repository. \nIf updating, you should provide the SHA of the file you want to update. Use this tool to create or update a file in a GitHub repository remotely; do not use it for local file operations.\n\nTo obtain the current blob SHA before updating, call the get_file_contents tool with the same owner, repo, and path, and set its ref parameter to this tool's branch value. The first text result reports the blob SHA for the requested path.\n\nSHA MUST be provided for existing file updates.\n",
88
"inputSchema": {
99
"properties": {
1010
"allow_symlink_write": {
@@ -37,7 +37,7 @@
3737
"type": "string"
3838
},
3939
"sha": {
40-
"description": "The blob SHA of the file being replaced. Required if the file already exists.",
40+
"description": "The blob SHA of the file being replaced. Required if the file already exists. Retrieve it with get_file_contents using the same owner, repo, and path, with ref set to this tool's branch value.",
4141
"type": "string"
4242
}
4343
},

‎pkg/github/repositories.go‎

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -412,8 +412,7 @@ func CreateOrUpdateFile(t translations.TranslationHelperFunc) inventory.ServerTo
412412
Description: t("TOOL_CREATE_OR_UPDATE_FILE_DESCRIPTION", `Create or update a single file in a GitHub repository.
413413
If updating, you should provide the SHA of the file you want to update. Use this tool to create or update a file in a GitHub repository remotely; do not use it for local file operations.
414414
415-
In order to obtain the SHA of original file version before updating, use the following git command:
416-
git rev-parse <branch>:<path to file>
415+
To obtain the current blob SHA before updating, call the get_file_contents tool with the same owner, repo, and path, and set its ref parameter to this tool's branch value. The first text result reports the blob SHA for the requested path.
417416
418417
SHA MUST be provided for existing file updates.
419418
`),
@@ -450,7 +449,7 @@ SHA MUST be provided for existing file updates.
450449
},
451450
"sha": {
452451
Type: "string",
453-
Description: "The blob SHA of the file being replaced. Required if the file already exists.",
452+
Description: "The blob SHA of the file being replaced. Required if the file already exists. Retrieve it with get_file_contents using the same owner, repo, and path, with ref set to this tool's branch value.",
454453
},
455454
"allow_symlink_write": {
456455
Type: "boolean",
@@ -551,8 +550,10 @@ SHA MUST be provided for existing file updates.
551550
if currentSHA != sha {
552551
return utils.NewToolResultError(fmt.Sprintf(
553552
"SHA mismatch: provided SHA %s is stale. Current file SHA is %s. "+
554-
"Pull the latest changes and use git rev-parse %s:%s to get the current SHA.",
555-
sha, currentSHA, branch, path)), nil, nil
553+
"The file changed since you read it. Call get_file_contents with owner=%q, repo=%q, path=%q, and ref=%q; "+
554+
"its first text result reports the blob SHA for the requested path. "+
555+
"Rebuild your content against what it returns, and retry with the sha parameter set to the SHA that call reports.",
556+
sha, currentSHA, owner, repo, path, branch)), nil, nil
556557
}
557558
if !allowSymlinkWrite {
558559
if existingFile.GetType() == "symlink" {
@@ -596,8 +597,10 @@ SHA MUST be provided for existing file updates.
596597
// File exists but no SHA was provided - reject to prevent blind overwrites
597598
return utils.NewToolResultError(fmt.Sprintf(
598599
"File already exists at %s. You must provide the current file's SHA when updating. "+
599-
"Use git rev-parse %s:%s to get the blob SHA, then retry with the sha parameter.",
600-
path, branch, path)), nil, nil
600+
"Call get_file_contents with owner=%q, repo=%q, path=%q, and ref=%q to read the file you are about to overwrite; "+
601+
"its first text result reports the blob SHA for the requested path. "+
602+
"Then retry with the sha parameter set to the blob SHA that call reports.",
603+
path, owner, repo, path, branch)), nil, nil
601604
}
602605
// If file not found, no previous SHA needed (new file creation)
603606
}

‎pkg/github/repositories_test.go‎

Lines changed: 95 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -170,6 +170,7 @@ func Test_GetFileContents(t *testing.T) {
170170
Text: "# Test Repository\n\nThis is a test repository.",
171171
MIMEType: "text/plain; charset=utf-8",
172172
},
173+
expectedMsg: "SHA: " + gitBlobSHA(mockRawContent),
173174
},
174175
{
175176
name: "successful binary file content fetch (PNG)",
@@ -625,6 +626,7 @@ func Test_GetFileContents_SymlinkDisclosure(t *testing.T) {
625626
metadata := repositoryPathMetadataFromResult(t, result)
626627
assert.Equal(t, "symlink", metadata.Type)
627628
assert.Equal(t, "docs/link", metadata.Path)
629+
assert.Equal(t, linkSHA, metadata.SHA)
628630
assert.Equal(t, target, metadata.Target)
629631
assert.Equal(t, "target/"+tc.name, metadata.ResolvedTargetPath)
630632
assert.Equal(t, "dereferenced_target", metadata.Content)
@@ -649,6 +651,7 @@ func Test_GetFileContents_SymlinkDisclosure(t *testing.T) {
649651
require.False(t, result.IsError)
650652
assert.Equal(t, 1, requests)
651653
metadata := repositoryPathMetadataFromResult(t, result)
654+
assert.Equal(t, gitBlobSHA([]byte(target)), metadata.SHA)
652655
assert.Equal(t, target, metadata.Target)
653656
assert.Empty(t, metadata.ResolvedTargetPath)
654657
assert.Equal(t, "not_returned", metadata.Content)
@@ -2057,6 +2060,9 @@ func Test_CreateOrUpdateFile(t *testing.T) {
20572060

20582061
assert.Equal(t, "create_or_update_file", tool.Name)
20592062
assert.NotEmpty(t, tool.Description)
2063+
assert.NotContains(t, tool.Description, "git rev-parse")
2064+
assert.Contains(t, tool.Description, "get_file_contents")
2065+
assert.Contains(t, tool.Description, "set its ref parameter to this tool's branch value")
20602066
assert.Contains(t, schema.Properties, "owner")
20612067
assert.Contains(t, schema.Properties, "repo")
20622068
assert.Contains(t, schema.Properties, "path")
@@ -2065,6 +2071,7 @@ func Test_CreateOrUpdateFile(t *testing.T) {
20652071
assert.Contains(t, schema.Properties, "branch")
20662072
assert.Contains(t, schema.Properties, "sha")
20672073
assert.Contains(t, schema.Properties, "allow_symlink_write")
2074+
assert.Contains(t, schema.Properties["sha"].Description, "with ref set to this tool's branch value")
20682075
assert.ElementsMatch(t, schema.Required, []string{"owner", "repo", "path", "content", "message", "branch"})
20692076

20702077
// Setup mock file content response
@@ -2135,6 +2142,7 @@ func Test_CreateOrUpdateFile(t *testing.T) {
21352142
expectedContent *github.RepositoryContentResponse
21362143
expectedErrMsg string
21372144
expectedErrMsgs []string
2145+
unexpectedErrMsgs []string
21382146
expectedRequestCount int
21392147
}{
21402148
{
@@ -2449,26 +2457,60 @@ func Test_CreateOrUpdateFile(t *testing.T) {
24492457
{
24502458
name: "sha validation - stale sha detected",
24512459
mockedClient: MockHTTPClientWithHandlers(map[string]http.HandlerFunc{
2452-
"GET /repos/owner/repo/contents/docs/example.md": mockResponse(t, http.StatusOK, &github.RepositoryContent{
2453-
SHA: github.Ptr("newsha999888"),
2454-
Type: github.Ptr("file"),
2460+
"GET /repos/owner/repo/contents/docs/example.md": expectQueryParams(t, map[string]string{
2461+
"ref": "main",
2462+
}).andThen(mockResponse(t, http.StatusOK, &github.RepositoryContent{
2463+
SHA: github.Ptr(symlinkSHA),
2464+
Type: github.Ptr("symlink"),
2465+
Target: github.Ptr(string(symlinkTarget)),
2466+
})),
2467+
"GET /repos/{owner}/{repo}/contents/{path:.*}": expectQueryParams(t, map[string]string{
2468+
"ref": "main",
2469+
}).andThen(mockResponse(t, http.StatusOK, &github.RepositoryContent{
2470+
SHA: github.Ptr(symlinkSHA),
2471+
Type: github.Ptr("symlink"),
2472+
Target: github.Ptr(string(symlinkTarget)),
2473+
})),
2474+
}),
2475+
requestArgs: map[string]any{
2476+
"owner": "owner",
2477+
"repo": "repo",
2478+
"path": "docs/example.md",
2479+
"content": "# Updated Example\n\nThis file has been updated.",
2480+
"message": "Update example file",
2481+
"branch": "main",
2482+
"sha": "oldsha123456",
2483+
},
2484+
expectError: true,
2485+
expectedErrMsgs: []string{
2486+
"SHA mismatch: provided SHA oldsha123456 is stale. Current file SHA is " + symlinkSHA,
2487+
`Call get_file_contents with owner="owner", repo="repo", path="docs/example.md", and ref="main"`,
2488+
"its first text result reports the blob SHA for the requested path",
2489+
"retry with the sha parameter set to the SHA that call reports",
2490+
},
2491+
expectedRequestCount: 1,
2492+
},
2493+
{
2494+
name: "sha validation - api error is surfaced",
2495+
mockedClient: MockHTTPClientWithHandlers(map[string]http.HandlerFunc{
2496+
"GET /repos/owner/repo/contents/docs/example.md": mockResponse(t, http.StatusForbidden, map[string]any{
2497+
"message": "Resource not accessible",
24552498
}),
2456-
"GET /repos/{owner}/{repo}/contents/{path:.*}": mockResponse(t, http.StatusOK, &github.RepositoryContent{
2457-
SHA: github.Ptr("newsha999888"),
2458-
Type: github.Ptr("file"),
2499+
"GET /repos/{owner}/{repo}/contents/{path:.*}": mockResponse(t, http.StatusForbidden, map[string]any{
2500+
"message": "Resource not accessible",
24592501
}),
24602502
}),
24612503
requestArgs: map[string]any{
24622504
"owner": "owner",
24632505
"repo": "repo",
24642506
"path": "docs/example.md",
2465-
"content": "# Updated Example\n\nThis file has been updated.",
2507+
"content": "updated",
24662508
"message": "Update example file",
24672509
"branch": "main",
24682510
"sha": "oldsha123456",
24692511
},
24702512
expectError: true,
2471-
expectedErrMsg: "SHA mismatch: provided SHA oldsha123456 is stale. Current file SHA is newsha999888",
2513+
expectedErrMsg: "failed to verify file SHA",
24722514
expectedRequestCount: 1,
24732515
},
24742516
{
@@ -2513,25 +2555,59 @@ func Test_CreateOrUpdateFile(t *testing.T) {
25132555
{
25142556
name: "no sha provided - file exists, rejects update",
25152557
mockedClient: MockHTTPClientWithHandlers(map[string]http.HandlerFunc{
2516-
"GET /repos/owner/repo/contents/docs/example.md": mockResponse(t, http.StatusOK, &github.RepositoryContent{
2558+
"GET /repos/owner/repo/contents/docs/example.md": expectQueryParams(t, map[string]string{
2559+
"ref": "release/#candidate",
2560+
}).andThen(mockResponse(t, http.StatusOK, &github.RepositoryContent{
25172561
SHA: github.Ptr("existing123"),
25182562
Type: github.Ptr("file"),
2519-
}),
2520-
"GET /repos/{owner}/{repo}/contents/{path:.*}": mockResponse(t, http.StatusOK, &github.RepositoryContent{
2563+
})),
2564+
"GET /repos/{owner}/{repo}/contents/{path:.*}": expectQueryParams(t, map[string]string{
2565+
"ref": "release/#candidate",
2566+
}).andThen(mockResponse(t, http.StatusOK, &github.RepositoryContent{
25212567
SHA: github.Ptr("existing123"),
25222568
Type: github.Ptr("file"),
2523-
}),
2569+
})),
25242570
}),
25252571
requestArgs: map[string]any{
25262572
"owner": "owner",
25272573
"repo": "repo",
25282574
"path": "docs/example.md",
25292575
"content": "# Updated\n\nUpdated without SHA.",
25302576
"message": "Update without SHA",
2577+
"branch": "release/#candidate",
2578+
},
2579+
expectError: true,
2580+
expectedErrMsgs: []string{
2581+
"File already exists at docs/example.md",
2582+
`Call get_file_contents with owner="owner", repo="repo", path="docs/example.md", and ref="release/#candidate"`,
2583+
"its first text result reports the blob SHA for the requested path",
2584+
"retry with the sha parameter set to the blob SHA that call reports",
2585+
},
2586+
// A caller that never supplied a SHA has not read this file, so the
2587+
// error must not hand it one to overwrite with.
2588+
unexpectedErrMsgs: []string{"existing123"},
2589+
expectedRequestCount: 1,
2590+
},
2591+
{
2592+
name: "no sha provided - api error is surfaced",
2593+
mockedClient: MockHTTPClientWithHandlers(map[string]http.HandlerFunc{
2594+
"GET /repos/owner/repo/contents/docs/example.md": mockResponse(t, http.StatusInternalServerError, map[string]any{
2595+
"message": "Internal Server Error",
2596+
}),
2597+
"GET /repos/{owner}/{repo}/contents/{path:.*}": mockResponse(t, http.StatusInternalServerError, map[string]any{
2598+
"message": "Internal Server Error",
2599+
}),
2600+
}),
2601+
requestArgs: map[string]any{
2602+
"owner": "owner",
2603+
"repo": "repo",
2604+
"path": "docs/example.md",
2605+
"content": "updated",
2606+
"message": "Update example file",
25312607
"branch": "main",
25322608
},
25332609
expectError: true,
2534-
expectedErrMsg: "File already exists at docs/example.md",
2610+
expectedErrMsg: "failed to check if file exists",
25352611
expectedRequestCount: 1,
25362612
},
25372613
{
@@ -2606,6 +2682,12 @@ func Test_CreateOrUpdateFile(t *testing.T) {
26062682
for _, expectedErrMsg := range tc.expectedErrMsgs {
26072683
assert.Contains(t, errorText.String(), expectedErrMsg)
26082684
}
2685+
for _, unexpectedErrMsg := range tc.unexpectedErrMsgs {
2686+
assert.NotContains(t, errorText.String(), unexpectedErrMsg)
2687+
}
2688+
// The caller of this tool works over the API and has no working
2689+
// tree, so errors must never ask it to run a local git command.
2690+
assert.NotContains(t, errorText.String(), "git rev-parse")
26092691
return
26102692
}
26112693

0 commit comments

Comments
 (0)