Every agent invocation currently pays ~22K+ tokens of overhead before the AI even reads the user's message: ~15K for the monolithic system prompt (workspace/CLAUDE.md) + ~7K for 38 tool schemas. A simple "remind me at 5pm" loads Gmail patterns, canvas widget JSON examples, data table schemas, workflow pipeline docs, and 31 tools it will never use. Multi-widget dashboards require 5-6 sequential LLM turns for what should be 1. Long conversations accumulate unbounded context.
The goal: make the framework faster, more reliable, and more token-efficient so the AI can do more with less.
Improvement 1: Modular System Prompt via MCP Resources
~7-11K tokens saved per invocation (47-73% reduction) | Low complexity
Split workspace/CLAUDE.md into a lean core (~150 lines, ~4K tokens) plus on-demand guide resources the agent reads only when needed.
Keep in CLAUDE.md (core):
Persona, philosophy, critical rules (lines 1-45)
Condensed tool table — name + one-liner only, no examples (lines 48-87)
Available models list (lines 387-405)
New "Reference Guides" section listing resource URIs
Extract to workspace/guides/*.md, served as MCP resources:
Resource URI
Content
When read
guide://gmail
Gmail patterns, query syntax
Email requests
guide://canvas
Canvas components, widgets, JSON examples, data binding, action buttons
Page/dashboard/widget requests
guide://data-tables
Table creation, CRUD, column types
Data/table requests
guide://documents
Upload, parsing, creation
File/document requests
guide://approvals
Approval gates, workflow integration
Approval requests
guide://automation
Triggers, workflows, step types
Automation requests
guide://design-system
CSS tokens, component classes, Tailwind
Building HTML
guide://python
Python execution, virtualenv, skills
Python requests
Files:
workspace/CLAUDE.md — trim to core
fang/resources/guide_resource.rb — new templated FastMcp::Resource serving guide://{topic}
workspace/guides/*.md — 8 extracted guide files
Improvement 2: Tool Context Groups with Pre-Classification
~4-5K tokens saved per invocation (60-70% tool schema reduction) | Medium complexity
Filter which tools are available per conversation based on context. Most conversations need only 7-13 tools, not 38. Use a cheap/fast model call to classify intent before spawning the full agent.
Before spawning the Claude agent subprocess, make a fast Haiku call (~200ms, ~200 tokens) to classify which tool groups the message needs:
ruby
# fang/tool_classifier.rb
module Fang
module ToolClassifier
GROUPS = %w[gmail canvas data documents automation system].freeze
def self.classify(message, conversation: nil)
# Include recent conversation context for better classification
context = if conversation && conversation.messages.count > 1
recent = conversation.messages.order(created_at: :desc).limit(3).map { |m| "#{m.role}: #{m.truncated_content(100)}" }.reverse.join("\n")
"Recent conversation:\n#{recent}\n\nNew message: #{message}"
else
message
end
response = Anthropic::Client.new.messages(
model: "claude-haiku-4-5-20251001",
max_tokens: 50,
system: "You classify user messages for an AI assistant. Return ONLY a comma-separated list of needed tool groups from: #{GROUPS.join(', ')}. Return 'none' if only basic tools are needed. Be conservative — only include groups clearly needed.",
messages: [{ role: "user", content: context }]
)
groups = response.dig("content", 0, "text").to_s.strip.split(",").map(&:strip)
groups = groups & GROUPS # only allow known groups
[:core] + groups.map(&:to_sym)
rescue => e
Fang.logger.warn "Tool classification failed: #{e.message}, loading all tools"
nil # nil = no filtering, load everything (safe fallback)
end
end
end
Implementation:
Add tool_group class-level DSL to each tool (one line per tool file)
Cumulative effect of 1+2+4: A simple request goes from ~22K overhead tokens to ~5.5K. That's a 75% reduction in per-invocation baseline cost.
Verification
Run rake test after each improvement
Compare token usage before/after via message metadata (total_cost_usd, usage)
Test a "remind me at 5pm" request — should use only core tools, no guides loaded
Test a "build me a dashboard" request — should load canvas guide, use build_canvas tool
Test a 20+ message conversation — should see context compression kick in
If you need specific details from before exiting plan mode (like exact code snippets, error messages, or content you generated), read the full transcript at: /home/greg/.REDACTED.jsonl
Assistant
I'll start by reading the key files I need to understand before implementing. Let me read them in parallel.
Assistant
Let me read a few more key files.
Assistant
Let me read the existing resource pattern and check the MCP SSE route in the web app.
Assistant
Let me check how the MCP SSE endpoint is mounted and look at the update_canvas tool for the build_canvas implementation.
Assistant
Now I have a complete understanding of the codebase. Let me create tasks and start implementing all 5 improvements.
Assistant
Starting with Improvement 1: Modular System Prompt. First, let me create the guide files by extracting content from the current CLAUDE.md, then create the MCP resource, and finally trim CLAUDE.md.
Assistant
Now let me create all the guide files and the resource in parallel.
Assistant
Now create the MCP guide resource and rewrite CLAUDE.md.
Assistant
Now rewrite CLAUDE.md to the lean core version:
Assistant
Improvements 1 & 2 are done (the run_code promotion was integrated into the new CLAUDE.md). Now Improvement 3: build_canvas tool.
Assistant
Now Improvement 4: Tool context groups. This requires: the concern, the classifier, modifications to all tool files, MCP server filter, and agent.rb changes. Let me first check how fast_mcp's filter_tools works.
Assistant
Now I understand the fast_mcp filter_tools API. The filter receives (request, tools_array) and returns filtered tools. Let me check the rack transport to understand what request looks like.
Assistant
Now I understand the full filter_tools API. The filter block receives a Rack::Request object and can read query params. Let me implement all the pieces for tool context groups.
Assistant
Now add tool_group to all tool files. Let me do this efficiently by reading each tool and adding the group line.
Assistant
Good, the tool_group additions are done. Now let me update the MCP server to add the filter_tools block, and modify agent.rb to call the classifier.
Assistant
Now update agent.rb to call the classifier and generate per-conversation .mcp.json:
Assistant
Now I need to make sure the tool_classifier is loaded by bootstrap:
Assistant
Now Improvement 5: Conversation context compression. Need a migration, model changes, and agent.rb modifications.
Assistant
Now add summarization methods to the Conversation model:
Assistant
Now I need to add a call_haiku helper to ToolClassifier for general Haiku calls:
Assistant
Now modify agent.rb to use context compression for long conversations, and update the AgentExecutorJob to trigger summary generation:
Assistant
Now wire build_prompt into the execute methods. I need to apply it before passing to run_claude:
Assistant
Now simplify the run_code return value as mentioned in Improvement 2:
Assistant
Now let's run the migration and tests:
Assistant
Migration ran successfully. Now let's run the tests:
Assistant
The output was truncated. Let me check if tests passed:
Assistant
Two test failures from the run_code return value change. Let me fix the tests:
Assistant
All 283 tests pass with 0 failures. Let me mark the last task complete.
Assistant
All 5 improvements are implemented and all tests pass. Here's a summary of everything that was done:
Summary
Improvement 1: Modular System Prompt via MCP Resources
workspace/CLAUDE.md trimmed from ~500 lines to ~165 lines (~67% reduction)
Created 8 guide files in workspace/guides/: gmail, canvas, data-tables, documents, approvals, automation, design-system, python
Created fang/resources/guide_resource.rb — dynamically registers a guide://{topic} MCP resource for each guide, plus a guide://index listing
Improvement 2: Promote run_code as First-Class Meta-Tool
New "Smart Tool Selection" section in CLAUDE.md guides when to use run_code vs dedicated tools
run_code_tool.rb — simplified return value from {success, result, output} to just {result}
Improvement 3: Batch Canvas Operations
fang/tools/build_canvas_tool.rb — new build_canvas tool creates a page with multiple widgets in one call
Supports grid (2-column), stack (single column), and freeform layouts with auto-positioning
Improvement 4: Tool Context Groups with Pre-Classification
fang/concerns/tool_grouping.rb — tool_group DSL for tool classes
Cumulative effect of 1+2+4: A simple request goes from ~22K overhead tokens to ~5.5K. That's a 75% reduction in per-invocation baseline cost.
Verification
Run rake test after each improvement
Compare token usage before/after via message metadata (total_cost_usd, usage)
Test a "remind me at 5pm" request — should use only core tools, no guides loaded
Test a "build me a dashboard" request — should load canvas guide, use build_canvas tool
Test a 20+ message conversation — should see context compression kick in
If you need specific details from before exiting plan mode (like exact code snippets, error messages, or content you generated), read the full transcript at: /home/greg/.REDACTED.jsonl
User
Improvement 5: Conversation Context Compression
~20-60K tokens saved per long conversation | Medium-high complexity
For conversations exceeding 15 messages, start fresh Claude sessions with an injected summary instead of resuming with full history.
Add context_summary column to conversations table
After crossing message thresholds (15, 30, 50), generate a summary via a cheap Haiku call
When starting a new agent turn on a long conversation, build prompt as: CONVERSATION CONTEXT:\n{summary}\n\nUSER REQUEST:\n{message}
Start a new session instead of resuming (gives us context window control)
Files:
New migration: add_context_summary_to_conversations
fang/tools/build_canvas_tool.rb — new compound tool
workspace/guides/canvas.md — document the tool
User
Improvement 2: Tool Context Groups with Pre-Classification
~4-5K tokens saved per invocation (60-70% tool schema reduction) | Medium complexity
Filter which tools are available per conversation based on context. Most conversations need only 7-13 tools, not 38. Use a cheap/fast model call to classify intent before spawning the full agent.
# fang/tool_classifier.rb
module Fang
module ToolClassifier
GROUPS = %w[gmail canvas data documents automation system].freeze
def self.classify(message, conversation: nil)
# Include recent conversation context for better classification
context = if conversation && conversation.messages.count > 1
recent = conversation.messages.order(created_at: :desc).limit(3).map { |m| "#{m.role}: #{m.truncated_content(100)}" }.reverse.join("\n")
"Recent conversation:\n#{recent}\n\nNew message: #{message}"
else
message
end
response = Anthropic::Client.new.messages(
model: "claude-haiku-4-5-20251001",
max_tokens: 50,
system: "You classify user messages for an AI assistant. Return ONLY a comma-separated list of needed tool groups from: #{GROUPS.join(', ')}. Return 'none' if only basic tools are needed. Be conservative — only include groups clearly needed.",
messages: [{ role: "user", content: context }]
)
groups = response.dig("content", 0, "text").to_s.strip.split(",").map(&:strip)
groups = groups & GROUPS # only allow known groups
[:core] + groups.map(&:to_sym)
rescue => e
Fang.logger.warn "Tool classification failed: #{e.message}, loading all tools"
nil # nil = no filtering, load everything (safe fallback)
end
end
end
Implementation:
Add tool_group class-level DSL to each tool (one line per tool file)