Debian Codegraph @

debian/go/src/github.com/modelcontextprotocol/go-sdk/mcp/resource.go

raw symbols SCIP
1 // Copyright 2025 The Go MCP SDK Authors. All rights reserved.
2 // Use of this source code is governed by an MIT-style
3 // license that can be found in the LICENSE file.
4
5 package mcp
6
7 import (
8 "context"
9 "encoding/json"
10 "errors"
11 "fmt"
12 "io"
13 "net/url"
14 "os"
15 "path/filepath"
16 "strings"
17
18 "github.com/modelcontextprotocol/go-sdk/internal/util"
19 "github.com/modelcontextprotocol/go-sdk/jsonrpc"
20 "github.com/yosida95/uritemplate/v3"
21 )
22
23 // A serverResource associates a Resource with its handler.
24 type serverResource struct {
25 resource *Resource
26 handler ResourceHandler
27 }
28
29 // A serverResourceTemplate associates a ResourceTemplate with its handler.
30 type serverResourceTemplate struct {
31 resourceTemplate *ResourceTemplate
32 handler ResourceHandler
33 }
34
35 // A ResourceHandler is a function that reads a resource.
36 // It will be called when the client calls [ClientSession.ReadResource].
37 // If it cannot find the resource, it should return the result of calling [ResourceNotFoundError].
38 type ResourceHandler func(context.Context, *ReadResourceRequest) (*ReadResourceResult, error)
39
40 // ResourceNotFoundError returns an error indicating that a resource being read could
41 // not be found.
42 func ResourceNotFoundError(uri string) error {
43 return &jsonrpc.Error{
44 Code: CodeResourceNotFound,
45 Message: "Resource not found",
46 Data: json.RawMessage(fmt.Sprintf(`{"uri":%q}`, uri)),
47 }
48 }
49
50 // readFileResource reads from the filesystem at a URI relative to dirFilepath, respecting
51 // the roots.
52 // dirFilepath and rootFilepaths are absolute filesystem paths.
53 func readFileResource(rawURI, dirFilepath string, rootFilepaths []string) ([]byte, error) {
54 uriFilepath, err := computeURIFilepath(rawURI, dirFilepath, rootFilepaths)
55 if err != nil {
56 return nil, err
57 }
58
59 var data []byte
60 err = withFile(dirFilepath, uriFilepath, func(f *os.File) error {
61 var err error
62 data, err = io.ReadAll(f)
63 return err
64 })
65 if os.IsNotExist(err) {
66 err = ResourceNotFoundError(rawURI)
67 }
68 return data, err
69 }
70
71 // computeURIFilepath returns a path relative to dirFilepath.
72 // The dirFilepath and rootFilepaths are absolute file paths.
73 func computeURIFilepath(rawURI, dirFilepath string, rootFilepaths []string) (string, error) {
74 // We use "file path" to mean a filesystem path.
75 uri, err := url.Parse(rawURI)
76 if err != nil {
77 return "", err
78 }
79 if uri.Scheme != "file" {
80 return "", fmt.Errorf("URI is not a file: %s", uri)
81 }
82 if uri.Path == "" {
83 // A more specific error than the one below, to catch the
84 // common mistake "file://foo".
85 return "", errors.New("empty path")
86 }
87 // The URI's path is interpreted relative to dirFilepath, and in the local filesystem.
88 // It must not try to escape its directory.
89 uriFilepathRel, err := filepath.Localize(strings.TrimPrefix(uri.Path, "/"))
90 if err != nil {
91 return "", fmt.Errorf("%q cannot be localized: %w", uriFilepathRel, err)
92 }
93
94 // Check roots, if there are any.
95 if len(rootFilepaths) > 0 {
96 // To check against the roots, we need an absolute file path, not relative to the directory.
97 // uriFilepath is local, so the joined path is under dirFilepath.
98 uriFilepathAbs := filepath.Join(dirFilepath, uriFilepathRel)
99 rootOK := false
100 // Check that the requested file path is under some root.
101 // Since both paths are absolute, that's equivalent to filepath.Rel constructing
102 // a local path.
103 for _, rootFilepathAbs := range rootFilepaths {
104 if rel, err := filepath.Rel(rootFilepathAbs, uriFilepathAbs); err == nil && filepath.IsLocal(rel) {
105 rootOK = true
106 break
107 }
108 }
109 if !rootOK {
110 return "", fmt.Errorf("URI path %q is not under any root", uriFilepathAbs)
111 }
112 }
113 return uriFilepathRel, nil
114 }
115
116 // withFile calls f on the file at join(dir, rel),
117 // protecting against path traversal attacks.
118 func withFile(dir, rel string, f func(*os.File) error) (err error) {
119 r, err := os.OpenRoot(dir)
120 if err != nil {
121 return err
122 }
123 defer r.Close()
124 file, err := r.Open(rel)
125 if err != nil {
126 return err
127 }
128 // Record error, in case f writes.
129 defer func() { err = errors.Join(err, file.Close()) }()
130 return f(file)
131 }
132
133 // fileRoots transforms the Roots obtained from the client into absolute paths on
134 // the local filesystem.
135 // TODO(jba): expose this functionality to user ResourceHandlers,
136 // so they don't have to repeat it.
137 func fileRoots(rawRoots []*Root) ([]string, error) {
138 var fileRoots []string
139 for _, r := range rawRoots {
140 fr, err := fileRoot(r)
141 if err != nil {
142 return nil, err
143 }
144 fileRoots = append(fileRoots, fr)
145 }
146 return fileRoots, nil
147 }
148
149 // fileRoot returns the absolute path for Root.
150 func fileRoot(root *Root) (_ string, err error) {
151 defer util.Wrapf(&err, "root %q", root.URI)
152
153 // Convert to absolute file path.
154 rurl, err := url.Parse(root.URI)
155 if err != nil {
156 return "", err
157 }
158 if rurl.Scheme != "file" {
159 return "", errors.New("not a file URI")
160 }
161 if rurl.Path == "" {
162 // A more specific error than the one below, to catch the
163 // common mistake "file://foo".
164 return "", errors.New("empty path")
165 }
166 // We don't want Localize here: we want an absolute path, which is not local.
167 fileRoot := filepath.Clean(filepath.FromSlash(rurl.Path))
168 if !filepath.IsAbs(fileRoot) {
169 return "", errors.New("not an absolute path")
170 }
171 return fileRoot, nil
172 }
173
174 // Matches reports whether the receiver's uri template matches the uri.
175 func (sr *serverResourceTemplate) Matches(uri string) bool {
176 tmpl, err := uritemplate.New(sr.resourceTemplate.URITemplate)
177 if err != nil {
178 return false
179 }
180 return tmpl.Regexp().MatchString(uri)
181 }