go-sdk/mcp/resource_go124.go
Jonathan Amsterdam 8361df724d internal/mcp: add the FileResourceHandler method
Provide secure reading of files on the local filesystem.

There are subtleties in path manipulation on Windows that I don't fully
understand, so I defer that work for now.

Change-Id: Ic11f4617dde4ac0b31ccd5b0a772bb2f56db026f
Reviewed-on: https://go-review.googlesource.com/c/tools/+/673196
Reviewed-by: Robert Findley <rfindley@google.com>
Reviewed-by: Sam Thanawalla <samthanawalla@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2025-05-19 11:15:23 -07:00

29 lines
643 B
Go

// Copyright 2025 The Go MCP SDK Authors. All rights reserved.
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
//go:build go1.24
package mcp
import (
"errors"
"os"
)
// withFile calls f on the file at join(dir, rel),
// protecting against path traversal attacks.
func withFile(dir, rel string, f func(*os.File) error) (err error) {
r, err := os.OpenRoot(dir)
if err != nil {
return err
}
defer r.Close()
file, err := r.Open(rel)
if err != nil {
return err
}
// Record error, in case f writes.
defer func() { err = errors.Join(err, file.Close()) }()
return f(file)
}