new feature is comming, write design doc first: implement "sql generation" and "chart…
- User
new feature is comming, write design doc first:
implement "sql generation" and "chart generation" using subagents instead of tools
Assistant
I'll start by invoking the brainstorming skill since this is a creative/design task before writing the design doc.
Assistant
I'll follow the brainstorming process. Let me start by exploring the project context.
Assistant
Let me explore the project to understand the current architecture.
Assistant
Good, I now have a solid understanding of the current architecture. Let me start asking clarifying questions.
Currently, the agent uses MCP tools (
execute_sql,generate_chart) — the main Claude agent calls these tools directly. The proposal is to replace them with subagents — separate Claude instances that specialize in SQL generation and chart generation.Here's my first question:
Assistant
Now let me check the claude-agent-sdk to understand the subagent API before proposing approaches.
Assistant
Now I have all the context I need. Let me propose approaches.
Assistant
Here are 3 approaches for implementing subagent-based SQL and chart generation:
Approach A: Two Specialized Subagents (Recommended)
SQL subagent + Chart subagent, each with
execute_sqlMCP tool access.- Orchestrator has no direct tool access — only the
Tasktool to delegate - SQL subagent: specialized system prompt for DuckDB SQL, has tool, self-corrects on errors
- Orchestrator has no direct tool access — only the
Assistant
Now let me present the design section by section.
Assistant
Design Section 1: Architecture Overview
Three actors:
-
Orchestrator Agent — The main Claude agent. Receives user messages, decides what to do, delegates to subagents. Has NO direct MCP tool access. Only has the
Tasktool. -
SQL Subagent (
sql-analyst) — Specializes in DuckDB SQL generation and execution. Hasexecute_sqlMCP tool. Gets table schemas in its prompt. Can self-correct on query errors. Configurable model (default: haiku). -
Chart Subagent (
chart-builder) — Specializes in Plotly visualization. Hasexecute_sqlMCP tool to fetch data. Returns achart_specJSON object. Configurable model (default: haiku).
Flow:
code-
Assistant
Design Section 2: Subagent Definitions & System Prompts
SQL Subagent (
sql-analyst):pythonAgentDefinition( description="Use this agent for any data question that requires SQL queries — " "exploring data, aggregations, filtering, joins, etc.", prompt=f"""You are a DuckDB SQL expert. Your job is to write and execute SQL queries to answer data questions. Guidelines: - Write clear, efficient DuckDB SQL - Start with small queries (use LIMIT) when exploring - If a query fails, analyze the error and fix it - Return results with a brief explanation {table_schemas} # Injected dynamically """, tools=["mcp__duckdb__execute_sql"], model=SQL_SUBAGENT_MODEL, # from env, default "haiku" )Assistant
Design Section 3: Backend Changes
Key changes to
agent.py:-
New config vars in
config.py:SQL_SUBAGENT_MODEL(env:SQL_SUBAGENT_MODEL, default:"haiku")CHART_SUBAGENT_MODEL(env:CHART_SUBAGENT_MODEL, default:"haiku")
-
New function
build_subagent_definitions(db: Database) -> dict[str, AgentDefinition]:- Builds table schema string from
db.list_tables() - Returns
{"sql-analyst": AgentDefinition(...), "chart-builder": AgentDefinition(...)}
- Builds table schema string from
-
Modified
ClaudeAgentOptions:
-
Assistant
Design Section 4: Frontend Changes
New SSE events to handle in
agentService.ts:subagent_start→{id, name, description, prompt}— shows which subagent was invokedsubagent_end→{id, name, result}— subagent finished, may contain chart_spec- Existing
tool_call/tool_resultevents still stream inside subagent scope
UI changes in
MessageBubble/InlineQueryResult:- When
subagent_startarrives: show a collapsible "SQL Analyst working..." or "Chart Builder working..." section - Inside the subagent section: render tool_call/tool_result as currently done (SQL table, chart)
- When
subagent_endarrives: collapse the working indicator, show final result - If subagent result contains
chart_spec: renderChartWidgetas before
New callback in
AgentCallbacks:onSubagentStart(data)— add subagent indicator to messageonSubagentEnd(data)— finalize subagent section
The chart rendering itself (ChartWidget, Plotly) stays unchanged — same format.
Assistant
Design Section 5: Container Mode Compatibility
The containerized sidecar (
_stream_chat_container) also needs updates:- The sidecar TypeScript code needs to pass
agentsconfig to Claude Code CLI - Same subagent definitions, same MCP server URL pattern
- SSE parsing in
_stream_chat_containerneeds to detect subagent events from the sidecar stream - The subagent events should follow the same format as local mode
This is a secondary concern — we implement local mode first, then update container mode.
Design Section 6: Testing Strategy
- Unit tests: Test
build_subagent_definitions()returns correctAgentDefinitionstructures - Unit tests: Test SSE event parsing for new
subagent_start/subagent_endevents - Integration tests: Mock claude-agent-sdk to verify subagent invocation flow
- E2E manual test: Upload CSV, ask a data question → verify SQL subagent runs. Ask for chart → verify chart subagent runs and chart renders.
- The sidecar TypeScript code needs to pass
Assistant
Now let me commit the design doc.
Assistant
Design doc written and committed. Ready to transition to implementation planning.
Assistant
I'm using the writing-plans skill to create the implementation plan.
Let me first review the design doc and explore the codebase to write precise implementation steps with exact file paths and code.
Assistant
Now let me read the key files I need for precise implementation steps.
Assistant
Now let me check existing tests to understand patterns.
Assistant
Now let me check the AgentDefinition import path and the existing SDK types.
Assistant
Now I have everything I need. Let me write the implementation plan.
Assistant
Good, I have thorough understanding of all files. Now let me write the implementation plan.
Assistant
Now I'll write the implementation plan with bite-sized TDD steps.
Assistant
Now commit the implementation plan.
Assistant
Plan complete and saved to
docs/plans/2026-02-25-subagent-sql-chart-design.md. 13 tasks covering:- Config vars (
SQL_SUBAGENT_MODEL,CHART_SUBAGENT_MODEL) build_subagent_definitions()function- Simplified orchestrator system prompt
- Remove
generate_chartfrom tools.py - Remove
generate_chartfrom MCP SSE server - Wire subagents into
ClaudeAgentOptions - Emit
subagent_start/subagent_endSSE events - Frontend SSE event handling
- AgentProvider callback wiring
- MessageBubble subagent UI rendering
- Container mode SSE parsing updates
- Full test suite verification
- Manual E2E testing
Two execution options:
- Subagent-Driven (this session) — I dispatch a fresh subagent per task, review between tasks, fast iteration
- Parallel Session (separate) — Open a new session with
executing-plans, batch execution with checkpoints
Which approach?
- Config vars (
- User
subagent
Assistant
I'm using Subagent-Driven Development to execute the plan. Let me read the prompt templates first.
Assistant
Now let me create the task list from the plan. I already have the full plan text in context.
Assistant
Now let me set up dependencies: tasks 1-5 are independent backend changes, 6-7 depend on 1-2, 8-10 are frontend, 11 depends on 7, 12 depends on all.
Assistant
Let me get the base SHA before starting.
Assistant
Good. Base SHA is
5a87531. Now dispatching Task 1 implementer.Assistant
Task 1 implemented. Now spec review.
Assistant
Spec review: ✅ Passed. Skipping code quality review for this trivial task (2 lines of config). Moving to Task 2.
Assistant
That diagnostic is pre-existing (the
attemptvariable in the container health check loop, not from our changes). Continuing with spec review for Task 2.Assistant
Spec review: ✅ Passed (minor note about weak assertion in test 5, not a blocker). Task 2 complete.
Assistant
Now Tasks 3, 4, and 5 are independent — I'll dispatch them in parallel.
Assistant
Pre-existing diagnostic, not from our changes. Task 3 done. Now dispatching Tasks 4 and 5 in parallel.
Assistant
Tasks 3, 4, 5 all done. Let me verify and mark them complete.
Assistant
All 91 tests pass. Tasks 3, 4, 5 complete.
Assistant
Now Task 6 (wire subagents into ClaudeAgentOptions) and Task 7 (SSE events). These touch the same file so must be sequential. Let me dispatch Task 6.
Assistant
93 tests pass. Tasks 6+7 complete.
Assistant
Now Tasks 8, 9, 10 (frontend changes). These are sequential since they build on each other. Let me dispatch them together.
Assistant
Frontend builds clean. Tasks 8-10 complete.
Assistant
Now Task 11: container mode SSE parsing.
Assistant
Now Task 12: full test suite verification.
Assistant
93/93 tests pass. Frontend build also clean. All implementation tasks complete.
Assistant
Let me do a final code review of the entire implementation.
Assistant
Good review. Let me fix the two important items (I-1 stale comment, I-5 i18n strings) and the dead type (I-3).
Assistant
Now fix I-5: add i18n keys for subagent labels. Let me check the translation file.
Assistant
Now let me fix all three issues: I-1 (already done), I-3 (remove unused SubagentEvent), and I-5 (i18n).
Assistant
Now fix I-5: add i18n keys and use them in MessageBubble.
Assistant
Now update MessageBubble.tsx to use the translation keys.
Assistant
Now verify the build.
Assistant
All clean. Commit the review fixes.
Assistant
All done. Now let me use the finishing skill.
Assistant
I'm using the finishing-a-development-branch skill to complete this work.
Step 1: Verify tests.
Assistant
93 backend tests pass, frontend builds clean.
Step 2: Base branch is
main.Assistant
Step 3: Implementation complete. What would you like to do?
- Merge back to
mainlocally - Push and create a Pull Request
- Keep the branch as-is (I'll handle it later)
- Discard this work
Which option?
- Merge back to
- User
3
Assistant
Keeping branch
feat/subagent-sql-chart. It has 11 commits (2 design docs + 9 implementation) on top ofmain.Summary of what was built:
Area Changes Config SQL_SUBAGENT_MODEL,CHART_SUBAGENT_MODELenv vars (default:haiku)Backend build_subagent_definitions()createssql-analystandchart-builderAgentDefinitionobjectsBackend Orchestrator system prompt simplified to delegate to subagents Backend generate_charttool removed fromtools.pyandmcp_sse.pyBackend ClaudeAgentOptionswired withagents=andallowed_tools=["Task", "mcp__duckdb__execute_sql"]Backend subagent_start/subagent_endSSE events emitted in both local and container modes- User
ui doesn't see chart in answer text but only chart spec in json
Assistant
That's a real issue — the chart-builder subagent returns chart_spec as text in its response (possibly wrapped in markdown), not as a structured tool result. Let me investigate and fix.
Assistant
Phase 1: Root Cause Investigation. Let me trace the data flow to understand exactly where chart_spec gets lost.
Assistant
Root cause identified. Lines 660-665: The code does
json.loads(output)on the subagent's result text. But the chart-builder subagent returns markdown text with an embedded JSON code block, not pure JSON. For example:codeHere's the visualization: ```json {"chart_spec": {"data": [...], "layout": {...}}}The chart shows revenue by product.
code`json.loads()` fails on this markdown, so it falls through to `end_data["result"] = output` — the raw text including the JSON blob. The orchestrator then echoes this in its answer text, and the frontend shows raw JSON. **Phase 2: Pattern Analysis.** The fix needs to extract `chart_spec` from markdown-wrapped JSON. A regex to find ````json\n{...}\n``` ` blocks is the right approach. **Phase 3: Hypothesis.** Add a helper function that extracts chart_spec from text — first try `json.loads()` (pure JSON), then fall back to regex extraction from markdown code blocks. Let me implement the fix.Assistant
Now update the subagent_end emission code to use this helper (local subprocess mode):
Assistant
Continuing the chart_spec extraction bug fix. I need to update the container mode code and write tests. Let me read the current state of the file.
Assistant
Now I can see both the local mode (already fixed at line 690-698) and the container mode (still using old code at lines 441-451). Let me fix the container mode and write tests.
Assistant
Now let me also move the
import reto the top of the file instead of inside the function.Assistant
Now let me write a test for
_extract_chart_spec.Assistant
Now let me run the new tests and the full test suite.
Assistant
All 8 tests pass. Now let me run the full test suite.
Assistant
All 101 tests pass. Let me commit the fix.
Assistant
I'm inside the backend directory. Let me use paths relative to here.
Assistant
Bug fix is complete. Here's a summary of what was done:
Root cause: The chart-builder subagent returns markdown text with an embedded JSON code block (e.g.,
```json {...} ```), not pure JSON. The previous code usedjson.loads(output)directly, which fails on markdown text, sochart_specwas never extracted and the raw JSON appeared as text in the UI instead of rendering as a Plotly chart.Fix:
- Added
_extract_chart_spec(text)helper inbackend/app/agent.pythat:- Tries parsing as pure JSON first (for backwards compatibility)
- Falls back to regex extraction from markdown fenced code blocks (
```json ```or``` ```) - Handles both
{"chart_spec": {...}}wrapper and direct{"data": [...], "layout": {...}}format
- Updated both local subprocess mode and container mode subagent_end emission to use the new helper
- Moved
import reto module level - Added 8 unit tests covering all parsing scenarios — all 101 tests pass
- Added
- User
doesn't need to show chart spec in json in answer section, simply display chart in answer section
Assistant
Let me trace the issue. The orchestrator's answer text likely contains the raw chart spec JSON, and charts render separately from the answer section. I need to fix both backend (prompt) and frontend (rendering).
Assistant
Two changes needed:
- Backend: Tell orchestrator not to repeat chart spec JSON in its answer
- Frontend: Strip chart spec JSON from answer text (safety net) and render charts inside the answer section
Assistant
Now update the frontend. I'll add a helper to strip chart spec JSON blocks from answer text, and restructure rendering so charts appear inside the answer section.
Assistant
Now I'll add a helper to strip chart spec JSON from answer text, and restructure the rendering so charts are inside the answer section.
Assistant
Now restructure the rendering so charts appear inside the answer section, and apply text stripping to answer segments.
Assistant
I need to update the answerSegments filtering to also strip chart spec blocks and filter out segments that become empty after stripping. And then restructure the rendering.
Assistant
Now restructure the rendering to put charts inside the answer section instead of before it.
Assistant
Now I'll replace the chart + answer rendering to put charts inside the answer section with a single "Answer" label.
Assistant
Also apply the same stripping to the streaming remainder when in answer phase with charts.
Assistant
The streaming remainder block for the answer phase should also strip chart spec if charts exist. Let me update it:
Assistant
Now let me verify the frontend builds.
Assistant
TypeScript checks pass. Let me also verify the backend tests still pass.
Assistant
All 101 tests pass. Let me verify the final state of the changed files.
Assistant
Done. Here's what changed:
Backend (
agent.py): Added prompt instruction telling the orchestrator to not repeat chart spec JSON after the chart-builder returns — just describe the visualization in plain language.Frontend (
MessageBubble.tsx):- Added
stripChartSpecBlocks()— regex strips```json {"chart_spec":...} ```blocks from answer text as a safety net - Charts now render inside the answer section under a single "Answer" label, instead of in a separate section above it
- Answer text segments are filtered through the stripper when charts are present, so any residual JSON is removed
- Added