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

Function Example_logging

mcp/server_example_test.go:90–145  ·  view source on GitHub ↗

!-prompts !+logging

()

Source from the content-addressed store, hash-verified

88// !+logging
89
90func Example_logging() {
91 ctx := context.Background()
92
93 // Create a server.
94 s := mcp.NewServer(&mcp.Implementation{Name: "server", Version: "v0.0.1"}, nil)
95
96 // Create a client that displays log messages.
97 done := make(chan struct{}) // solely for the example
98 var nmsgs atomic.Int32
99 c := mcp.NewClient(
100 &mcp.Implementation{Name: "client", Version: "v0.0.1"},
101 &mcp.ClientOptions{
102 LoggingMessageHandler: func(_ context.Context, r *mcp.LoggingMessageRequest) {
103 m := r.Params.Data.(map[string]any)
104 fmt.Println(m["msg"], m["value"])
105 if nmsgs.Add(1) == 2 { // number depends on logger calls below
106 close(done)
107 }
108 },
109 })
110
111 // Connect the server and client.
112 t1, t2 := mcp.NewInMemoryTransports()
113 ss, err := s.Connect(ctx, t1, nil)
114 if err != nil {
115 log.Fatal(err)
116 }
117 defer ss.Close()
118 cs, err := c.Connect(ctx, t2, nil)
119 if err != nil {
120 log.Fatal(err)
121 }
122 defer cs.Close()
123
124 // Set the minimum log level to "info".
125 if err := cs.SetLoggingLevel(ctx, &mcp.SetLoggingLevelParams{Level: "info"}); err != nil {
126 log.Fatal(err)
127 }
128
129 // Get a slog.Logger for the server session.
130 logger := slog.New(mcp.NewLoggingHandler(ss, nil))
131
132 // Log some things.
133 logger.Info("info shows up", "value", 1)
134 logger.Debug("debug doesn't show up", "value", 2)
135 logger.Warn("warn shows up", "value", 3)
136
137 // Wait for them to arrive on the client.
138 // In a real application, the log messages would appear asynchronously
139 // while other work was happening.
140 <-done
141
142 // Output:
143 // info shows up 1
144 // warn shows up 3
145}
146
147// !-logging

Callers

nothing calls this directly

Calls 8

ConnectMethod · 0.95
ConnectMethod · 0.95
NewServerFunction · 0.92
NewClientFunction · 0.92
NewInMemoryTransportsFunction · 0.92
NewLoggingHandlerFunction · 0.92
SetLoggingLevelMethod · 0.80
CloseMethod · 0.65

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…