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

Function Example_sampling

mcp/client_example_test.go:67–100  ·  view source on GitHub ↗

!-roots !+sampling

()

Source from the content-addressed store, hash-verified

65// !+sampling
66
67func Example_sampling() {
68 ctx := context.Background()
69
70 // Create a client with a sampling handler.
71 c := mcp.NewClient(&mcp.Implementation{Name: "client", Version: "v0.0.1"}, &mcp.ClientOptions{
72 CreateMessageHandler: func(_ context.Context, req *mcp.CreateMessageRequest) (*mcp.CreateMessageResult, error) {
73 return &mcp.CreateMessageResult{
74 Content: &mcp.TextContent{
75 Text: "would have created a message",
76 },
77 }, nil
78 },
79 })
80
81 // Connect the server and client...
82 ct, st := mcp.NewInMemoryTransports()
83 s := mcp.NewServer(&mcp.Implementation{Name: "server", Version: "v0.0.1"}, nil)
84 session, err := s.Connect(ctx, st, nil)
85 if err != nil {
86 log.Fatal(err)
87 }
88 defer session.Close()
89
90 if _, err := c.Connect(ctx, ct, nil); err != nil {
91 log.Fatal(err)
92 }
93
94 msg, err := session.CreateMessage(ctx, &mcp.CreateMessageParams{})
95 if err != nil {
96 log.Fatal(err)
97 }
98 fmt.Println(msg.Content.(*mcp.TextContent).Text)
99 // Output: would have created a message
100}
101
102// !-sampling
103

Callers

nothing calls this directly

Calls 7

ConnectMethod · 0.95
ConnectMethod · 0.95
NewClientFunction · 0.92
NewInMemoryTransportsFunction · 0.92
NewServerFunction · 0.92
CreateMessageMethod · 0.80
CloseMethod · 0.65

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…