Skip to content

Tool Schema Builder — Go source

Build function-calling and MCP tool schemas that pass strict mode on the first try, and lint pasted ones against the strict-mode contract — additionalProperties, required-sync, defaults, enums — with one-click autofix for every mechanical violation. Runs entirely in your browser.

This is the Go implementation — the same logic the interactive tool runs, in a shareable, citable form.

// Package toolschema is the Go twin of CosmoDev's
// src/lib/tool-schema.ts (dual source: web lib TypeScript, CLI lib Go —
// kept in lock-step). Strict-mode JSON Schema rules for function-calling
// and MCP tool definitions: validate a definition, autofix the mechanical
// violations, or build a compliant definition from parameter rows. Pure +
// total: garbage input yields issues, never a panic. The rule table in the
// tool README mirrors these IDs one-to-one.
package toolschema

import (
	"encoding/json"
	"slices"
)

// Rule identifies one strict-mode check.
type Rule string

const (
	RuleJSONParseable          Rule = "json-parseable"
	RuleNonEmptyName           Rule = "non-empty-name"
	RuleDescriptionPresent     Rule = "description-present"
	RuleNoAdditionalProperties Rule = "no-additional-properties"
	RuleAllRequired            Rule = "all-required"
	RuleNoDefaults             Rule = "no-defaults"
	RuleTypedProperties        Rule = "typed-properties"
	RuleEnumValues             Rule = "enum-values"
	RuleArrayItems             Rule = "array-items"
)

// SupportedTypes mirrors the TS SUPPORTED_TYPES set.
var SupportedTypes = []string{"string", "number", "integer", "boolean", "object", "array"}

// Issue is one rule violation at a path.
type Issue struct {
	Rule    Rule
	Path    string
	Message string
}

// ValidateResult mirrors the TS ValidateResult (ParseError "" = ok).
type ValidateResult struct {
	ParseError string
	Issues     []Issue
}

// AutoStrictResult mirrors the TS AutoStrictResult (Fixed is JSON text).
type AutoStrictResult struct {
	ParseError string
	Fixed      string
	Fixes      []string
}

// ParamDef mirrors the TS ParamDef.
type ParamDef struct {
	Name        string
	Type        string
	Description string
}

// BuildDef is the buildToolSchema input.
type BuildDef struct {
	Name        string
	Description string
	Params      []ParamDef
}

func isObj(v any) bool {
	_, ok := v.(map[string]any)
	return ok
}

func asObj(v any) map[string]any {
	if m, ok := v.(map[string]any); ok {
		return m
	}
	return nil
}

func supported(typeName any) bool {
	s, ok := typeName.(string)
	if !ok {
		return false
	}
	return slices.Contains(SupportedTypes, s)
}

func checkObject(path string, obj map[string]any, issues *[]Issue) {
	if obj["additionalProperties"] != false {
		*issues = append(*issues, Issue{RuleNoAdditionalProperties, path,
			path + ": set additionalProperties: false (strict mode requires it on every object)"})
	}
	props := asObj(obj["properties"])
	keys := make([]string, 0, len(props))
	for k := range props {
		keys = append(keys, k)
	}
	requiredSet := map[string]bool{}
	if arr, ok := obj["required"].([]any); ok {
		for _, r := range arr {
			if s, ok := r.(string); ok {
				requiredSet[s] = true
			}
		}
	}
	missing := false
	for _, k := range keys {
		if !requiredSet[k] {
			missing = true
		}
	}
	if missing {
		*issues = append(*issues, Issue{RuleAllRequired, path,
			path + ": required must list every property"})
	}
	for _, k := range keys {
		propPath := path + ".properties." + k
		prop := asObj(props[k])
		if prop == nil {
			continue
		}
		if _, has := prop["default"]; has {
			*issues = append(*issues, Issue{RuleNoDefaults, propPath,
				propPath + ": strict mode rejects defaults — remove the default key"})
		}
		if d, ok := prop["description"].(string); !ok || len(trim(d)) == 0 {
			*issues = append(*issues, Issue{RuleDescriptionPresent, propPath,
				propPath + ": every property needs a description"})
		}
		if !supported(prop["type"]) {
			*issues = append(*issues, Issue{RuleTypedProperties, propPath,
				propPath + ": property type must be one of the supported types"})
		}
		if enum, ok := prop["enum"].([]any); ok {
			if len(enum) == 0 {
				*issues = append(*issues, Issue{RuleEnumValues, propPath, propPath + ": enum must not be empty"})
			} else {
				kinds := map[string]bool{}
				for _, v := range enum {
					switch v.(type) {
					case string:
						kinds["string"] = true
					case float64:
						kinds["number"] = true
					case bool:
						kinds["bool"] = true
					default:
						kinds["other"] = true
					}
				}
				if len(kinds) > 1 || kinds["other"] {
					*issues = append(*issues, Issue{RuleEnumValues, propPath, propPath + ": enum values must share one primitive type"})
				}
			}
		}
		if t, _ := prop["type"].(string); t == "array" && !isObj(prop["items"]) {
			*issues = append(*issues, Issue{RuleArrayItems, propPath, propPath + ": arrays must declare items with a type"})
		}
		if t, _ := prop["type"].(string); t == "object" {
			if nested := asObj(prop); nested != nil {
				if _, hasProps := nested["properties"]; hasProps {
					checkObject(propPath, nested, issues)
				}
			}
		}
	}
}

