!+roots
()
| 16 | // !+roots |
| 17 | |
| 18 | func 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 |
nothing calls this directly
no test coverage detected
searching dependent graphs…