MCPcopy Create free account
hub / github.com/modelcontextprotocol/go-sdk / Example_roots

Function Example_roots

mcp/client_example_test.go:18–61  ·  view source on GitHub ↗

!+roots

()

Source from the content-addressed store, hash-verified

16// !+roots
17
18func Example_roots() {
19 ctx := context.Background()
20
21 // Create a client with a single root.
22 c := mcp.NewClient(&mcp.Implementation{Name: "client", Version: "v0.0.1"}, nil)
23 c.AddRoots(&mcp.Root{URI: "file://a"})
24
25 // Now create a server with a handler to receive notifications about roots.
26 rootsChanged := make(chan struct{})
27 handleRootsChanged := func(ctx context.Context, req *mcp.RootsListChangedRequest) {
28 rootList, err := req.Session.ListRoots(ctx, nil)
29 if err != nil {
30 log.Fatal(err)
31 }
32 var roots []string
33 for _, root := range rootList.Roots {
34 roots = append(roots, root.URI)
35 }
36 fmt.Println(roots)
37 close(rootsChanged)
38 }
39 s := mcp.NewServer(&mcp.Implementation{Name: "server", Version: "v0.0.1"}, &mcp.ServerOptions{
40 RootsListChangedHandler: handleRootsChanged,
41 })
42
43 // Connect the server and client...
44 t1, t2 := mcp.NewInMemoryTransports()
45 serverSession, err := s.Connect(ctx, t1, nil)
46 if err != nil {
47 log.Fatal(err)
48 }
49 defer serverSession.Close()
50
51 clientSession, err := c.Connect(ctx, t2, nil)
52 if err != nil {
53 log.Fatal(err)
54 }
55 defer clientSession.Close()
56
57 // ...and add a root. The server is notified about the change.
58 c.AddRoots(&mcp.Root{URI: "file://b"})
59 <-rootsChanged
60 // Output: [file://a file://b]
61}
62
63// !-roots
64

Callers

nothing calls this directly

Calls 8

AddRootsMethod · 0.95
ConnectMethod · 0.95
ConnectMethod · 0.95
NewClientFunction · 0.92
NewServerFunction · 0.92
NewInMemoryTransportsFunction · 0.92
ListRootsMethod · 0.80
CloseMethod · 0.65

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…