-
Notifications
You must be signed in to change notification settings - Fork 419
Expand file tree
/
Copy pathmain.go
More file actions
895 lines (787 loc) · 26.3 KB
/
main.go
File metadata and controls
895 lines (787 loc) · 26.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
// Copyright 2025 The Go MCP SDK Authors. All rights reserved.
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
// The conformance server implements features required for MCP conformance testing.
// It mirrors the functionality of the TypeScript conformance server at
// https://github.com/modelcontextprotocol/conformance/blob/main/examples/servers/typescript/everything-server.ts
//go:build mcp_go_client_oauth
package main
import (
"context"
"encoding/base64"
"encoding/json"
"errors"
"flag"
"fmt"
"log"
"net/http"
"net/url"
"os"
"strings"
"time"
"github.com/google/jsonschema-go/jsonschema"
"github.com/modelcontextprotocol/go-sdk/auth"
"github.com/modelcontextprotocol/go-sdk/mcp"
"github.com/modelcontextprotocol/go-sdk/oauthex"
"github.com/yosida95/uritemplate/v3"
)
var (
httpAddr = flag.String("http", "", "if set, use streamable HTTP at this address, instead of stdin/stdout")
enableAuth = flag.Bool("enable_auth", false, "if set, enable OAuth authorization")
)
const (
watchedResourceURI = "test://watched-resource"
adminScope = "admin"
)
func main() {
flag.Parse()
opts := &mcp.ServerOptions{
CompletionHandler: completionHandler,
SubscribeHandler: subscribeHandler,
UnsubscribeHandler: unsubscribeHandler,
}
server := mcp.NewServer(&mcp.Implementation{
Name: "mcp-conformance-test-server",
Version: "1.0.0",
}, opts)
// Register server features.
registerTools(server)
registerResources(server)
registerPrompts(server)
// Start the watched resource auto-update goroutine.
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go watchedResourceUpdater(ctx, server)
// Serve over stdio, or streamable HTTP if -http is set.
if *httpAddr != "" {
mux := http.NewServeMux()
var mcpHandler http.Handler = mcp.NewStreamableHTTPHandler(func(*http.Request) *mcp.Server {
return server
}, nil)
if *enableAuth {
authServerURL := os.Getenv("MCP_CONFORMANCE_AUTH_SERVER_URL")
if authServerURL == "" {
log.Fatal("MCP_CONFORMANCE_AUTH_SERVER_URL environment variable must be set when --enable-auth is true")
}
handlePRM(mux, authServerURL)
var err error
mcpHandler, err = addAuthMiddleware(mcpHandler, authServerURL)
if err != nil {
log.Fatalf("auth middleware: %v", err)
}
}
mux.Handle("/mcp", mcpHandler)
log.Printf("Conformance server listening at http://%s/mcp", *httpAddr)
log.Fatal(http.ListenAndServe(*httpAddr, mux))
} else {
t := &mcp.StdioTransport{}
if err := server.Run(ctx, t); err != nil {
log.Printf("Server failed: %v", err)
os.Exit(1)
}
}
}
// watchedResourceUpdater sends resource update notifications every 3 seconds.
func watchedResourceUpdater(ctx context.Context, server *mcp.Server) {
ticker := time.NewTicker(3 * time.Second)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
server.ResourceUpdated(ctx, &mcp.ResourceUpdatedNotificationParams{
URI: watchedResourceURI,
})
}
}
}
// =============================================================================
// Tools
// =============================================================================
func registerTools(server *mcp.Server) {
mcp.AddTool(server, &mcp.Tool{
Name: "test_simple_text",
Description: "Tests simple text content response",
}, testSimpleTextHandler)
mcp.AddTool(server, &mcp.Tool{
Name: "test_image_content",
Description: "Tests image content response",
}, testImageContentHandler)
mcp.AddTool(server, &mcp.Tool{
Name: "test_audio_content",
Description: "Tests audio content response",
}, testAudioContentHandler)
mcp.AddTool(server, &mcp.Tool{
Name: "test_embedded_resource",
Description: "Tests embedded resource content response",
}, testEmbeddedResourceHandler)
mcp.AddTool(server, &mcp.Tool{
Name: "test_multiple_content_types",
Description: "Tests response with multiple content types (text, image, resource)",
}, testMultipleContentTypesHandler)
mcp.AddTool(server, &mcp.Tool{
Name: "test_tool_with_logging",
Description: "Tests tool that emits log messages during execution",
}, testToolWithLoggingHandler)
mcp.AddTool(server, &mcp.Tool{
Name: "test_tool_with_progress",
Description: "Tests tool that reports progress notifications",
}, testToolWithProgressHandler)
mcp.AddTool(server, &mcp.Tool{
Name: "test_error_handling",
Description: "Tests error response handling",
}, testErrorHandlingHandler)
mcp.AddTool(server, &mcp.Tool{
Name: "test_sampling",
Description: "Tests server-initiated sampling (LLM completion request)",
}, testSamplingHandler)
mcp.AddTool(server, &mcp.Tool{
Name: "test_elicitation",
Description: "Tests server-initiated elicitation (user input request)",
}, testElicitationHandler)
mcp.AddTool(server, &mcp.Tool{
Name: "test_elicitation_sep1034_defaults",
Description: "Tests elicitation with default values per SEP-1034",
}, testElicitationDefaultsHandler)
mcp.AddTool(server, &mcp.Tool{
Name: "test_elicitation_sep1330_enums",
Description: "Tests elicitation with enum schema improvements per SEP-1330",
}, testElicitationEnumsHandler)
mcp.AddTool(server, &mcp.Tool{
Name: "json_schema_2020_12_tool",
Description: "Tool with JSON Schema 2020-12 features for conformance testing (SEP-1613)",
InputSchema: json.RawMessage(`{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"$defs": {
"address": {
"type": "object",
"properties": {
"street": { "type": "string" },
"city": { "type": "string" }
}
}
},
"properties": {
"name": { "type": "string" },
"address": { "$ref": "#/$defs/address" }
},
"additionalProperties": false
}`),
}, jsonSchema202012Handler)
mcp.AddTool(server, &mcp.Tool{
Name: "test_reconnection",
Description: "Tests SSE stream disconnection and client reconnection (SEP-1699). Server will close the stream mid-call and send the result after client reconnects.",
}, testReconnectionHandler)
}
// Tool handlers
func testSimpleTextHandler(ctx context.Context, req *mcp.CallToolRequest, _ any) (*mcp.CallToolResult, any, error) {
return &mcp.CallToolResult{
Content: []mcp.Content{
&mcp.TextContent{Text: "This is a simple text response for testing."},
},
}, nil, nil
}
func testImageContentHandler(ctx context.Context, req *mcp.CallToolRequest, _ any) (*mcp.CallToolResult, any, error) {
return &mcp.CallToolResult{
Content: []mcp.Content{
&mcp.ImageContent{
Data: imageData(),
MIMEType: "image/png",
},
},
}, nil, nil
}
func testAudioContentHandler(ctx context.Context, req *mcp.CallToolRequest, _ any) (*mcp.CallToolResult, any, error) {
return &mcp.CallToolResult{
Content: []mcp.Content{
&mcp.AudioContent{
Data: audioData(),
MIMEType: "audio/wav",
},
},
}, nil, nil
}
func testEmbeddedResourceHandler(ctx context.Context, req *mcp.CallToolRequest, _ any) (*mcp.CallToolResult, any, error) {
return &mcp.CallToolResult{
Content: []mcp.Content{
&mcp.EmbeddedResource{
Resource: &mcp.ResourceContents{
URI: "test://embedded-resource",
MIMEType: "text/plain",
Text: "This is an embedded resource",
},
},
},
}, nil, nil
}
func testMultipleContentTypesHandler(ctx context.Context, req *mcp.CallToolRequest, _ any) (*mcp.CallToolResult, any, error) {
return &mcp.CallToolResult{
Content: []mcp.Content{
&mcp.TextContent{Text: "This is text content"},
&mcp.ImageContent{
Data: imageData(),
MIMEType: "image/png",
},
&mcp.EmbeddedResource{
Resource: &mcp.ResourceContents{
URI: "test://embedded-in-multiple",
MIMEType: "text/plain",
Text: "This is an embedded resource",
},
},
},
}, nil, nil
}
func testToolWithLoggingHandler(ctx context.Context, req *mcp.CallToolRequest, _ any) (*mcp.CallToolResult, any, error) {
// Emit three info-level log messages
req.Session.Log(ctx, &mcp.LoggingMessageParams{
Level: "info",
Data: "Tool execution started",
})
time.Sleep(50 * time.Millisecond)
req.Session.Log(ctx, &mcp.LoggingMessageParams{
Level: "info",
Data: "Tool processing data",
})
time.Sleep(50 * time.Millisecond)
req.Session.Log(ctx, &mcp.LoggingMessageParams{
Level: "info",
Data: "Tool execution completed",
})
return &mcp.CallToolResult{
Content: []mcp.Content{
&mcp.TextContent{Text: "Tool with logging executed successfully"},
},
}, nil, nil
}
func testToolWithProgressHandler(ctx context.Context, req *mcp.CallToolRequest, _ any) (*mcp.CallToolResult, any, error) {
// Get progress token from the request if provided
progressToken := req.Params.GetProgressToken()
// Send three progress notifications (0%, 50%, 100%)
total := 100.0
steps := []float64{0, 50, 100}
for _, progress := range steps {
req.Session.NotifyProgress(ctx, &mcp.ProgressNotificationParams{
ProgressToken: progressToken,
Progress: progress,
Total: total,
Message: fmt.Sprintf("Completed step %.0f of %.0f", progress, total),
})
time.Sleep(50 * time.Millisecond)
}
// Return the progress token value as the response (matching TypeScript behavior)
tokenStr := fmt.Sprintf("%v", progressToken)
return &mcp.CallToolResult{
Content: []mcp.Content{
&mcp.TextContent{Text: tokenStr},
},
}, nil, nil
}
func testErrorHandlingHandler(ctx context.Context, req *mcp.CallToolRequest, _ any) (*mcp.CallToolResult, any, error) {
return nil, nil, errors.New("this tool intentionally returns an error for testing")
}
type samplingInput struct {
Prompt string `json:"prompt" jsonschema:"The prompt to send to the LLM"`
}
func testSamplingHandler(ctx context.Context, req *mcp.CallToolRequest, input samplingInput) (*mcp.CallToolResult, any, error) {
// Request LLM completion from the client
result, err := req.Session.CreateMessage(ctx, &mcp.CreateMessageParams{
Messages: []*mcp.SamplingMessage{
{
Role: "user",
Content: &mcp.TextContent{
Text: input.Prompt,
},
},
},
MaxTokens: 100,
})
if err != nil {
return nil, nil, fmt.Errorf("sampling failed: %w", err)
}
// Extract the text response from the result
var responseText string
if tc, ok := result.Content.(*mcp.TextContent); ok {
responseText = tc.Text
} else {
responseText = "(non-text response)"
}
return &mcp.CallToolResult{
Content: []mcp.Content{
&mcp.TextContent{Text: fmt.Sprintf("LLM response: %s", responseText)},
},
}, nil, nil
}
type elicitationInput struct {
Message string `json:"message" jsonschema:"The message to show the user"`
}
func testElicitationHandler(ctx context.Context, req *mcp.CallToolRequest, input elicitationInput) (*mcp.CallToolResult, any, error) {
result, err := req.Session.Elicit(ctx, &mcp.ElicitParams{
Message: input.Message,
RequestedSchema: &jsonschema.Schema{
Type: "object",
Properties: map[string]*jsonschema.Schema{
"username": {
Type: "string",
Description: "Your preferred username",
},
},
Required: []string{"username"},
},
})
if err != nil {
return nil, nil, fmt.Errorf("elicitation failed: %w", err)
}
return &mcp.CallToolResult{
Content: []mcp.Content{
&mcp.TextContent{Text: fmt.Sprintf("Elicitation result: action=%s, content=%v", result.Action, result.Content)},
},
}, nil, nil
}
func testElicitationDefaultsHandler(ctx context.Context, req *mcp.CallToolRequest, _ any) (*mcp.CallToolResult, any, error) {
result, err := req.Session.Elicit(ctx, &mcp.ElicitParams{
Message: "Test defaults for primitives",
RequestedSchema: map[string]any{
"type": "object",
"properties": map[string]any{
"name": map[string]any{
"type": "string",
"description": "User name",
"default": "John Doe",
},
"age": map[string]any{
"type": "integer",
"description": "User age",
"default": 30,
},
"score": map[string]any{
"type": "number",
"description": "User score",
"default": 95.5,
},
"status": map[string]any{
"type": "string",
"description": "User status",
"enum": []string{"active", "inactive", "pending"},
"default": "active",
},
"verified": map[string]any{
"type": "boolean",
"description": "Verification status",
"default": true,
},
},
},
})
if err != nil {
return nil, nil, fmt.Errorf("elicitation failed: %w", err)
}
return &mcp.CallToolResult{
Content: []mcp.Content{
&mcp.TextContent{Text: fmt.Sprintf("Elicitation result: action=%s, content=%v", result.Action, result.Content)},
},
}, nil, nil
}
func testElicitationEnumsHandler(ctx context.Context, req *mcp.CallToolRequest, _ any) (*mcp.CallToolResult, any, error) {
result, err := req.Session.Elicit(ctx, &mcp.ElicitParams{
Message: "Test enum schemas",
RequestedSchema: map[string]any{
"type": "object",
"properties": map[string]any{
// Basic enum without titles
"untitledSingle": map[string]any{
"type": "string",
"enum": []string{"option1", "option2", "option3"},
},
// Enum with titles using oneOf
"titledSingle": map[string]any{
"type": "string",
"oneOf": []map[string]any{
{"const": "value1", "title": "First Option"},
{"const": "value2", "title": "Second Option"},
{"const": "value3", "title": "Third Option"},
},
},
// Legacy enum with enumNames
"legacyEnum": map[string]any{
"type": "string",
"enum": []string{"opt1", "opt2", "opt3"},
"enumNames": []string{"Option One", "Option Two", "Option Three"},
},
// Multi-select without titles
"untitledMulti": map[string]any{
"type": "array",
"minItems": 1,
"maxItems": 3,
"items": map[string]any{
"type": "string",
"enum": []string{"option1", "option2", "option3"},
},
},
// Multi-select with titles using anyOf
"titledMulti": map[string]any{
"type": "array",
"minItems": 1,
"maxItems": 3,
"items": map[string]any{
"type": "string",
"anyOf": []map[string]any{
{"const": "value1", "title": "First Option"},
{"const": "value2", "title": "Second Option"},
{"const": "value3", "title": "Third Option"},
},
},
},
},
},
})
if err != nil {
return nil, nil, fmt.Errorf("elicitation failed: %w", err)
}
return &mcp.CallToolResult{
Content: []mcp.Content{
&mcp.TextContent{Text: fmt.Sprintf("Elicitation result: action=%s, content=%v", result.Action, result.Content)},
},
}, nil, nil
}
type jsonSchemaAddress struct {
Street string `json:"street"`
City string `json:"city"`
}
type jsonSchemaInput struct {
Name string `json:"name"`
Address *jsonSchemaAddress `json:"address"`
}
func jsonSchema202012Handler(ctx context.Context, req *mcp.CallToolRequest, input jsonSchemaInput) (*mcp.CallToolResult, any, error) {
// Echo back the arguments received
var addressStr string
if input.Address != nil {
addressStr = fmt.Sprintf("{street: %q, city: %q}", input.Address.Street, input.Address.City)
} else {
addressStr = "nil"
}
return &mcp.CallToolResult{
Content: []mcp.Content{
&mcp.TextContent{
Text: fmt.Sprintf("Received: name=%q, address=%s", input.Name, addressStr),
},
},
}, nil, nil
}
func testReconnectionHandler(ctx context.Context, req *mcp.CallToolRequest, _ any) (*mcp.CallToolResult, any, error) {
// Close the SSE stream to trigger client reconnection (SEP-1699)
if req.Extra != nil && req.Extra.CloseSSEStream != nil {
req.Extra.CloseSSEStream(mcp.CloseSSEStreamArgs{RetryAfter: 10 * time.Millisecond})
}
// Wait for client to reconnect
time.Sleep(100 * time.Millisecond)
return &mcp.CallToolResult{
Content: []mcp.Content{
&mcp.TextContent{
Text: "Reconnection test completed successfully. If you received this, the client properly reconnected after stream closure.",
},
},
}, nil, nil
}
// =============================================================================
// Resources
// =============================================================================
func registerResources(server *mcp.Server) {
server.AddResource(&mcp.Resource{
Name: "static-text",
Description: "A static text resource for testing",
MIMEType: "text/plain",
URI: "test://static-text",
}, staticTextHandler)
server.AddResource(&mcp.Resource{
Name: "static-binary",
Description: "A static binary resource (image) for testing",
MIMEType: "image/png",
URI: "test://static-binary",
}, staticBinaryHandler)
server.AddResourceTemplate(&mcp.ResourceTemplate{
Name: "template",
Description: "A resource template with parameter substitution",
MIMEType: "application/json",
URITemplate: "test://template/{id}/data",
}, templateResourceHandler)
server.AddResource(&mcp.Resource{
Name: "watched-resource",
Description: "A resource that auto-updates every 3 seconds",
MIMEType: "text/plain",
URI: watchedResourceURI,
}, watchedResourceHandler)
}
func staticTextHandler(ctx context.Context, req *mcp.ReadResourceRequest) (*mcp.ReadResourceResult, error) {
return &mcp.ReadResourceResult{
Contents: []*mcp.ResourceContents{
{
URI: req.Params.URI,
MIMEType: "text/plain",
Text: "This is the content of the static text resource.",
},
},
}, nil
}
func staticBinaryHandler(ctx context.Context, req *mcp.ReadResourceRequest) (*mcp.ReadResourceResult, error) {
return &mcp.ReadResourceResult{
Contents: []*mcp.ResourceContents{
{
URI: req.Params.URI,
MIMEType: "image/png",
Blob: imageData(),
},
},
}, nil
}
// templatePattern is the compiled URI template for the template resource.
var templatePattern = uritemplate.MustNew("test://template/{id}/data")
func templateResourceHandler(ctx context.Context, req *mcp.ReadResourceRequest) (*mcp.ReadResourceResult, error) {
// Extract the ID from the URI using the template pattern
uri := req.Params.URI
match := templatePattern.Regexp().FindStringSubmatch(uri)
id := ""
if len(match) > 1 {
id = match[1]
}
jsonContent := fmt.Sprintf(`{"id": "%s", "templateTest": true, "data": "Data for ID: %s"}`, id, id)
return &mcp.ReadResourceResult{
Contents: []*mcp.ResourceContents{
{
URI: uri,
MIMEType: "application/json",
Text: jsonContent,
},
},
}, nil
}
func watchedResourceHandler(ctx context.Context, req *mcp.ReadResourceRequest) (*mcp.ReadResourceResult, error) {
return &mcp.ReadResourceResult{
Contents: []*mcp.ResourceContents{
{
URI: req.Params.URI,
MIMEType: "text/plain",
Text: "Watched resource content",
},
},
}, nil
}
// =============================================================================
// Prompts
// =============================================================================
func registerPrompts(server *mcp.Server) {
server.AddPrompt(&mcp.Prompt{
Name: "test_simple_prompt",
Title: "Simple Test Prompt",
Description: "A simple prompt without arguments",
}, simplePromptHandler)
server.AddPrompt(&mcp.Prompt{
Name: "test_prompt_with_arguments",
Title: "Prompt With Arguments",
Description: "A prompt with required arguments",
Arguments: []*mcp.PromptArgument{
{Name: "arg1", Description: "First test argument", Required: true},
{Name: "arg2", Description: "Second test argument", Required: true},
},
}, promptWithArgumentsHandler)
server.AddPrompt(&mcp.Prompt{
Name: "test_prompt_with_embedded_resource",
Title: "Prompt With Embedded Resource",
Description: "A prompt that includes an embedded resource",
Arguments: []*mcp.PromptArgument{
{Name: "resourceUri", Description: "URI of the resource to embed", Required: true},
},
}, promptWithEmbeddedResourceHandler)
server.AddPrompt(&mcp.Prompt{
Name: "test_prompt_with_image",
Title: "Prompt With Image",
Description: "A prompt that includes image content",
}, promptWithImageHandler)
}
func simplePromptHandler(ctx context.Context, req *mcp.GetPromptRequest) (*mcp.GetPromptResult, error) {
return &mcp.GetPromptResult{
Description: "A simple test prompt",
Messages: []*mcp.PromptMessage{
{
Role: "user",
Content: &mcp.TextContent{Text: "This is a simple prompt for testing."},
},
},
}, nil
}
func promptWithArgumentsHandler(ctx context.Context, req *mcp.GetPromptRequest) (*mcp.GetPromptResult, error) {
arg1 := req.Params.Arguments["arg1"]
arg2 := req.Params.Arguments["arg2"]
return &mcp.GetPromptResult{
Description: "A prompt with arguments",
Messages: []*mcp.PromptMessage{
{
Role: "user",
Content: &mcp.TextContent{
Text: fmt.Sprintf("Prompt with arguments: arg1='%s', arg2='%s'", arg1, arg2),
},
},
},
}, nil
}
func promptWithEmbeddedResourceHandler(ctx context.Context, req *mcp.GetPromptRequest) (*mcp.GetPromptResult, error) {
resourceUri := req.Params.Arguments["resourceUri"]
return &mcp.GetPromptResult{
Description: "A prompt with an embedded resource",
Messages: []*mcp.PromptMessage{
{
Role: "user",
Content: &mcp.EmbeddedResource{
Resource: &mcp.ResourceContents{
URI: resourceUri,
MIMEType: "text/plain",
Text: "Embedded resource content for testing.",
},
},
},
{
Role: "user",
Content: &mcp.TextContent{Text: "Please process the embedded resource above."},
},
},
}, nil
}
func promptWithImageHandler(ctx context.Context, req *mcp.GetPromptRequest) (*mcp.GetPromptResult, error) {
return &mcp.GetPromptResult{
Description: "A prompt with an image",
Messages: []*mcp.PromptMessage{
{
Role: "user",
Content: &mcp.ImageContent{
Data: imageData(),
MIMEType: "image/png",
},
},
{
Role: "user",
Content: &mcp.TextContent{Text: "Please analyze the image above."},
},
},
}, nil
}
// =============================================================================
// Middleware
// =============================================================================
func handlePRM(mux *http.ServeMux, authServerURL string) {
// Host the resource metadata document.
resourceMetadata := &oauthex.ProtectedResourceMetadata{
Resource: "http://" + *httpAddr,
AuthorizationServers: []string{authServerURL},
ScopesSupported: []string{adminScope},
}
mux.Handle("/.well-known/oauth-protected-resource", auth.ProtectedResourceMetadataHandler(resourceMetadata))
}
func addAuthMiddleware(handler http.Handler, authServerURL string) (http.Handler, error) {
log.Printf("Fetching authorization server metadata from %s...", authServerURL)
metadata, err := oauthex.GetAuthServerMeta(context.Background(), authServerURL, http.DefaultClient)
if err != nil {
return nil, fmt.Errorf("fetch auth server metadata: %v", err)
}
if metadata.IntrospectionEndpoint == "" {
return nil, fmt.Errorf("auth server metadata does not contain introspection_endpoint")
}
log.Printf("Using introspection endpoint: %s", metadata.IntrospectionEndpoint)
tokenVerifier := createIntrospectionVerifier(metadata.IntrospectionEndpoint)
verifyAuth := auth.RequireBearerToken(tokenVerifier, &auth.RequireBearerTokenOptions{
ResourceMetadataURL: fmt.Sprintf("http://%s/.well-known/oauth-protected-resource", *httpAddr),
})
return verifyAuth(handler), nil
}
func createIntrospectionVerifier(introspectionEndpoint string) auth.TokenVerifier {
return func(ctx context.Context, token string, req *http.Request) (*auth.TokenInfo, error) {
data := url.Values{}
data.Set("token", token)
req, err := http.NewRequestWithContext(ctx, "POST", introspectionEndpoint, strings.NewReader(data.Encode()))
if err != nil {
return nil, fmt.Errorf("create introspection request: %v", err)
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Accept", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, fmt.Errorf("introspection request failed: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("introspection returned status %d", resp.StatusCode)
}
var result struct {
Active bool `json:"active"`
Scope string `json:"scope"`
Expiration int64 `json:"exp"`
ClientID string `json:"client_id"`
}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return nil, fmt.Errorf("decode introspection response: %v", err)
}
if !result.Active {
return nil, auth.ErrInvalidToken
}
expiration := time.Time{}
if result.Expiration != 0 {
expiration = time.Unix(result.Expiration, 0)
}
var scopes []string
if result.Scope != "" {
scopes = strings.Split(result.Scope, " ")
}
return &auth.TokenInfo{
Scopes: scopes,
Expiration: expiration,
Extra: map[string]any{
"client_id": result.ClientID,
},
}, nil
}
}
// =============================================================================
// Server handlers
// =============================================================================
func completionHandler(ctx context.Context, req *mcp.CompleteRequest) (*mcp.CompleteResult, error) {
// Return empty completion - just acknowledging the capability
return &mcp.CompleteResult{
Completion: mcp.CompletionResultDetails{
Values: []string{},
Total: 0,
},
}, nil
}
func subscribeHandler(ctx context.Context, req *mcp.SubscribeRequest) error {
// The SDK handles subscription tracking internally via Server.ResourceUpdated()
return nil
}
func unsubscribeHandler(ctx context.Context, req *mcp.UnsubscribeRequest) error {
// The SDK handles subscription tracking internally
return nil
}
// =============================================================================
// Helper functions
// =============================================================================
// Base64-encoded minimal test files, copied from the typescript conformance example.
const (
// Minimal 1x1 red PNG image
testImageBase64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFBQIAX8jx0gAAAABJRU5ErkJggg=="
// Minimal WAV audio file (silence)
testAudioBase64 = "UklGRiYAAABXQVZFZm10IBAAAAABAAEAQB8AAAB9AAACABAAZGF0YQIAAAA="
)
func imageData() []byte {
data, err := base64.StdEncoding.DecodeString(testImageBase64)
if err != nil {
panic("invalid testImageBase64: " + err.Error())
}
return data
}
func audioData() []byte {
data, err := base64.StdEncoding.DecodeString(testAudioBase64)
if err != nil {
panic("invalid testAudioBase64: " + err.Error())
}
return data
}