Class: RailsAiBridge::ToolResultCache
- Inherits:
-
Object
- Object
- RailsAiBridge::ToolResultCache
- Defined in:
- lib/rails_ai_bridge/tool_result_cache.rb
Overview
Caches MCP tool call results keyed by a stable fingerprint of the arguments.
The cache is in-memory, per-process, and TTL-based. It ignores server_context
when fingerprinting so identical client requests share the same cached response.
Enable by setting config.mcp.tool_result_cache_ttl to a positive number of seconds.
Defined Under Namespace
Classes: CachedTool
Class Method Summary collapse
-
.enabled? ⇒ Boolean
Whether tool result caching is enabled.
-
.fetch_response(tool_name, arguments) ⇒ MCP::Tool::Response
Fetches a cached response or yields to compute it.
-
.maybe_wrap(tool_class) ⇒ Class, CachedTool
Wraps a tool class if caching is enabled; otherwise returns the class unchanged.
-
.reset! ⇒ void
Clears all cached tool results.
-
.wrap(tool_class) ⇒ CachedTool
Wraps a tool class so every call goes through the cache.
Class Method Details
.enabled? ⇒ Boolean
Returns whether tool result caching is enabled.
112 113 114 |
# File 'lib/rails_ai_bridge/tool_result_cache.rb', line 112 def enabled? RailsAiBridge.configuration.mcp.tool_result_cache_ttl.to_i.positive? end |
.fetch_response(tool_name, arguments) ⇒ MCP::Tool::Response
Fetches a cached response or yields to compute it.
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 |
# File 'lib/rails_ai_bridge/tool_result_cache.rb', line 83 def fetch_response(tool_name, arguments) return yield unless enabled? key = cache_key(tool_name, arguments) fingerprint = key.split(':', 2).last mutex.synchronize do entry = cache[key] if entry && ttl_valid?(entry) Instrumentation.instrument('tool.result_cache_hit', tool_name: tool_name, fingerprint: fingerprint) return entry[:response] end end Instrumentation.instrument('tool.result_cache_miss', tool_name: tool_name, fingerprint: fingerprint) do response = yield mutex.synchronize { cache[key] = { response: response, fetched_at: monotonic_now } } response end end |
.maybe_wrap(tool_class) ⇒ Class, CachedTool
Wraps a tool class if caching is enabled; otherwise returns the class unchanged.
65 66 67 |
# File 'lib/rails_ai_bridge/tool_result_cache.rb', line 65 def maybe_wrap(tool_class) enabled? ? wrap(tool_class) : tool_class end |
.reset! ⇒ void
This method returns an undefined value.
Clears all cached tool results.
107 108 109 |
# File 'lib/rails_ai_bridge/tool_result_cache.rb', line 107 def reset! mutex.synchronize { @cache = {} } end |
.wrap(tool_class) ⇒ CachedTool
Wraps a tool class so every call goes through the cache.
73 74 75 |
# File 'lib/rails_ai_bridge/tool_result_cache.rb', line 73 def wrap(tool_class) CachedTool.new(tool_class) end |