@@ -13,11 +13,11 @@ import (
1313 "net/url"
1414 "os"
1515 "path/filepath"
16- "regexp"
1716 "strings"
1817
1918 "github.com/modelcontextprotocol/go-sdk/internal/jsonrpc2"
2019 "github.com/modelcontextprotocol/go-sdk/internal/util"
20+ "github.com/yosida95/uritemplate/v3"
2121)
2222
2323// A serverResource associates a Resource with its handler.
@@ -155,67 +155,10 @@ func fileRoot(root *Root) (_ string, err error) {
155155}
156156
157157// Matches reports whether the receiver's uri template matches the uri.
158- // TODO: use "github.com/yosida95/uritemplate/v3"
159158func (sr * serverResourceTemplate ) Matches (uri string ) bool {
160- re , err := uriTemplateToRegexp (sr .resourceTemplate .URITemplate )
159+ tmpl , err := uritemplate . New (sr .resourceTemplate .URITemplate )
161160 if err != nil {
162161 return false
163162 }
164- return re .MatchString (uri )
165- }
166-
167- func uriTemplateToRegexp (uriTemplate string ) (* regexp.Regexp , error ) {
168- pat := uriTemplate
169- var b strings.Builder
170- b .WriteByte ('^' )
171- seen := map [string ]bool {}
172- for len (pat ) > 0 {
173- literal , rest , ok := strings .Cut (pat , "{" )
174- b .WriteString (regexp .QuoteMeta (literal ))
175- if ! ok {
176- break
177- }
178- expr , rest , ok := strings .Cut (rest , "}" )
179- if ! ok {
180- return nil , errors .New ("missing '}'" )
181- }
182- pat = rest
183- if strings .ContainsRune (expr , ',' ) {
184- return nil , errors .New ("can't handle commas in expressions" )
185- }
186- if strings .ContainsRune (expr , ':' ) {
187- return nil , errors .New ("can't handle prefix modifiers in expressions" )
188- }
189- if len (expr ) > 0 && expr [len (expr )- 1 ] == '*' {
190- return nil , errors .New ("can't handle explode modifiers in expressions" )
191- }
192-
193- // These sets of valid characters aren't accurate.
194- // See https://datatracker.ietf.org/doc/html/rfc6570.
195- var re , name string
196- first := byte (0 )
197- if len (expr ) > 0 {
198- first = expr [0 ]
199- }
200- switch first {
201- default :
202- // {var} doesn't match slashes. (It should also fail to match other characters,
203- // but this simplified implementation doesn't handle that.)
204- re = `[^/]*`
205- name = expr
206- case '+' :
207- // {+var} matches anything, even slashes
208- re = `.*`
209- name = expr [1 :]
210- case '#' , '.' , '/' , ';' , '?' , '&' :
211- return nil , fmt .Errorf ("prefix character %c unsupported" , first )
212- }
213- if seen [name ] {
214- return nil , fmt .Errorf ("can't handle duplicate name %q" , name )
215- }
216- seen [name ] = true
217- b .WriteString (re )
218- }
219- b .WriteByte ('$' )
220- return regexp .Compile (b .String ())
163+ return tmpl .Regexp ().MatchString (uri )
221164}
0 commit comments