MCPcopy Create free account
hub / github.com/modelcontextprotocol/go-sdk / ExampleAddTool_complexSchema

Function ExampleAddTool_complexSchema

mcp/tool_example_test.go:191–254  ·  view source on GitHub ↗

!-weathertool

()

Source from the content-addressed store, hash-verified

189// !-weathertool
190
191func 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"))

Callers

nothing calls this directly

Calls 6

NewServerFunction · 0.92
AddToolFunction · 0.92
jsonPathFunction · 0.85
ToolsMethod · 0.80
connectFunction · 0.70
CloseMethod · 0.65

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…