Debian Codegraph @

debian/go/src/github.com/modelcontextprotocol/go-sdk/mcp/server_example_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_test
6
7 import (
8 "context"
9 "fmt"
10 "log"
11 "log/slog"
12 "sync/atomic"
13
14 "github.com/modelcontextprotocol/go-sdk/mcp"
15 )
16
17 // !+prompts
18
19 func Example_prompts() {
20 ctx := context.Background()
21
22 promptHandler := func(ctx context.Context, req *mcp.GetPromptRequest) (*mcp.GetPromptResult, error) {
23 return &mcp.GetPromptResult{
24 Description: "Hi prompt",
25 Messages: []*mcp.PromptMessage{
26 {
27 Role: "user",
28 Content: &mcp.TextContent{Text: "Say hi to " + req.Params.Arguments["name"]},
29 },
30 },
31 }, nil
32 }
33
34 // Create a server with a single prompt.
35 s := mcp.NewServer(&mcp.Implementation{Name: "server", Version: "v0.0.1"}, nil)
36 prompt := &mcp.Prompt{
37 Name: "greet",
38 Arguments: []*mcp.PromptArgument{
39 {
40 Name: "name",
41 Description: "the name of the person to greet",
42 Required: true,
43 },
44 },
45 }
46 s.AddPrompt(prompt, promptHandler)
47
48 // Create a client.
49 c := mcp.NewClient(&mcp.Implementation{Name: "client", Version: "v0.0.1"}, nil)
50
51 // Connect the server and client.
52 t1, t2 := mcp.NewInMemoryTransports()
53 if _, err := s.Connect(ctx, t1, nil); err != nil {
54 log.Fatal(err)
55 }
56 cs, err := c.Connect(ctx, t2, nil)
57 if err != nil {
58 log.Fatal(err)
59 }
60 defer cs.Close()
61
62 // List the prompts.
63 for p, err := range cs.Prompts(ctx, nil) {
64 if err != nil {
65 log.Fatal(err)
66 }
67 fmt.Println(p.Name)
68 }
69
70 // Get the prompt.
71 res, err := cs.GetPrompt(ctx, &mcp.GetPromptParams{
72 Name: "greet",
73 Arguments: map[string]string{"name": "Pat"},
74 })
75 if err != nil {
76 log.Fatal(err)
77 }
78 for _, msg := range res.Messages {
79 fmt.Println(msg.Role, msg.Content.(*mcp.TextContent).Text)
80 }
81 // Output:
82 // greet
83 // user Say hi to Pat
84 }
85
86 // !-prompts
87
88 // !+logging
89
90 func Example_logging() {
91 ctx := context.Background()
92
93 // Create a server.
94 s := mcp.NewServer(&mcp.Implementation{Name: "server", Version: "v0.0.1"}, nil)
95
96 // Create a client that displays log messages.
97 done := make(chan struct{}) // solely for the example
98 var nmsgs atomic.Int32
99 c := mcp.NewClient(
100 &mcp.Implementation{Name: "client", Version: "v0.0.1"},
101 &mcp.ClientOptions{
102 LoggingMessageHandler: func(_ context.Context, r *mcp.LoggingMessageRequest) {
103 m := r.Params.Data.(map[string]any)
104 fmt.Println(m["msg"], m["value"])
105 if nmsgs.Add(1) == 2 { // number depends on logger calls below
106 close(done)
107 }
108 },
109 })
110
111 // Connect the server and client.
112 t1, t2 := mcp.NewInMemoryTransports()
113 ss, err := s.Connect(ctx, t1, nil)
114 if err != nil {
115 log.Fatal(err)
116 }
117 defer ss.Close()
118 cs, err := c.Connect(ctx, t2, nil)
119 if err != nil {
120 log.Fatal(err)
121 }
122 defer cs.Close()
123
124 // Set the minimum log level to "info".
125 if err := cs.SetLoggingLevel(ctx, &mcp.SetLoggingLevelParams{Level: "info"}); err != nil {
126 log.Fatal(err)
127 }
128
129 // Get a slog.Logger for the server session.
130 logger := slog.New(mcp.NewLoggingHandler(ss, nil))
131
132 // Log some things.
133 logger.Info("info shows up", "value", 1)
134 logger.Debug("debug doesn't show up", "value", 2)
135 logger.Warn("warn shows up", "value", 3)
136
137 // Wait for them to arrive on the client.
138 // In a real application, the log messages would appear asynchronously
139 // while other work was happening.
140 <-done
141
142 // Output:
143 // info shows up 1
144 // warn shows up 3
145 }
146
147 // !-logging
148
149 // !+resources
150 func Example_resources() {
151 ctx := context.Background()
152
153 resources := map[string]string{
154 "file:///a": "a",
155 "file:///dir/x": "x",
156 "file:///dir/y": "y",
157 }
158
159 handler := func(_ context.Context, req *mcp.ReadResourceRequest) (*mcp.ReadResourceResult, error) {
160 uri := req.Params.URI
161 c, ok := resources[uri]
162 if !ok {
163 return nil, mcp.ResourceNotFoundError(uri)
164 }
165 return &mcp.ReadResourceResult{
166 Contents: []*mcp.ResourceContents{{URI: uri, Text: c}},
167 }, nil
168 }
169
170 // Create a server with a single resource.
171 s := mcp.NewServer(&mcp.Implementation{Name: "server", Version: "v0.0.1"}, nil)
172 s.AddResource(&mcp.Resource{URI: "file:///a"}, handler)
173 s.AddResourceTemplate(&mcp.ResourceTemplate{URITemplate: "file:///dir/{f}"}, handler)
174
175 // Create a client.
176 c := mcp.NewClient(&mcp.Implementation{Name: "client", Version: "v0.0.1"}, nil)
177
178 // Connect the server and client.
179 t1, t2 := mcp.NewInMemoryTransports()
180 if _, err := s.Connect(ctx, t1, nil); err != nil {
181 log.Fatal(err)
182 }
183 cs, err := c.Connect(ctx, t2, nil)
184 if err != nil {
185 log.Fatal(err)
186 }
187 defer cs.Close()
188
189 // List resources and resource templates.
190 for r, err := range cs.Resources(ctx, nil) {
191 if err != nil {
192 log.Fatal(err)
193 }
194 fmt.Println(r.URI)
195 }
196 for r, err := range cs.ResourceTemplates(ctx, nil) {
197 if err != nil {
198 log.Fatal(err)
199 }
200 fmt.Println(r.URITemplate)
201 }
202
203 // Read resources.
204 for _, path := range []string{"a", "dir/x", "b"} {
205 res, err := cs.ReadResource(ctx, &mcp.ReadResourceParams{URI: "file:///" + path})
206 if err != nil {
207 fmt.Println(err)
208 } else {
209 fmt.Println(res.Contents[0].Text)
210 }
211 }
212 // Output:
213 // file:///a
214 // file:///dir/{f}
215 // a
216 // x
217 // calling "resources/read": Resource not found
218 }
219
220 // !-resources