Debian Codegraph @

debian/go/src/github.com/modelcontextprotocol/go-sdk/mcp/event.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 // This file is for SSE events.
6 // See https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events.
7
8 package mcp
9
10 import (
11 "bufio"
12 "bytes"
13 "context"
14 "errors"
15 "fmt"
16 "io"
17 "iter"
18 "maps"
19 "net/http"
20 "slices"
21 "strings"
22 "sync"
23 )
24
25 // If true, MemoryEventStore will do frequent validation to check invariants, slowing it down.
26 // Enable for debugging.
27 const validateMemoryEventStore = false
28
29 // An Event is a server-sent event.
30 // See https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#fields.
31 type Event struct {
32 Name string // the "event" field
33 ID string // the "id" field
34 Data []byte // the "data" field
35 Retry string // the "retry" field
36 }
37
38 // Empty reports whether the Event is empty.
39 func (e Event) Empty() bool {
40 return e.Name == "" && e.ID == "" && len(e.Data) == 0 && e.Retry == ""
41 }
42
43 // writeEvent writes the event to w, and flushes.
44 func writeEvent(w http.ResponseWriter, evt Event) (int, error) {
45 var b bytes.Buffer
46 if evt.Name != "" {
47 fmt.Fprintf(&b, "event: %s\n", evt.Name)
48 }
49 if evt.ID != "" {
50 fmt.Fprintf(&b, "id: %s\n", evt.ID)
51 }
52 if evt.Retry != "" {
53 fmt.Fprintf(&b, "retry: %s\n", evt.Retry)
54 }
55 fmt.Fprintf(&b, "data: %s\n\n", string(evt.Data))
56 n, err := w.Write(b.Bytes())
57 rc := http.NewResponseController(w)
58 // Ignore returned error as flushing is best-effort.
59 _ = rc.Flush()
60 return n, err
61 }
62
63 // scanEvents iterates SSE events in the given scanner. The iterated error is
64 // terminal: if encountered, the stream is corrupt or broken and should no
65 // longer be used.
66 //
67 // TODO(rfindley): consider a different API here that makes failure modes more
68 // apparent.
69 func scanEvents(r io.Reader) iter.Seq2[Event, error] {
70 reader := bufio.NewReader(r)
71
72 // TODO: investigate proper behavior when events are out of order, or have
73 // non-standard names.
74 var (
75 eventKey = []byte("event")
76 idKey = []byte("id")
77 dataKey = []byte("data")
78 retryKey = []byte("retry")
79 )
80
81 return func(yield func(Event, error) bool) {
82 // iterate event from the wire.
83 // https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#examples
84 //
85 // - `key: value` line records.
86 // - Consecutive `data: ...` fields are joined with newlines.
87 // - Unrecognized fields are ignored. Since we only care about 'event', 'id', and
88 // 'data', these are the only three we consider.
89 // - Lines starting with ":" are ignored.
90 // - Records are terminated with two consecutive newlines.
91 var (
92 evt Event
93 dataBuf *bytes.Buffer // if non-nil, preceding field was also data
94 )
95 yieldEvent := func() bool {
96 if dataBuf != nil {
97 evt.Data = dataBuf.Bytes()
98 dataBuf = nil
99 }
100 if evt.Empty() {
101 return true
102 }
103 if !yield(evt, nil) {
104 return false
105 }
106 evt = Event{}
107 return true
108 }
109 for {
110 line, err := reader.ReadBytes('\n')
111 if err != nil && !errors.Is(err, io.EOF) {
112 yield(Event{}, fmt.Errorf("error reading event: %v", err))
113 return
114 }
115 line = bytes.TrimRight(line, "\r\n")
116 isEOF := errors.Is(err, io.EOF)
117
118 if len(line) == 0 {
119 if !yieldEvent() {
120 return
121 }
122 if isEOF {
123 return
124 }
125 continue
126 }
127 before, after, found := bytes.Cut(line, []byte{':'})
128 if !found {
129 yield(Event{}, fmt.Errorf("%w: malformed line in SSE stream: %q", errMalformedEvent, string(line)))
130 return
131 }
132 switch {
133 case bytes.Equal(before, eventKey):
134 evt.Name = strings.TrimSpace(string(after))
135 case bytes.Equal(before, idKey):
136 evt.ID = strings.TrimSpace(string(after))
137 case bytes.Equal(before, retryKey):
138 evt.Retry = strings.TrimSpace(string(after))
139 case bytes.Equal(before, dataKey):
140 data := bytes.TrimSpace(after)
141 if dataBuf == nil {
142 dataBuf = new(bytes.Buffer)
143 } else {
144 dataBuf.WriteByte('\n')
145 }
146 dataBuf.Write(data)
147 }
148
149 if isEOF {
150 yieldEvent()
151 return
152 }
153 }
154 }
155 }
156
157 // An EventStore tracks data for SSE streams.
158 // A single EventStore suffices for all sessions, since session IDs are
159 // globally unique. So one EventStore can be created per process, for
160 // all Servers in the process.
161 // Such a store is able to bound resource usage for the entire process.
162 //
163 // All of an EventStore's methods must be safe for use by multiple goroutines.
164 type EventStore interface {
165 // Open is called when a new stream is created. It may be used to ensure that
166 // the underlying data structure for the stream is initialized, making it
167 // ready to store and replay event streams.
168 Open(_ context.Context, sessionID, streamID string) error
169
170 // Append appends data for an outgoing event to given stream, which is part of the
171 // given session.
172 Append(_ context.Context, sessionID, streamID string, data []byte) error
173
174 // After returns an iterator over the data for the given session and stream, beginning
175 // just after the given index.
176 //
177 // Once the iterator yields a non-nil error, it will stop.
178 // After's iterator must return an error immediately if any data after index was
179 // dropped; it must not return partial results.
180 // The stream must have been opened previously (see [EventStore.Open]).
181 After(_ context.Context, sessionID, streamID string, index int) iter.Seq2[[]byte, error]
182
183 // SessionClosed informs the store that the given session is finished, along
184 // with all of its streams.
185 //
186 // A store cannot rely on this method being called for cleanup. It should institute
187 // additional mechanisms, such as timeouts, to reclaim storage.
188 SessionClosed(_ context.Context, sessionID string) error
189
190 // There is no StreamClosed method. A server doesn't know when a stream is finished, because
191 // the client can always send a GET with a Last-Event-ID referring to the stream.
192 }
193
194 // A dataList is a list of []byte.
195 // The zero dataList is ready to use.
196 type dataList struct {
197 size int // total size of data bytes
198 first int // the stream index of the first element in data
199 data [][]byte
200 }
201
202 func (dl *dataList) appendData(d []byte) {
203 // Empty data consumes memory but doesn't increment size. However, it should
204 // be rare.
205 dl.data = append(dl.data, d)
206 dl.size += len(d)
207 }
208
209 // removeFirst removes the first data item in dl, returning the size of the item.
210 // It panics if dl is empty.
211 func (dl *dataList) removeFirst() int {
212 if len(dl.data) == 0 {
213 panic("empty dataList")
214 }
215 r := len(dl.data[0])
216 dl.size -= r
217 dl.data[0] = nil // help GC
218 dl.data = dl.data[1:]
219 dl.first++
220 return r
221 }
222
223 // A MemoryEventStore is an [EventStore] backed by memory.
224 type MemoryEventStore struct {
225 mu sync.Mutex
226 maxBytes int // max total size of all data
227 nBytes int // current total size of all data
228 store map[string]map[string]*dataList // session ID -> stream ID -> *dataList
229 }
230
231 // MemoryEventStoreOptions are options for a [MemoryEventStore].
232 type MemoryEventStoreOptions struct{}
233
234 // MaxBytes returns the maximum number of bytes that the store will retain before
235 // purging data.
236 func (s *MemoryEventStore) MaxBytes() int {
237 s.mu.Lock()
238 defer s.mu.Unlock()
239 return s.maxBytes
240 }
241
242 // SetMaxBytes sets the maximum number of bytes the store will retain before purging
243 // data. The argument must not be negative. If it is zero, a suitable default will be used.
244 // SetMaxBytes can be called at any time. The size of the store will be adjusted
245 // immediately.
246 func (s *MemoryEventStore) SetMaxBytes(n int) {
247 s.mu.Lock()
248 defer s.mu.Unlock()
249 switch {
250 case n < 0:
251 panic("negative argument")
252 case n == 0:
253 s.maxBytes = defaultMaxBytes
254 default:
255 s.maxBytes = n
256 }
257 s.purge()
258 }
259
260 const defaultMaxBytes = 10 << 20 // 10 MiB
261
262 // NewMemoryEventStore creates a [MemoryEventStore] with the default value
263 // for MaxBytes.
264 func NewMemoryEventStore(opts *MemoryEventStoreOptions) *MemoryEventStore {
265 return &MemoryEventStore{
266 maxBytes: defaultMaxBytes,
267 store: make(map[string]map[string]*dataList),
268 }
269 }
270
271 // Open implements [EventStore.Open]. It ensures that the underlying data
272 // structures for the given session are initialized and ready for use.
273 func (s *MemoryEventStore) Open(_ context.Context, sessionID, streamID string) error {
274 s.mu.Lock()
275 defer s.mu.Unlock()
276 s.init(sessionID, streamID)
277 return nil
278 }
279
280 // init is an internal helper function that ensures the nested map structure for a
281 // given sessionID and streamID exists, creating it if necessary. It returns the
282 // dataList associated with the specified IDs.
283 // Requires s.mu.
284 func (s *MemoryEventStore) init(sessionID, streamID string) *dataList {
285 streamMap, ok := s.store[sessionID]
286 if !ok {
287 streamMap = make(map[string]*dataList)
288 s.store[sessionID] = streamMap
289 }
290 dl, ok := streamMap[streamID]
291 if !ok {
292 dl = &dataList{}
293 streamMap[streamID] = dl
294 }
295 return dl
296 }
297
298 // Append implements [EventStore.Append] by recording data in memory.
299 func (s *MemoryEventStore) Append(_ context.Context, sessionID, streamID string, data []byte) error {
300 s.mu.Lock()
301 defer s.mu.Unlock()
302 dl := s.init(sessionID, streamID)
303 // Purge before adding, so at least the current data item will be present.
304 // (That could result in nBytes > maxBytes, but we'll live with that.)
305 s.purge()
306 dl.appendData(data)
307 s.nBytes += len(data)
308 return nil
309 }
310
311 // ErrEventsPurged is the error that [EventStore.After] should return if the event just after the
312 // index is no longer available.
313 var ErrEventsPurged = errors.New("data purged")
314
315 // errMalformedEvent is returned when an SSE event cannot be parsed due to format violations.
316 // This is a hard error indicating corrupted data or protocol violations, as opposed to
317 // transient I/O errors which may be retryable.
318 var errMalformedEvent = errors.New("malformed event")
319
320 // After implements [EventStore.After].
321 func (s *MemoryEventStore) After(_ context.Context, sessionID, streamID string, index int) iter.Seq2[[]byte, error] {
322 // Return the data items to yield.
323 // We must copy, because dataList.removeFirst nils out slice elements.
324 copyData := func() ([][]byte, error) {
325 s.mu.Lock()
326 defer s.mu.Unlock()
327 streamMap, ok := s.store[sessionID]
328 if !ok {
329 return nil, fmt.Errorf("MemoryEventStore.After: unknown session ID %q", sessionID)
330 }
331 dl, ok := streamMap[streamID]
332 if !ok {
333 return nil, fmt.Errorf("MemoryEventStore.After: unknown stream ID %v in session %q", streamID, sessionID)
334 }
335 start := index + 1
336 if dl.first > start {
337 return nil, fmt.Errorf("MemoryEventStore.After: index %d, stream ID %v, session %q: %w",
338 index, streamID, sessionID, ErrEventsPurged)
339 }
340 return slices.Clone(dl.data[start-dl.first:]), nil
341 }
342
343 return func(yield func([]byte, error) bool) {
344 ds, err := copyData()
345 if err != nil {
346 yield(nil, err)
347 return
348 }
349 for _, d := range ds {
350 if !yield(d, nil) {
351 return
352 }
353 }
354 }
355 }
356
357 // SessionClosed implements [EventStore.SessionClosed].
358 func (s *MemoryEventStore) SessionClosed(_ context.Context, sessionID string) error {
359 s.mu.Lock()
360 defer s.mu.Unlock()
361 for _, dl := range s.store[sessionID] {
362 s.nBytes -= dl.size
363 }
364 delete(s.store, sessionID)
365 s.validate()
366 return nil
367 }
368
369 // purge removes data until no more than s.maxBytes bytes are in use.
370 // It must be called with s.mu held.
371 func (s *MemoryEventStore) purge() {
372 // Remove the first element of every dataList until below the max.
373 for s.nBytes > s.maxBytes {
374 changed := false
375 for _, sm := range s.store {
376 for _, dl := range sm {
377 if dl.size > 0 {
378 r := dl.removeFirst()
379 // Even if we remove an empty chunk, that's
380 // still progress. There may be non-empty
381 // chunks after it.
382 changed = true
383 s.nBytes -= r
384 }
385 }
386 }
387 if !changed {
388 panic("no progress during purge")
389 }
390 }
391 s.validate()
392 }
393
394 // validate checks that the store's data structures are valid.
395 // It must be called with s.mu held.
396 func (s *MemoryEventStore) validate() {
397 if !validateMemoryEventStore {
398 return
399 }
400 // Check that we're accounting for the size correctly.
401 n := 0
402 for _, sm := range s.store {
403 for _, dl := range sm {
404 for _, d := range dl.data {
405 n += len(d)
406 }
407 }
408 }
409 if n != s.nBytes {
410 panic("sizes don't add up")
411 }
412 }
413
414 // debugString returns a string containing the state of s.
415 // Used in tests.
416 func (s *MemoryEventStore) debugString() string {
417 s.mu.Lock()
418 defer s.mu.Unlock()
419 var b strings.Builder
420 for i, sess := range slices.Sorted(maps.Keys(s.store)) {
421 if i > 0 {
422 fmt.Fprintf(&b, "; ")
423 }
424 sm := s.store[sess]
425 for i, sid := range slices.Sorted(maps.Keys(sm)) {
426 if i > 0 {
427 fmt.Fprintf(&b, "; ")
428 }
429 dl := sm[sid]
430 fmt.Fprintf(&b, "%s %s first=%d", sess, sid, dl.first)
431 for _, d := range dl.data {
432 fmt.Fprintf(&b, " %s", d)
433 }
434 }
435 }
436 return b.String()
437 }