Debian Codegraph @

debian/go/src/github.com/modelcontextprotocol/go-sdk/mcp/logging.go

raw symbols SCIP
1 // Copyright 2025 The Go MCP SDK Authors. All rights reserved.
2 // Use of this source code is governed by an MIT-style
3 // license that can be found in the LICENSE file.
4
5 package mcp
6
7 import (
8 "bytes"
9 "cmp"
10 "context"
11 "encoding/json"
12 "log/slog"
13 "slices"
14 "sync"
15 "time"
16 )
17
18 // Logging levels.
19 const (
20 LevelDebug = slog.LevelDebug
21 LevelInfo = slog.LevelInfo
22 LevelNotice = (slog.LevelInfo + slog.LevelWarn) / 2
23 LevelWarning = slog.LevelWarn
24 LevelError = slog.LevelError
25 LevelCritical = slog.LevelError + 4
26 LevelAlert = slog.LevelError + 8
27 LevelEmergency = slog.LevelError + 12
28 )
29
30 var slogToMCP = map[slog.Level]LoggingLevel{
31 LevelDebug: "debug",
32 LevelInfo: "info",
33 LevelNotice: "notice",
34 LevelWarning: "warning",
35 LevelError: "error",
36 LevelCritical: "critical",
37 LevelAlert: "alert",
38 LevelEmergency: "emergency",
39 }
40
41 var mcpToSlog = make(map[LoggingLevel]slog.Level)
42
43 func init() {
44 for sl, ml := range slogToMCP {
45 mcpToSlog[ml] = sl
46 }
47 }
48
49 func slogLevelToMCP(sl slog.Level) LoggingLevel {
50 if ml, ok := slogToMCP[sl]; ok {
51 return ml
52 }
53 return "debug" // for lack of a better idea
54 }
55
56 func mcpLevelToSlog(ll LoggingLevel) slog.Level {
57 if sl, ok := mcpToSlog[ll]; ok {
58 return sl
59 }
60 // TODO: is there a better default?
61 return LevelDebug
62 }
63
64 // compareLevels behaves like [cmp.Compare] for [LoggingLevel]s.
65 func compareLevels(l1, l2 LoggingLevel) int {
66 return cmp.Compare(mcpLevelToSlog(l1), mcpLevelToSlog(l2))
67 }
68
69 // LoggingHandlerOptions are options for a LoggingHandler.
70 type LoggingHandlerOptions struct {
71 // The value for the "logger" field of logging notifications.
72 LoggerName string
73 // Limits the rate at which log messages are sent.
74 // Excess messages are dropped.
75 // If zero, there is no rate limiting.
76 MinInterval time.Duration
77 }
78
79 // A LoggingHandler is a [slog.Handler] for MCP.
80 type LoggingHandler struct {
81 opts LoggingHandlerOptions
82 ss *ServerSession
83 // Ensures that the buffer reset is atomic with the write (see Handle).
84 // A pointer so that clones share the mutex. See
85 // https://github.com/golang/example/blob/master/slog-handler-guide/README.md#getting-the-mutex-right.
86 mu *sync.Mutex
87 lastMessageSent time.Time // for rate-limiting
88 buf *bytes.Buffer
89 handler slog.Handler
90 }
91
92 // ensureLogger returns l if non-nil, otherwise a discard logger.
93 func ensureLogger(l *slog.Logger) *slog.Logger {
94 if l != nil {
95 return l
96 }
97 return slog.New(slog.DiscardHandler)
98 }
99
100 // NewLoggingHandler creates a [LoggingHandler] that logs to the given [ServerSession] using a
101 // [slog.JSONHandler].
102 func NewLoggingHandler(ss *ServerSession, opts *LoggingHandlerOptions) *LoggingHandler {
103 var buf bytes.Buffer
104 jsonHandler := slog.NewJSONHandler(&buf, &slog.HandlerOptions{
105 ReplaceAttr: func(_ []string, a slog.Attr) slog.Attr {
106 // Remove level: it appears in LoggingMessageParams.
107 if a.Key == slog.LevelKey {
108 return slog.Attr{}
109 }
110 return a
111 },
112 })
113 lh := &LoggingHandler{
114 ss: ss,
115 mu: new(sync.Mutex),
116 buf: &buf,
117 handler: jsonHandler,
118 }
119 if opts != nil {
120 lh.opts = *opts
121 }
122 return lh
123 }
124
125 // Enabled implements [slog.Handler.Enabled] by comparing level to the [ServerSession]'s level.
126 func (h *LoggingHandler) Enabled(ctx context.Context, level slog.Level) bool {
127 // This is also checked in ServerSession.LoggingMessage, so checking it here
128 // is just an optimization that skips building the JSON.
129 h.ss.mu.Lock()
130 mcpLevel := h.ss.state.LogLevel
131 h.ss.mu.Unlock()
132 return level >= mcpLevelToSlog(mcpLevel)
133 }
134
135 // WithAttrs implements [slog.Handler.WithAttrs].
136 func (h *LoggingHandler) WithAttrs(as []slog.Attr) slog.Handler {
137 h2 := *h
138 h2.handler = h.handler.WithAttrs(as)
139 return &h2
140 }
141
142 // WithGroup implements [slog.Handler.WithGroup].
143 func (h *LoggingHandler) WithGroup(name string) slog.Handler {
144 h2 := *h
145 h2.handler = h.handler.WithGroup(name)
146 return &h2
147 }
148
149 // Handle implements [slog.Handler.Handle] by writing the Record to a JSONHandler,
150 // then calling [ServerSession.LoggingMessage] with the result.
151 func (h *LoggingHandler) Handle(ctx context.Context, r slog.Record) error {
152 err := h.handle(ctx, r)
153 // TODO(jba): find a way to surface the error.
154 // The return value will probably be ignored.
155 return err
156 }
157
158 func (h *LoggingHandler) handle(ctx context.Context, r slog.Record) error {
159 // Observe the rate limit.
160 // TODO(jba): use golang.org/x/time/rate.
161 h.mu.Lock()
162 skip := time.Since(h.lastMessageSent) < h.opts.MinInterval
163 h.mu.Unlock()
164 if skip {
165 return nil
166 }
167
168 var err error
169 var data json.RawMessage
170 // Make the buffer reset atomic with the record write.
171 // We are careful here in the unlikely event that the handler panics.
172 // We don't want to hold the lock for the entire function, because Notify is
173 // an I/O operation.
174 // This can result in out-of-order delivery.
175 func() {
176 h.mu.Lock()
177 defer h.mu.Unlock()
178 h.buf.Reset()
179 err = h.handler.Handle(ctx, r)
180 // Clone the buffer as Bytes() references the internal buffer.
181 data = json.RawMessage(slices.Clone(h.buf.Bytes()))
182 }()
183 if err != nil {
184 return err
185 }
186
187 h.mu.Lock()
188 h.lastMessageSent = time.Now()
189 h.mu.Unlock()
190
191 params := &LoggingMessageParams{
192 Logger: h.opts.LoggerName,
193 Level: slogLevelToMCP(r.Level),
194 Data: data,
195 }
196 // We pass the argument context to Notify, even though slog.Handler.Handle's
197 // documentation says not to.
198 // In this case logging is a service to clients, not a means for debugging the
199 // server, so we want to cancel the log message.
200 return h.ss.Log(ctx, params)
201 }