parent
84a568bf89
commit
4e9a387d04
2 changed files with 175 additions and 2 deletions
|
|
@ -70,6 +70,7 @@ type LoggingHandlerOptions struct {
|
|||
// The value for the "logger" field of logging notifications.
|
||||
LoggerName string
|
||||
// Limits the rate at which log messages are sent.
|
||||
// Excess messages are dropped.
|
||||
// If zero, there is no rate limiting.
|
||||
MinInterval time.Duration
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,6 +8,8 @@ import (
|
|||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"log/slog"
|
||||
"sync/atomic"
|
||||
|
||||
"github.com/modelcontextprotocol/go-sdk/mcp"
|
||||
)
|
||||
|
|
@ -83,6 +85,67 @@ func Example_prompts() {
|
|||
|
||||
// !-prompts
|
||||
|
||||
// !+logging
|
||||
|
||||
func Example_logging() {
|
||||
ctx := context.Background()
|
||||
|
||||
// Create a server.
|
||||
s := mcp.NewServer(&mcp.Implementation{Name: "server", Version: "v0.0.1"}, nil)
|
||||
|
||||
// Create a client that displays log messages.
|
||||
done := make(chan struct{}) // solely for the example
|
||||
var nmsgs atomic.Int32
|
||||
c := mcp.NewClient(
|
||||
&mcp.Implementation{Name: "client", Version: "v0.0.1"},
|
||||
&mcp.ClientOptions{
|
||||
LoggingMessageHandler: func(_ context.Context, r *mcp.LoggingMessageRequest) {
|
||||
m := r.Params.Data.(map[string]any)
|
||||
fmt.Println(m["msg"], m["value"])
|
||||
if nmsgs.Add(1) == 2 { // number depends on logger calls below
|
||||
close(done)
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
// Connect the server and client.
|
||||
t1, t2 := mcp.NewInMemoryTransports()
|
||||
ss, err := s.Connect(ctx, t1, nil)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
defer ss.Close()
|
||||
cs, err := c.Connect(ctx, t2, nil)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
defer cs.Close()
|
||||
|
||||
// Set the minimum log level to "info".
|
||||
if err := cs.SetLoggingLevel(ctx, &mcp.SetLoggingLevelParams{Level: "info"}); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
// Get a slog.Logger for the server session.
|
||||
logger := slog.New(mcp.NewLoggingHandler(ss, nil))
|
||||
|
||||
// Log some things.
|
||||
logger.Info("info shows up", "value", 1)
|
||||
logger.Debug("debug doesn't show up", "value", 2)
|
||||
logger.Warn("warn shows up", "value", 3)
|
||||
|
||||
// Wait for them to arrive on the client.
|
||||
// In a real application, the log messages would appear asynchronously
|
||||
// while other work was happening.
|
||||
<-done
|
||||
|
||||
// Output:
|
||||
// info shows up 1
|
||||
// warn shows up 3
|
||||
}
|
||||
|
||||
// !-logging
|
||||
|
||||
// !+resources
|
||||
func Example_resources() {
|
||||
ctx := context.Background()
|
||||
|
|
|
|||
Loading…
Reference in a new issue