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

Function ExampleAddTool_customMarshalling

mcp/tool_example_test.go:62–128  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

60}
61
62func 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": {

Callers

nothing calls this directly

Calls 5

NewServerFunction · 0.92
AddToolFunction · 0.92
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…