Debian Codegraph @

debian/go/src/github.com/modelcontextprotocol/go-sdk/mcp/event_test.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 "context"
9 "crypto/rand"
10 "fmt"
11 "slices"
12 "strings"
13 "testing"
14 "time"
15 )
16
17 func TestScanEvents(t *testing.T) {
18 tests := []struct {
19 name string
20 input string
21 want []Event
22 wantErr string
23 }{
24 {
25 name: "simple event",
26 input: "event: message\nid: 1\ndata: hello\n\n",
27 want: []Event{
28 {Name: "message", ID: "1", Data: []byte("hello")},
29 },
30 },
31 {
32 name: "multiple data lines",
33 input: "data: line 1\ndata: line 2\n\n",
34 want: []Event{
35 {Data: []byte("line 1\nline 2")},
36 },
37 },
38 {
39 name: "multiple events",
40 input: "data: first\n\nevent: second\ndata: second\n\n",
41 want: []Event{
42 {Data: []byte("first")},
43 {Name: "second", Data: []byte("second")},
44 },
45 },
46 {
47 name: "no trailing newline",
48 input: "data: hello",
49 want: []Event{
50 {Data: []byte("hello")},
51 },
52 },
53 {
54 name: "malformed line",
55 input: "invalid line\n\n",
56 wantErr: "malformed line",
57 },
58 {
59 name: "message with 2 data lines and another event",
60 input: "event: message\ndata: hello\ndata: hello\ndata: hello\n\nevent:keepalive",
61 want: []Event{
62 {Name: "message", Data: []byte("hello\nhello\nhello")},
63 {Name: "keepalive"},
64 },
65 },
66 {
67 name: "event with multiple lines",
68 input: "event: message\ndata: hello\ndata: hello\ndata: hello\nid:1",
69 want: []Event{
70 {Name: "message", ID: "1", Data: []byte("hello\nhello\nhello")},
71 },
72 },
73 {
74 name: "multiple events, out of order keys",
75 input: strings.Join([]string{
76 "event:message",
77 "data: hello0",
78 "\n",
79 "data: hello1",
80 "data: hello1",
81 "id:1",
82 "event:message",
83 "\n",
84 "event:message",
85 "data: hello3",
86 "data: hello3",
87 "id:3",
88 "\n",
89 "data: hello4",
90 "data: hello4",
91 "id:4",
92 "event:message",
93 }, "\n"),
94 want: []Event{
95 {Name: "message", Data: []byte("hello0")},
96 {Name: "message", ID: "1", Data: []byte("hello1\nhello1")},
97 {Name: "message", ID: "3", Data: []byte("hello3\nhello3")},
98 {Name: "message", ID: "4", Data: []byte("hello4\nhello4")},
99 },
100 },
101 {
102 name: "non-continuous data items in the event",
103 input: "event: foo\ndata: 123\nretry: 5\ndata: 456",
104 want: []Event{
105 {Name: "foo", Data: []byte("123\n456"), Retry: "5"},
106 },
107 },
108 {
109 name: "no-data events",
110 input: "event: foo\n\nevent: bar",
111 want: []Event{
112 {Name: "foo"},
113 {Name: "bar"},
114 },
115 },
116 {
117 name: "empty data event",
118 input: "event: foo\ndata:\n\nevent: bar",
119 want: []Event{
120 {Name: "foo"},
121 {Name: "bar"},
122 },
123 },
124 {
125
126 name: "malformed data event",
127 input: "someline",
128 wantErr: "malformed event",
129 },
130 }
131
132 for _, tt := range tests {
133 t.Run(tt.name, func(t *testing.T) {
134 r := strings.NewReader(tt.input)
135 var got []Event
136 var err error
137 for e, err2 := range scanEvents(r) {
138 if err2 != nil {
139 err = err2
140 break
141 }
142 got = append(got, e)
143 }
144
145 if tt.wantErr != "" {
146 if err == nil {
147 t.Fatalf("scanEvents() got nil error, want error containing %q", tt.wantErr)
148 }
149 if !strings.Contains(err.Error(), tt.wantErr) {
150 t.Fatalf("scanEvents() error = %q, want containing %q", err, tt.wantErr)
151 }
152 return
153 }
154
155 if err != nil {
156 t.Fatalf("scanEvents() returned unexpected error: %v", err)
157 }
158
159 if len(got) != len(tt.want) {
160 t.Fatalf("scanEvents() got %d events, want %d", len(got), len(tt.want))
161 }
162
163 for i := range got {
164 if g, w := got[i].Name, tt.want[i].Name; g != w {
165 t.Errorf("event %d: name = %q, want %q", i, g, w)
166 }
167 if g, w := got[i].ID, tt.want[i].ID; g != w {
168 t.Errorf("event %d: id = %q, want %q", i, g, w)
169 }
170 if g, w := string(got[i].Data), string(tt.want[i].Data); g != w {
171 t.Errorf("event %d: data = %q, want %q", i, g, w)
172 }
173 }
174 })
175 }
176 }
177
178 func TestMemoryEventStoreState(t *testing.T) {
179 ctx := context.Background()
180
181 appendEvent := func(s *MemoryEventStore, sess, stream string, data string) {
182 if err := s.Append(ctx, sess, stream, []byte(data)); err != nil {
183 t.Fatal(err)
184 }
185 }
186
187 for _, tt := range []struct {
188 name string
189 actions func(*MemoryEventStore)
190 want string // output of debugString
191 wantSize int // value of nBytes
192 }{
193 {
194 "appends",
195 func(s *MemoryEventStore) {
196 appendEvent(s, "S1", "1", "d1")
197 appendEvent(s, "S1", "2", "d2")
198 appendEvent(s, "S1", "1", "d3")
199 appendEvent(s, "S2", "8", "d4")
200 },
201 "S1 1 first=0 d1 d3; S1 2 first=0 d2; S2 8 first=0 d4",
202 8,
203 },
204 {
205 "session close",
206 func(s *MemoryEventStore) {
207 appendEvent(s, "S1", "1", "d1")
208 appendEvent(s, "S1", "2", "d2")
209 appendEvent(s, "S1", "1", "d3")
210 appendEvent(s, "S2", "8", "d4")
211 s.SessionClosed(ctx, "S1")
212 },
213 "S2 8 first=0 d4",
214 2,
215 },
216 {
217 "purge",
218 func(s *MemoryEventStore) {
219 appendEvent(s, "S1", "1", "d1")
220 appendEvent(s, "S1", "2", "d2")
221 appendEvent(s, "S1", "1", "d3")
222 appendEvent(s, "S2", "8", "d4")
223 // We are using 8 bytes (d1,d2, d3, d4).
224 // To purge 6, we remove the first of each stream, leaving only d3.
225 s.SetMaxBytes(2)
226 },
227 // The other streams remain, because we may add to them.
228 "S1 1 first=1 d3; S1 2 first=1; S2 8 first=1",
229 2,
230 },
231 {
232 "purge append",
233 func(s *MemoryEventStore) {
234 appendEvent(s, "S1", "1", "d1")
235 appendEvent(s, "S1", "2", "d2")
236 appendEvent(s, "S1", "1", "d3")
237 appendEvent(s, "S2", "8", "d4")
238 s.SetMaxBytes(2)
239 // Up to here, identical to the "purge" case.
240 // Each of these additions will result in a purge.
241 appendEvent(s, "S1", "2", "d5") // remove d3
242 appendEvent(s, "S1", "2", "d6") // remove d5
243 },
244 "S1 1 first=2; S1 2 first=2 d6; S2 8 first=1",
245 2,
246 },
247 {
248 "purge resize append",
249 func(s *MemoryEventStore) {
250 appendEvent(s, "S1", "1", "d1")
251 appendEvent(s, "S1", "2", "d2")
252 appendEvent(s, "S1", "1", "d3")
253 appendEvent(s, "S2", "8", "d4")
254 s.SetMaxBytes(2)
255 // Up to here, identical to the "purge" case.
256 s.SetMaxBytes(6) // make room
257 appendEvent(s, "S1", "2", "d5")
258 appendEvent(s, "S1", "2", "d6")
259 },
260 // The other streams remain, because we may add to them.
261 "S1 1 first=1 d3; S1 2 first=1 d5 d6; S2 8 first=1",
262 6,
263 },
264 } {
265 t.Run(tt.name, func(t *testing.T) {
266 s := NewMemoryEventStore(nil)
267 tt.actions(s)
268 got := s.debugString()
269 if got != tt.want {
270 t.Errorf("\ngot %s\nwant %s", got, tt.want)
271 }
272 if g, w := s.nBytes, tt.wantSize; g != w {
273 t.Errorf("got size %d, want %d", g, w)
274 }
275 })
276 }
277 }
278
279 func TestMemoryEventStoreAfter(t *testing.T) {
280 ctx := context.Background()
281 s := NewMemoryEventStore(nil)
282 s.SetMaxBytes(4)
283 s.Append(ctx, "S1", "1", []byte("d1"))
284 s.Append(ctx, "S1", "1", []byte("d2"))
285 s.Append(ctx, "S1", "1", []byte("d3"))
286 s.Append(ctx, "S1", "2", []byte("d4")) // will purge d1
287 want := "S1 1 first=1 d2 d3; S1 2 first=0 d4"
288 if got := s.debugString(); got != want {
289 t.Fatalf("got state %q, want %q", got, want)
290 }
291
292 for _, tt := range []struct {
293 sessionID string
294 streamID string
295 index int
296 want []string
297 wantErr string // if non-empty, error should contain this string
298 }{
299 {"S1", "1", 0, []string{"d2", "d3"}, ""},
300 {"S1", "1", 1, []string{"d3"}, ""},
301 {"S1", "1", 2, nil, ""},
302 {"S1", "2", 0, nil, ""},
303 {"S1", "3", 0, nil, "unknown stream ID"},
304 {"S2", "0", 0, nil, "unknown session ID"},
305 } {
306 t.Run(fmt.Sprintf("%s-%s-%d", tt.sessionID, tt.streamID, tt.index), func(t *testing.T) {
307 var got []string
308 for d, err := range s.After(ctx, tt.sessionID, tt.streamID, tt.index) {
309 if err != nil {
310 if tt.wantErr == "" {
311 t.Fatalf("unexpected error %q", err)
312 } else if g := err.Error(); !strings.Contains(g, tt.wantErr) {
313 t.Fatalf("got error %q, want it to contain %q", g, tt.wantErr)
314 } else {
315 return
316 }
317 }
318 got = append(got, string(d))
319 }
320 if tt.wantErr != "" {
321 t.Fatalf("expected error containing %q, got nil", tt.wantErr)
322 }
323 if !slices.Equal(got, tt.want) {
324 t.Errorf("got %v, want %v", got, tt.want)
325 }
326 })
327 }
328 }
329
330 func TestMemoryEventStorePurgeEmpty(t *testing.T) {
331 ctx := context.Background()
332 s := NewMemoryEventStore(nil)
333 s.SetMaxBytes(100)
334
335 // Append an empty chunk first.
336 if err := s.Append(ctx, "S1", "1", []byte("")); err != nil {
337 t.Fatal(err)
338 }
339 // Append a non-empty chunk.
340 if err := s.Append(ctx, "S1", "1", []byte("1234567890")); err != nil {
341 t.Fatal(err)
342 }
343 // Now nBytes = 10, but the first chunk is empty.
344
345 // This should not panic.
346 s.SetMaxBytes(5)
347
348 if s.nBytes > 5 {
349 t.Errorf("got nBytes %d, want <= 5", s.nBytes)
350 }
351 }
352
353 func BenchmarkMemoryEventStore(b *testing.B) {
354 // Benchmark with various settings for event store size, number of session,
355 // and payload size.
356 //
357 // Assume a small number of streams per session, which is probably realistic.
358 tests := []struct {
359 name string
360 limit int
361 sessions int
362 datasize int
363 }{
364 {"1KB", 1024, 1, 16},
365 {"1MB", 1024 * 1024, 10, 16},
366 {"10MB", 10 * 1024 * 1024, 100, 16},
367 {"10MB_big", 10 * 1024 * 1024, 1000, 128},
368 }
369
370 for _, test := range tests {
371 b.Run(test.name, func(b *testing.B) {
372 store := NewMemoryEventStore(nil)
373 store.SetMaxBytes(test.limit)
374 ctx := context.Background()
375 sessionIDs := make([]string, test.sessions)
376 streamIDs := make([][3]string, test.sessions)
377 for i := range sessionIDs {
378 sessionIDs[i] = fmt.Sprint(i)
379 for j := range 3 {
380 streamIDs[i][j] = rand.Text()
381 }
382 }
383 payload := make([]byte, test.datasize)
384 start := time.Now()
385 b.ResetTimer()
386 for i := range b.N {
387 sessionID := sessionIDs[i%len(sessionIDs)]
388 streamID := streamIDs[i%len(sessionIDs)][i%3]
389 store.Append(ctx, sessionID, streamID, payload)
390 }
391 b.ReportMetric(float64(test.datasize)*float64(b.N)/time.Since(start).Seconds(), "bytes/s")
392 })
393 }
394 }