func trim(s string) string {
	start, end := 0, len(s)
	for start < end && (s[start] == ' ' || s[start] == '\t' || s[start] == '\n' || s[start] == '\r') {
		start++
	}
	for end > start && (s[end-1] == ' ' || s[end-1] == '\t' || s[end-1] == '\n' || s[end-1] == '\r') {
		end--
	}
	return s[start:end]
}

func validName(name any) bool {
	s, ok := name.(string)
	if !ok || len(s) < 1 || len(s) > 64 {
		return false
	}
	for _, r := range s {
		if !(r >= 'a' && r <= 'z' || r >= '0' && r <= '9' || r == '_' || r == '-') {
			return false
		}
	}
	return true
}

// ValidateToolSchema validates a JSON tool definition ({name, description, input_schema}).
func ValidateToolSchema(input string) ValidateResult {
	var parsed any
	if err := json.Unmarshal([]byte(input), &parsed); err != nil {
		return ValidateResult{ParseError: err.Error()}
	}
	root := asObj(parsed)
	if root == nil {
		return ValidateResult{Issues: []Issue{{RuleJSONParseable, "$", "Input must be a JSON object"}}}
	}
	var issues []Issue
	if !validName(root["name"]) {
		issues = append(issues, Issue{RuleNonEmptyName, "name",
			"name must be 1-64 chars of [a-z0-9_-] (the get_weather convention)"})
	}
	if d, ok := root["description"].(string); !ok || len(trim(d)) == 0 {
		issues = append(issues, Issue{RuleDescriptionPresent, "description", "The tool needs a description"})
	}
	schema := asObj(root["input_schema"])
	if schema != nil && schema["type"] == "object" {
		checkObject("input_schema", schema, &issues)
	} else {
		issues = append(issues, Issue{RuleJSONParseable, "input_schema",
			`input_schema must be an object with type: "object"`})
	}
	return ValidateResult{Issues: issues}
}

func strictObject(obj map[string]any, path string, fixes *[]string) {
	if obj["additionalProperties"] != false {
		obj["additionalProperties"] = false
		*fixes = append(*fixes, "added additionalProperties: false at "+path)
	}
	props := asObj(obj["properties"])
	if props != nil {
		keys := make([]string, 0, len(props))
		for k := range props {
			keys = append(keys, k)
		}
		requiredSet := map[string]bool{}
		rawRequired, _ := obj["required"].([]any)
		for _, r := range rawRequired {
			if s, ok := r.(string); ok {
				requiredSet[s] = true
			}
		}
		missing := false
		for _, k := range keys {
			if !requiredSet[k] {
				missing = true
			}
		}
		if missing || len(requiredSet) != len(rawRequired) {
			all := make([]any, len(keys))
			for i, k := range keys {
				all[i] = k
			}
			obj["required"] = all
			*fixes = append(*fixes, "synced required at "+path)
		}
		for _, k := range keys {
			prop := asObj(props[k])
			if prop == nil {
				continue
			}
			if _, has := prop["default"]; has {
				delete(prop, "default")
				*fixes = append(*fixes, "removed default at "+path+".properties."+k)
			}
			if t, _ := prop["type"].(string); t == "object" {
				if nested := asObj(prop); nested != nil {
					if _, has := nested["properties"]; has {
						strictObject(nested, path+".properties."+k, fixes)
					}
				}
			}
		}
	}
}

// AutoStrict fixes the mechanical violations. Never invents names or copy. Idempotent.
func AutoStrict(input string) AutoStrictResult {
	var parsed any
	if err := json.Unmarshal([]byte(input), &parsed); err != nil {
		return AutoStrictResult{ParseError: err.Error()}
	}
	root := asObj(parsed)
	if root == nil {
		return AutoStrictResult{}
	}
	var fixes []string
	if schema := asObj(root["input_schema"]); schema != nil {
		strictObject(schema, "input_schema", &fixes)
	}
	out, err := json.MarshalIndent(root, "", "  ")
	if err != nil {
		return AutoStrictResult{ParseError: err.Error()}
	}
	return AutoStrictResult{Fixed: string(out), Fixes: fixes}
}

// BuildToolSchema builds a fully strict definition from param rows; empty names are skipped.
func BuildToolSchema(def BuildDef) string {
	type prop struct {
		Type        string `json:"type"`
		Description string `json:"description"`
	}
	real := make([]ParamDef, 0, len(def.Params))
	for _, p := range def.Params {
		if len(trim(p.Name)) > 0 {
			real = append(real, p)
		}
	}
	props := make(map[string]prop, len(real))
	names := make([]string, 0, len(real))
	for _, p := range real {
		desc := trim(p.Description)
		if desc == "" {
			desc = trim(p.Name) + " parameter"
		}
		props[trim(p.Name)] = prop{Type: p.Type, Description: desc}
		names = append(names, trim(p.Name))
	}
	namesJSON, _ := json.Marshal(names)
	propsJSON, _ := json.Marshal(props)
	return `{"name":` + quote(def.Name) + `,"description":` + quote(def.Description) +
		`,"input_schema":{"type":"object","properties":` + string(propsJSON) +
		`,"required":` + string(namesJSON) + `,"additionalProperties":false}}`
}

func quote(s string) string {
	b, _ := json.Marshal(s)
	return string(b)
}

Also available in 14 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →