Debian Codegraph @

debian/go/src/github.com/modelcontextprotocol/go-sdk/mcp/tool_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 "encoding/json"
10 "fmt"
11 "log"
12 "reflect"
13 "time"
14
15 "github.com/google/jsonschema-go/jsonschema"
16 "github.com/modelcontextprotocol/go-sdk/mcp"
17 )
18
19 func ExampleServer_AddTool_rawSchema() {
20 // In some scenarios, you may want your server to be a pass-through, with
21 // JSON schema coming from another source. Or perhaps you want to implement
22 // tool validation using a different JSON schema library.
23 //
24 // For these cases, you can use [mcp.Server.AddTool], which is the "raw" form
25 // of the API. Note that it is the caller's responsibility to validate inputs
26 // and outputs.
27 server := mcp.NewServer(&mcp.Implementation{Name: "server", Version: "v0.0.1"}, nil)
28 server.AddTool(&mcp.Tool{
29 Name: "greet",
30 InputSchema: json.RawMessage(`{"type":"object","properties":{"user":{"type":"string"}}}`),
31 }, func(_ context.Context, req *mcp.CallToolRequest) (*mcp.CallToolResult, error) {
32 // Note: no validation!
33 var args struct{ User string }
34 if err := json.Unmarshal(req.Params.Arguments, &args); err != nil {
35 // TODO: we should use a jsonrpc error here, to be consistent with other
36 // SDKs.
37 return nil, err
38 }
39 return &mcp.CallToolResult{
40 Content: []mcp.Content{&mcp.TextContent{Text: "Hi " + args.User}},
41 }, nil
42 })
43
44 ctx := context.Background()
45 session, err := connect(ctx, server)
46 if err != nil {
47 log.Fatal(err)
48 }
49 defer session.Close()
50
51 res, err := session.CallTool(ctx, &mcp.CallToolParams{
52 Name: "greet",
53 Arguments: map[string]any{"user": "you"},
54 })
55 if err != nil {
56 log.Fatal(err)
57 }
58 fmt.Println(res.Content[0].(*mcp.TextContent).Text)
59 // Output: Hi you
60 }
61
62 func ExampleAddTool_customMarshalling() {
63 // Sometimes when you want to customize the input or output schema for a
64 // tool, you need to customize the schema of a single helper type that's used
65 // in several places.
66 //
67 // For example, suppose you had a type that marshals/unmarshals like a
68 // time.Time, and that type was used multiple times in your tool input.
69 type MyDate struct {
70 time.Time
71 }
72 type Input struct {
73 Query string `json:"query,omitempty"`
74 Start MyDate `json:"start,omitempty"`
75 End MyDate `json:"end,omitempty"`
76 }
77
78 // In this case, you can use jsonschema.For along with jsonschema.ForOptions
79 // to customize the schema inference for your custom type.
80 inputSchema, err := jsonschema.For[Input](&jsonschema.ForOptions{
81 TypeSchemas: map[reflect.Type]*jsonschema.Schema{
82 reflect.TypeFor[MyDate](): {Type: "string"},
83 },
84 })
85 if err != nil {
86 log.Fatal(err)
87 }
88
89 server := mcp.NewServer(&mcp.Implementation{Name: "server", Version: "v0.0.1"}, nil)
90 toolHandler := func(context.Context, *mcp.CallToolRequest, Input) (*mcp.CallToolResult, any, error) {
91 panic("not implemented")
92 }
93 mcp.AddTool(server, &mcp.Tool{Name: "my_tool", InputSchema: inputSchema}, toolHandler)
94
95 ctx := context.Background()
96 session, err := connect(ctx, server) // create an in-memory connection
97 if err != nil {
98 log.Fatal(err)
99 }
100 defer session.Close()
101
102 for t, err := range session.Tools(ctx, nil) {
103 if err != nil {
104 log.Fatal(err)
105 }
106 schemaJSON, err := json.MarshalIndent(t.InputSchema, "", "\t")
107 if err != nil {
108 log.Fatal(err)
109 }
110 fmt.Println(t.Name, string(schemaJSON))
111 }
112 // Output:
113 // my_tool {
114 // "additionalProperties": false,
115 // "properties": {
116 // "end": {
117 // "type": "string"
118 // },
119 // "query": {
120 // "type": "string"
121 // },
122 // "start": {
123 // "type": "string"
124 // }
125 // },
126 // "type": "object"
127 // }
128 }
129
130 type Location struct {
131 Name string `json:"name"`
132 Latitude *float64 `json:"latitude,omitempty"`
133 Longitude *float64 `json:"longitude,omitempty"`
134 }
135
136 type Forecast struct {
137 Forecast string `json:"forecast" jsonschema:"description of the day's weather"`
138 Type WeatherType `json:"type" jsonschema:"type of weather"`
139 Rain float64 `json:"rain" jsonschema:"probability of rain, between 0 and 1"`
140 High float64 `json:"high" jsonschema:"high temperature"`
141 Low float64 `json:"low" jsonschema:"low temperature"`
142 }
143
144 type WeatherType string
145
146 const (
147 Sunny WeatherType = "sun"
148 PartlyCloudy WeatherType = "partly_cloudy"
149 Cloudy WeatherType = "clouds"
150 Rainy WeatherType = "rain"
151 Snowy WeatherType = "snow"
152 )
153
154 type Probability float64
155
156 // !+weathertool
157
158 type WeatherInput struct {
159 Location Location `json:"location" jsonschema:"user location"`
160 Days int `json:"days" jsonschema:"number of days to forecast"`
161 }
162
163 type WeatherOutput struct {
164 Summary string `json:"summary" jsonschema:"a summary of the weather forecast"`
165 Confidence Probability `json:"confidence" jsonschema:"confidence, between 0 and 1"`
166 AsOf time.Time `json:"asOf" jsonschema:"the time the weather was computed"`
167 DailyForecast []Forecast `json:"dailyForecast" jsonschema:"the daily forecast"`
168 Source string `json:"source,omitempty" jsonschema:"the organization providing the weather forecast"`
169 }
170
171 func WeatherTool(ctx context.Context, req *mcp.CallToolRequest, in WeatherInput) (*mcp.CallToolResult, WeatherOutput, error) {
172 perfectWeather := WeatherOutput{
173 Summary: "perfect",
174 Confidence: 1.0,
175 AsOf: time.Now(),
176 }
177 for range in.Days {
178 perfectWeather.DailyForecast = append(perfectWeather.DailyForecast, Forecast{
179 Forecast: "another perfect day",
180 Type: Sunny,
181 Rain: 0.0,
182 High: 72.0,
183 Low: 72.0,
184 })
185 }
186 return nil, perfectWeather, nil
187 }
188
189 // !-weathertool
190
191 func ExampleAddTool_complexSchema() {
192 // This example demonstrates a tool with a more 'realistic' input and output
193 // schema. We use a combination of techniques to tune our input and output
194 // schemas.
195
196 // !+customschemas
197
198 // Distinguished Go types allow custom schemas to be reused during inference.
199 customSchemas := map[reflect.Type]*jsonschema.Schema{
200 reflect.TypeFor[Probability](): {Type: "number", Minimum: jsonschema.Ptr(0.0), Maximum: jsonschema.Ptr(1.0)},
201 reflect.TypeFor[WeatherType](): {Type: "string", Enum: []any{Sunny, PartlyCloudy, Cloudy, Rainy, Snowy}},
202 }
203 opts := &jsonschema.ForOptions{TypeSchemas: customSchemas}
204 in, err := jsonschema.For[WeatherInput](opts)
205 if err != nil {
206 log.Fatal(err)
207 }
208
209 // Furthermore, we can tweak the inferred schema, in this case limiting
210 // forecasts to 0-10 days.
211 daysSchema := in.Properties["days"]
212 daysSchema.Minimum = jsonschema.Ptr(0.0)
213 daysSchema.Maximum = jsonschema.Ptr(10.0)
214
215 // Output schema inference can reuse our custom schemas from input inference.
216 out, err := jsonschema.For[WeatherOutput](opts)
217 if err != nil {
218 log.Fatal(err)
219 }
220
221 // Now add our tool to a server. Since we've customized the schemas, we need
222 // to override the default schema inference.
223 server := mcp.NewServer(&mcp.Implementation{Name: "server", Version: "v0.0.1"}, nil)
224 mcp.AddTool(server, &mcp.Tool{
225 Name: "weather",
226 InputSchema: in,
227 OutputSchema: out,
228 }, WeatherTool)
229
230 // !-customschemas
231
232 ctx := context.Background()
233 session, err := connect(ctx, server) // create an in-memory connection
234 if err != nil {
235 log.Fatal(err)
236 }
237 defer session.Close()
238
239 // Check that the client observes the correct schemas.
240 for t, err := range session.Tools(ctx, nil) {
241 if err != nil {
242 log.Fatal(err)
243 }
244 // Formatting the entire schemas would be too much output.
245 // Just check that our customizations were effective.
246 fmt.Println("max days:", jsonPath(t.InputSchema, "properties", "days", "maximum"))
247 fmt.Println("max confidence:", jsonPath(t.OutputSchema, "properties", "confidence", "maximum"))
248 fmt.Println("weather types:", jsonPath(t.OutputSchema, "properties", "dailyForecast", "items", "properties", "type", "enum"))
249 }
250 // Output:
251 // max days: 10
252 // max confidence: 1
253 // weather types: [sun partly_cloudy clouds rain snow]
254 }
255
256 func connect(ctx context.Context, server *mcp.Server) (*mcp.ClientSession, error) {
257 t1, t2 := mcp.NewInMemoryTransports()
258 if _, err := server.Connect(ctx, t1, nil); err != nil {
259 return nil, err
260 }
261 client := mcp.NewClient(&mcp.Implementation{Name: "client", Version: "v0.0.1"}, nil)
262 return client.Connect(ctx, t2, nil)
263 }
264
265 func jsonPath(s any, path ...string) any {
266 if len(path) == 0 {
267 return s
268 }
269 return jsonPath(s.(map[string]any)[path[0]], path[1:]...)
270 }