| 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 |
| 6 | |
| 7 | import ( |
| 8 | "context" |
| 9 | "encoding/json" |
| 10 | "fmt" |
| 11 | "strings" |
| 12 | |
| 13 | "github.com/google/jsonschema-go/jsonschema" |
| 14 | internaljson "github.com/modelcontextprotocol/go-sdk/internal/json" |
| 15 | ) |
| 16 | |
| 17 | // A ToolHandler handles a call to tools/call. |
| 18 | // |
| 19 | // This is a low-level API, for use with [Server.AddTool]. It does not do any |
| 20 | // pre- or post-processing of the request or result: the params contain raw |
| 21 | // arguments, no input validation is performed, and the result is returned to |
| 22 | // the user as-is, without any validation of the output. |
| 23 | // |
| 24 | // Most users will write a [ToolHandlerFor] and install it with the generic |
| 25 | // [AddTool] function. |
| 26 | // |
| 27 | // If ToolHandler returns an error, it is treated as a protocol error. By |
| 28 | // contrast, [ToolHandlerFor] automatically populates [CallToolResult.IsError] |
| 29 | // and [CallToolResult.Content] accordingly. |
| 30 | type ToolHandler func(context.Context, *CallToolRequest) (*CallToolResult, error) |
| 31 | |
| 32 | // A ToolHandlerFor handles a call to tools/call with typed arguments and results. |
| 33 | // |
| 34 | // Use [AddTool] to add a ToolHandlerFor to a server. |
| 35 | // |
| 36 | // Unlike [ToolHandler], [ToolHandlerFor] provides significant functionality |
| 37 | // out of the box, and enforces that the tool conforms to the MCP spec: |
| 38 | // - The In type provides a default input schema for the tool, though it may |
| 39 | // be overridden in [AddTool]. |
| 40 | // - The input value is automatically unmarshaled from req.Params.Arguments. |
| 41 | // - The input value is automatically validated against its input schema. |
| 42 | // Invalid input is rejected before getting to the handler. |
| 43 | // - If the Out type is not the empty interface [any], it provides the |
| 44 | // default output schema for the tool (which again may be overridden in |
| 45 | // [AddTool]). |
| 46 | // - The Out value is used to populate result.StructuredOutput. |
| 47 | // - If [CallToolResult.Content] is unset, it is populated with the JSON |
| 48 | // content of the output. |
| 49 | // - An error result is treated as a tool error, rather than a protocol |
| 50 | // error, and is therefore packed into CallToolResult.Content, with |
| 51 | // [IsError] set. |
| 52 | // |
| 53 | // For these reasons, most users can ignore the [CallToolRequest] argument and |
| 54 | // [CallToolResult] return values entirely. In fact, it is permissible to |
| 55 | // return a nil CallToolResult, if you only care about returning a output value |
| 56 | // or error. The effective result will be populated as described above. |
| 57 | type ToolHandlerFor[In, Out any] func(_ context.Context, request *CallToolRequest, input In) (result *CallToolResult, output Out, _ error) |
| 58 | |
| 59 | // A serverTool is a tool definition that is bound to a tool handler. |
| 60 | type serverTool struct { |
| 61 | tool *Tool |
| 62 | handler ToolHandler |
| 63 | } |
| 64 | |
| 65 | // applySchema validates whether data is valid JSON according to the provided |
| 66 | // schema, after applying schema defaults. |
| 67 | // |
| 68 | // Returns the JSON value augmented with defaults. |
| 69 | func applySchema(data json.RawMessage, resolved *jsonschema.Resolved) (json.RawMessage, error) { |
| 70 | // TODO: use reflection to create the struct type to unmarshal into. |
| 71 | // Separate validation from assignment. |
| 72 | |
| 73 | // Use default JSON marshalling for validation. |
| 74 | // |
| 75 | // This avoids inconsistent representation due to custom marshallers, such as |
| 76 | // time.Time (issue #449). |
| 77 | // |
| 78 | // Additionally, unmarshalling into a map ensures that the resulting JSON is |
| 79 | // at least {}, even if data is empty. For example, arguments is technically |
| 80 | // an optional property of callToolParams, and we still want to apply the |
| 81 | // defaults in this case. |
| 82 | // |
| 83 | // TODO(rfindley): in which cases can resolved be nil? |
| 84 | if resolved != nil { |
| 85 | v := make(map[string]any) |
| 86 | if len(data) > 0 { |
| 87 | if err := internaljson.Unmarshal(data, &v); err != nil { |
| 88 | return nil, fmt.Errorf("unmarshaling arguments: %w", err) |
| 89 | } |
| 90 | } |
| 91 | if err := resolved.ApplyDefaults(&v); err != nil { |
| 92 | return nil, fmt.Errorf("applying schema defaults:\n%w", err) |
| 93 | } |
| 94 | if err := resolved.Validate(&v); err != nil { |
| 95 | return nil, err |
| 96 | } |
| 97 | // We must re-marshal with the default values applied. |
| 98 | var err error |
| 99 | data, err = json.Marshal(v) |
| 100 | if err != nil { |
| 101 | return nil, fmt.Errorf("marshalling with defaults: %v", err) |
| 102 | } |
| 103 | } |
| 104 | return data, nil |
| 105 | } |
| 106 | |
| 107 | // validateToolName checks whether name is a valid tool name, reporting a |
| 108 | // non-nil error if not. |
| 109 | func validateToolName(name string) error { |
| 110 | if name == "" { |
| 111 | return fmt.Errorf("tool name cannot be empty") |
| 112 | } |
| 113 | if len(name) > 128 { |
| 114 | return fmt.Errorf("tool name exceeds maximum length of 128 characters (current: %d)", len(name)) |
| 115 | } |
| 116 | // For consistency with other SDKs, report characters in the order the appear |
| 117 | // in the name. |
| 118 | var invalidChars []string |
| 119 | seen := make(map[rune]bool) |
| 120 | for _, r := range name { |
| 121 | if !validToolNameRune(r) { |
| 122 | if !seen[r] { |
| 123 | invalidChars = append(invalidChars, fmt.Sprintf("%q", string(r))) |
| 124 | seen[r] = true |
| 125 | } |
| 126 | } |
| 127 | } |
| 128 | if len(invalidChars) > 0 { |
| 129 | return fmt.Errorf("tool name contains invalid characters: %s", strings.Join(invalidChars, ", ")) |
| 130 | } |
| 131 | return nil |
| 132 | } |
| 133 | |
| 134 | // validToolNameRune reports whether r is valid within tool names. |
| 135 | func validToolNameRune(r rune) bool { |
| 136 | return (r >= 'a' && r <= 'z') || |
| 137 | (r >= 'A' && r <= 'Z') || |
| 138 | (r >= '0' && r <= '9') || |
| 139 | r == '_' || r == '-' || r == '.' |
| 140 | } |