| 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 | "reflect" |
| 9 | "sync" |
| 10 | |
| 11 | "github.com/google/jsonschema-go/jsonschema" |
| 12 | ) |
| 13 | |
| 14 | // A SchemaCache caches JSON schemas to avoid repeated reflection and resolution. |
| 15 | // |
| 16 | // This is useful for stateless server deployments (one [Server] per request) |
| 17 | // where tools are re-registered on every request. Without caching, each |
| 18 | // [AddTool] call triggers expensive reflection-based schema generation. |
| 19 | // |
| 20 | // A SchemaCache is safe for concurrent use by multiple goroutines. |
| 21 | // |
| 22 | // # Trade-offs |
| 23 | // |
| 24 | // The cache is unbounded: it stores one entry per unique Go type or schema |
| 25 | // pointer. For typical MCP servers with a fixed set of tools, memory usage |
| 26 | // is negligible. However, if tool input types are generated dynamically, |
| 27 | // the cache will grow without bound. |
| 28 | // |
| 29 | // The cache uses pointer identity for pre-defined schemas. If a schema's |
| 30 | // contents change but the pointer remains the same, stale resolved schemas |
| 31 | // may be returned. In practice, this is not an issue because tool schemas |
| 32 | // are typically defined once at startup. |
| 33 | type SchemaCache struct { |
| 34 | byType sync.Map // reflect.Type -> *cachedSchema |
| 35 | bySchema sync.Map // *jsonschema.Schema -> *jsonschema.Resolved |
| 36 | } |
| 37 | |
| 38 | type cachedSchema struct { |
| 39 | schema *jsonschema.Schema |
| 40 | resolved *jsonschema.Resolved |
| 41 | } |
| 42 | |
| 43 | // NewSchemaCache creates a new [SchemaCache]. |
| 44 | func NewSchemaCache() *SchemaCache { |
| 45 | return &SchemaCache{} |
| 46 | } |
| 47 | |
| 48 | func (c *SchemaCache) getByType(t reflect.Type) (*jsonschema.Schema, *jsonschema.Resolved, bool) { |
| 49 | if v, ok := c.byType.Load(t); ok { |
| 50 | cs := v.(*cachedSchema) |
| 51 | return cs.schema, cs.resolved, true |
| 52 | } |
| 53 | return nil, nil, false |
| 54 | } |
| 55 | |
| 56 | func (c *SchemaCache) setByType(t reflect.Type, schema *jsonschema.Schema, resolved *jsonschema.Resolved) { |
| 57 | c.byType.Store(t, &cachedSchema{schema: schema, resolved: resolved}) |
| 58 | } |
| 59 | |
| 60 | func (c *SchemaCache) getBySchema(schema *jsonschema.Schema) (*jsonschema.Resolved, bool) { |
| 61 | if v, ok := c.bySchema.Load(schema); ok { |
| 62 | return v.(*jsonschema.Resolved), true |
| 63 | } |
| 64 | return nil, false |
| 65 | } |
| 66 | |
| 67 | func (c *SchemaCache) setBySchema(schema *jsonschema.Schema, resolved *jsonschema.Resolved) { |
| 68 | c.bySchema.Store(schema, resolved) |
| 69 | } |