{
    "componentChunkName": "component---src-templates-blog-template-js",
    "path": "/blog/solving-agent-tool-sprawl-with-dspy-building-a-shopify-scout-like-system",
    "result": {"data":{"markdownRemark":{"html":"<p><em>This is part 5 in a series of posts about differentiable programming for dynamic workflows using DSPy. <a href=\"https://github.com/viksit/differentiable-programming/blob/main/post5-dspy-orchestration-tool-sprawl.py\" target=\"_blank\" rel=\"noopener noreferrer\">The code is available here</a>.</em></p>\n<p class=\"article-image article-image--lead\"><a href=\"/images/substack/bd6b79cab3d42527a4071c2e.png\"><img src=\"/images/substack/bd6b79cab3d42527a4071c2e.png\" alt=\"\"></a></p>\n<p>Two months ago, <a href=\"https://x.com/tobi/status/1958244700189790549\" target=\"_blank\" rel=\"noopener noreferrer\">Tobi Lütke tweeted about Scout</a>, Shopify’s internal research tool:</p>\n<p>“<em>Scout has indexed hundreds of millions of merchant feedback items from Social posts, video feedback, and all our customer support channels. Then it makes it available (via MCP) in our internal librechat tool for deep research. I use it all the time.</em>“</p>\n<p>The interesting question isn’t what Scout does — aggregating data sources is table stakes after all. It is <em>how well</em> does it route queries intelligently across those sources?</p>\n<p>Because here’s what happens when you don’t solve routing: your LLM sees 15 tools, picks the wrong ones, and your only debugging mechanism is rewriting prompts and hoping vibes carry you through.</p>\n<p>I’m calling this the <strong>Agent Tool Sprawl Problem</strong>, and it’s why most multi-tool agents feel unreliable in production.</p>\n<p>In this post, we’ll see how to solve this via DSPy, and build a toy version of Shopify’s scout via DSPy orchestration.</p>\n<h2><strong>The Tool Sprawl Problem</strong></h2>\n<p>Here’s the architecture most teams build first.</p>\n<p>You expose all your tools via MCP. The base model sees everything. When a question comes in, it picks which tools to call. <strong>But you have no control layer.</strong> When it picks wrong, you add examples to the prompt. Then more examples. Then ALL CAPS WARNINGS. The model keeps improvising because the fundamental issue isn’t the prompt — it’s that you’ve delegated architectural decisions to a general-purpose model that doesn’t know your system.</p>\n<ul>\n<li>The model can’t learn from mistakes.</li>\n<li>You can’t see why it chose Tool X over Tool Y.</li>\n<li>You can’t A/B test routing strategies.</li>\n</ul>\n<p>You’re basically debugging by vibes.</p>\n<h2><strong>The Fix: Orchestration Layer + Intent-Based Routing</strong></h2>\n<p>Here’s what changes when you add a control layer.</p>\n<p class=\"article-image\"><a href=\"/images/substack/c35e34d86e34310a9936c315.png\"><img src=\"/images/substack/c35e34d86e34310a9936c315.png\" alt=\"\"></a></p>\n<p>The tools don’t change. But now there’s an <strong>orchestration layer</strong> that decides which tools to call, in what order, and how to combine results. This layer is:</p>\n<ul>\n<li><strong>Observable</strong> – You can see every routing decision</li>\n<li><strong>Programmable</strong> – You can modify the logic in code</li>\n<li><strong>Optimizable</strong> – You can improve it with data (Part 2)</li>\n</ul>\n<p>Let me show you how to build this, starting simple and adding sophistication.</p>\n<h2><strong>Step 1: Intent-Based Routing</strong></h2>\n<p>Let’s try an experiment. Instead of organizing by domain (Engineering vs Analytics), organize by <em>operation type</em>. Every query against your data sources falls into one of three intents:</p>\n<ul>\n<li><strong>search</strong> – Find relevant items using keywords (”find P0 tickets”)</li>\n<li><strong>retrieve</strong> – Get specific items by ID (”get details for SHOP-2847”)</li>\n<li><strong>analyze</strong> – Examine metrics and trends (”how are conversions trending?”)</li>\n</ul>\n<p>This is more powerful than domain-based routing because the same question might require multiple intents. “<em>Find P0 tickets and get details</em>“ requires both search <em>and</em> retrieve.</p>\n<p>Here’s how we define these agents.</p>\n<deckgo-highlight-code   >\n          <code slot=\"code\">class SearchQuery(dspy.Signature):\n    “”“Search for relevant information in Jira tickets and Confluence docs.”“”\n    question: str = dspy.InputField()\n    context: str = dspy.InputField(desc=”Results from previous steps (if any)”)\n    answer: str = dspy.OutputField(desc=”Summary of search results”)\n\nclass SearchAgent(dspy.Module):\n    “”“Specialized agent for searching (finding information).”“”\n    def __init__(self):\n        super().__init__()\n        self.react = dspy.ReAct(\n            signature=SearchQuery,\n            tools=[search_jira, search_confluence],\n            max_iters=4\n        )\n\n    def forward(self, question: str, context: str = “”):\n        result = self.react(question=question, context=context or “No previous context”)\n        return dspy.Prediction(answer=result.answer)</code>\n        </deckgo-highlight-code>\n<p>Notice two things:</p>\n<ol>\n<li><strong>ReAct pattern</strong> – The agent can reason and call tools iteratively. It’s not just “call this tool then that tool.” It can decide <em>which</em> tools to call based on what it learns.</li>\n<li><strong>Context parameter</strong> – This is crucial for multi-step queries. The agent receives results from previous steps, so it can build on prior work.</li>\n</ol>\n<p>The other two agents follow the same pattern.</p>\n<deckgo-highlight-code   >\n          <code slot=\"code\">class RetrieveQuery(dspy.Signature):\n    “”“Retrieve detailed information for specific tickets or documents.”“”\n    question: str = dspy.InputField()\n    context: str = dspy.InputField(desc=”Results from previous steps (if any)”)\n    answer: str = dspy.OutputField(desc=”Detailed information from retrieved items”)\n\nclass RetrieveAgent(dspy.Module):\n    “”“Specialized agent for retrieving (getting specific items by ID).”“”\n    def __init__(self):\n        super().__init__()\n        self.react = dspy.ReAct(\n            signature=RetrieveQuery,\n            tools=[get_ticket_details, get_confluence_doc],\n            max_iters=3\n        )\n\n    def forward(self, question: str, context: str = “”):\n        result = self.react(question=question, context=context or “No previous context”)\n        return dspy.Prediction(answer=result.answer)</code>\n        </deckgo-highlight-code>\n<deckgo-highlight-code   >\n          <code slot=\"code\">class AnalyzeQuery(dspy.Signature):\n    “”“Analyze metrics, trends, and data patterns.”“”\n    question: str = dspy.InputField()\n    context: str = dspy.InputField(desc=”Results from previous steps (if any)”)\n    answer: str = dspy.OutputField(desc=”Analysis with trends and insights”)\n\nclass AnalyzeAgent(dspy.Module):\n    “”“Specialized agent for analyzing (metrics and trends).”“”\n    def __init__(self):\n        super().__init__()\n        self.react = dspy.ReAct(\n            signature=AnalyzeQuery,\n            tools=[get_metric, compare_metrics, list_available_metrics],\n            max_iters=4\n        )\n\n    def forward(self, question: str, context: str = “”):\n        result = self.react(question=question, context=context or “No previous context”)\n        return dspy.Prediction(answer=result.answer)</code>\n        </deckgo-highlight-code>\n<p>Each agent is self-contained. They don’t know about each other. They just know how to execute their intent. <strong>This modularity is what makes the system optimizable</strong> — you can eval and improve each agent independently.</p>\n<h2><strong>Step 2: The Orchestrator</strong></h2>\n<p>Now we need something that generates execution plans. The orchestrator takes a question, figures out what intents are needed, and routes each step to the right agent.</p>\n<deckgo-highlight-code   >\n          <code slot=\"code\">class ScoutOrchestrator(dspy.Module):\n    def __init__(self):\n        super().__init__()\n        self.planner = dspy.ChainOfThought(QueryPlanning)\n\n        # Intent-based agent registry\n        self.agents = {\n            “search”: SearchAgent(),\n            “retrieve”: RetrieveAgent(),\n            “analyze”: AnalyzeAgent(),\n        }\n\n        # Intent descriptions for planner\n        self.intent_descriptions = “”“\nAvailable intents:\n- search: Use when you need to FIND tickets or docs using keywords (e.g., “find Safari issues”, “search for checkout docs”)\n- retrieve: Use when you have specific IDs and need DETAILS (e.g., “get ticket SHOP-2847”, “get doc checkout-rewrite”)\n- analyze: Use when you need to examine METRICS or TRENDS (e.g., “how are conversions trending?”, “compare mobile vs desktop”)\n\nExamples:\n- “What tickets are about Safari?” → search\n- “Get details for SHOP-2847” → retrieve\n- “Are mobile conversions down?” → analyze\n- “Find checkout issues and check if conversions dropped” → search (find issues), analyze (check metrics)\n        “”“.strip()</code>\n        </deckgo-highlight-code>\n<p>The planning signature is straightforward.</p>\n<deckgo-highlight-code   >\n          <code slot=\"code\">class QueryPlanning(dspy.Signature):\n    “”“Decompose a user question into an execution plan.\n\n    Intent types:\n    - search: Find relevant tickets or docs using keywords\n    - retrieve: Get specific items by ID (ticket numbers, doc keys)\n    - analyze: Analyze metrics, trends, or compare data\n    “”“\n    question: str = dspy.InputField()\n    available_intents: str = dspy.InputField()\n    plan: List[dict] = dspy.OutputField(\n        desc=”List of dicts with keys: subquery (str), intent (str: search/retrieve/analyze)”\n    )</code>\n        </deckgo-highlight-code>\n<p>The magic happens in execution. The orchestrator doesn’t just route — it builds <strong>accumulated context</strong> so each step can see what previous steps discovered.</p>\n<deckgo-highlight-code   >\n          <code slot=\"code\"># Execute each step by routing to intent-specific agent\n        step_results = []\n        accumulated_context = “”\n\n        for i, step in enumerate(steps):\n            agent = self.agents[step.intent]\n            result = agent(question=step.subquery, context=accumulated_context)\n            step_results.append({\n                “step_id”: i,\n                “step”: step,\n                “answer”: result.answer\n            })\n\n            # Build context for next step\n            accumulated_context += f”\\\\nStep {i} ({step.intent}): {result.answer}\\\\n”</code>\n        </deckgo-highlight-code>\n<p>This context threading is subtle but critical. Consider the query: <strong>“Find P0 tickets and get details for the most critical one.”</strong></p>\n<ul>\n<li><strong>Step 0 (search)</strong>: Finds “SHOP-2847: Safari checkout crashes (Priority: P0)”</li>\n<li><strong>Step 1 (retrieve)</strong>: Receives Step 0’s results as context, sees SHOP-2847 was found, retrieves its full details</li>\n</ul>\n<p>Without context passing, Step 1 would fail — it wouldn’t know which ticket to retrieve. With context passing, the agents compose naturally.</p>\n<h2><strong>Step 3: Tools Do the Work</strong></h2>\n<p>Each agent has access to tools matched to its intent. The search agent can search Jira and Confluence for instance.</p>\n<deckgo-highlight-code   >\n          <code slot=\"code\">def search_jira(query: str) -&gt; str:\n    “”“Search Jira tickets by keyword.”“”\n    query_lower = query.lower()\n    results = []\n\n    for ticket_id, ticket in JIRA_TICKETS.items():\n        if (query_lower in ticket[”title”].lower() or\n            query_lower in ticket[”description”].lower() or\n            query_lower in ticket[”priority”].lower() or\n            query_lower in ticket[”status”].lower() or\n            query_lower in ticket[”assignee”].lower()):\n            results.append(\n                f”{ticket_id}: {ticket[’title’]} “\n                f”(Status: {ticket[’status’]}, Priority: {ticket[’priority’]}, “\n                f”Assignee: {ticket[’assignee’]})”\n            )\n\n    if not results:\n        return f”No Jira tickets found matching ‘{query}’”\n\n    return f”Found {len(results)} ticket(s):\\\\n” + “\\\\n”.join(results)</code>\n        </deckgo-highlight-code>\n<p>The retrieve agent can get specific documents:</p>\n<deckgo-highlight-code   >\n          <code slot=\"code\">def get_ticket_details(ticket_id: str) -&gt; str:\n    “”“Get full details for a specific Jira ticket.”“”\n    ticket = JIRA_TICKETS.get(ticket_id.upper())\n\n    if not ticket:\n        return f”Ticket {ticket_id} not found”\n\n    return f”“”Ticket {ticket_id}: {ticket[’title’]}\nStatus: {ticket[’status’]}\nAssignee: {ticket[’assignee’]}\nPriority: {ticket[’priority’]}\nCreated: {ticket[’created’]}\nUpdated: {ticket[’updated’]}\n\nDescription:\n{ticket[’description’]}”“”</code>\n        </deckgo-highlight-code>\n<p>The analyze agent can query metrics:</p>\n<deckgo-highlight-code   >\n          <code slot=\"code\">def get_metric(metric_name: str) -&gt; str:\n    “”“Get current value and trend for a specific metric.”“”\n    metric = ANALYTICS_DATA.get(metric_name)\n\n    if not metric:\n        available = ‘, ‘.join(ANALYTICS_DATA.keys())\n        return f”Metric ‘{metric_name}’ not found. Available: {available}”\n\n    return f”“”{metric_name}:\nCurrent: {metric[’current’]}\nPrevious: {metric[’previous’]}\nTrend: {metric[’trend’]} ({metric[’change_pct’]:+.1f}%)\nPeriod: {metric[’period’]}”“”</code>\n        </deckgo-highlight-code>\n<p>In production, these would hit real APIs. The pattern is the same: <strong>agents decide</strong> <em><strong>which</strong></em> <strong>tools to call, the orchestrator decides</strong> <em><strong>which</strong></em> <strong>agents to invoke.</strong></p>\n<h2>Example run</h2>\n<deckgo-highlight-code   >\n          <code slot=\"code\">================================================================================\nQuery 1: What tickets mention Safari?\n================================================================================\n\n📋 EXECUTION PLAN:\n   Step 0: [search] Find tickets that mention Safari\n\n💬 ANSWER:\nThe following ticket mentions Safari:\n- **SHOP-2847**: Safari checkout crashes on iOS 17 (Status: In Review, Priority: P0, Assignee: Alice Chen)\n\n\n================================================================================\nQuery 2: Get details for ticket SHOP-2847\n================================================================================\n\n📋 EXECUTION PLAN:\n   Step 0: [retrieve] Get details for ticket SHOP-2847\n\n💬 ANSWER:\nTicket SHOP-2847: Safari checkout crashes on iOS 17\n- **Status**: In Review\n- **Assignee**: Alice Chen\n- **Priority**: P0\n- **Created**: 2025-01-15\n- **Updated**: 2025-01-18\n\n**Description**:\nUsers on Safari 17/iOS report checkout crashes at the payment step. A hotfix was deployed yesterday, and the team is currently monitoring for recovery.\n\n\n================================================================================\nQuery 3: How are mobile conversions trending?\n================================================================================\n\n📋 EXECUTION PLAN:\n   Step 0: [analyze] Analyze the trend of mobile conversions over time.\n\n💬 ANSWER:\nThe trend of mobile conversions over time shows a decline, with a week-over-week decrease of 8.6%. The current value is 3.2, down from 3.5 in the previous period. This suggests a negative trend in mobile conversions, which may require further investigation to identify potential causes and address them.\n\n\n================================================================================\nQuery 4: Find P0 tickets and get details for the most critical one\n================================================================================\n\n📋 EXECUTION PLAN:\n   Step 0: [search] Find all P0 tickets\n   Step 1: [retrieve] Get details for the most critical P0 ticket\n\n💬 ANSWER:\n**SEARCH**: Found 1 P0 ticket:\n- **SHOP-2847**: Safari checkout crashes on iOS 17 (Status: In Review, Priority: P0, Assignee: Alice Chen)\n\n**RETRIEVE**: The most critical P0 ticket is **SHOP-2847**. Here are the details:\n\n- **Title**: Safari checkout crashes on iOS 17\n- **Status**: In Review\n- **Assignee**: Alice Chen\n- **Priority**: P0\n- **Created**: 2025-01-15\n- **Updated**: 2025-01-18\n- **Description**: Users on Safari 17/iOS report checkout crashes at the payment step. A hotfix was deployed yesterday, and the team is currently monitoring for recovery.\n\nThis ticket is being actively worked on, with a hotfix already deployed and under observation.\n\n\n================================================================================\nQuery 5: Are there checkout issues and are conversion rates down?\n================================================================================\n\n📋 EXECUTION PLAN:\n   Step 0: [search] Find tickets or documents related to checkout issues\n   Step 1: [analyze] Analyze conversion rate metrics to determine if they are down\n\n💬 ANSWER:\n**SEARCH**: No Jira tickets or Confluence documents related to “checkout issues” were found.\n\n**ANALYZE**: The conversion rate metrics are down. Specifically, “mobile_conversions” decreased by 8.6% (from 3.5 to 3.2), and “checkout_completion” decreased by 4.4% (from 82.1 to 78.5) week-over-week. These declines indicate a negative trend in conversion performance, which may warrant further investigation to identify potential causes and address the issue.\n\n\n================================================================================\nQuery 6: Get details for SHOP-3001 and check if mobile metrics are affected\n================================================================================\n\n📋 EXECUTION PLAN:\n   Step 0: [retrieve] Get details for SHOP-3001\n   Step 1: [analyze] Check if mobile metrics are affected\n\n💬 ANSWER:\n**RETRIEVE**: Ticket ID: SHOP-3001\nTitle: Mobile web performance degradation\nStatus: In Progress\nAssignee: Carol Wang\nPriority: P1\nCreated: 2025-01-14\nUpdated: 2025-01-18\n\nDescription:\nMobile page load times increased 20% after new analytics integration.\n\n**ANALYZE**: Mobile metrics have been negatively affected, as evidenced by the following trends:\n1. “mobile_conversions” decreased by 8.6% week-over-week, indicating fewer successful transactions on mobile.\n2. “checkout_completion” dropped by 4.4%, showing a decline in the percentage of users completing the checkout process.\n3. “safari_users” fell by 3.2%, suggesting reduced engagement or retention among Safari users.\n\nThese declines align with the reported 20% increase in mobile page load times, suggesting that the new analytics integration has adversely impacted mobile performance and user behavior.\n\n\n================================================================================\nQuery 7: Find Safari-related tickets, get details for SHOP-2847, and check Safari user metrics\n================================================================================\n\n📋 EXECUTION PLAN:\n   Step 0: [search] Find Safari-related tickets\n   Step 1: [retrieve] Get details for ticket SHOP-2847\n   Step 2: [analyze] Check Safari user metrics\n\n💬 ANSWER:\n**SEARCH**: The Safari-related ticket found is:\n- **SHOP-2847**: Safari checkout crashes on iOS 17 (Status: In Review, Priority: P0, Assignee: Alice Chen)\n\n**RETRIEVE**: Ticket SHOP-2847: Safari checkout crashes on iOS 17\n- **Status**: In Review\n- **Assignee**: Alice Chen\n- **Priority**: P0\n- **Created**: 2025-01-15\n- **Updated**: 2025-01-18\n\n**Description**:\nUsers on Safari 17/iOS report checkout crashes at the payment step. A hotfix was deployed yesterday, and the team is currently monitoring for recovery.\n\n**ANALYZE**: The Safari user metrics indicate a decline in activity and performance, likely linked to the reported checkout crash issue on iOS 17 (SHOP-2847). Specifically:\n- Safari user activity is down by 3.2% week-over-week (current: 24.3, previous: 25.1).\n- Checkout completion rates have dropped by 4.4% (current: 78.5, previous: 82.1).\n- Payment success rates have decreased by 1.6% (current: 96.2, previous: 97.8).\n\nThese trends suggest that the Safari checkout issue is impacting user engagement and conversion rates. Monitoring these metrics in the coming days will help determine if the recent hotfix is effective in reversing these declines.</code>\n        </deckgo-highlight-code>\n<h2><strong>TL;DR</strong></h2>\n<ol>\n<li><strong>Routing is code, not hope</strong> – The planner generates structured plans you can log, debug, and improve</li>\n<li><strong>Context flows between steps</strong> – Multi-step queries compose naturally because agents see what previous steps discovered</li>\n<li><strong>Intent-based modularity</strong> – Each agent specializes in one operation type, making the system easier to test and optimize</li>\n<li><strong>Observable decisions</strong> – Every plan is structured data showing exactly what the system decided and why</li>\n</ol>\n<p><strong>What you can now do</strong></p>\n<ul>\n<li>Log every plan and see which routing decisions work</li>\n<li>A/B test different planning strategies</li>\n<li>Optimize agents independently (improve search without touching analyze)</li>\n<li>Add new intents without rewriting infrastructure</li>\n<li>Collect production data for systematic improvement</li>\n</ul>\n<h2><strong>Step 4: Front It with MCP</strong></h2>\n<p>Once you have a working orchestrator, expose it via MCP. External clients see one clean interface!</p>\n<deckgo-highlight-code   >\n          <code slot=\"code\">from fastmcp import FastMCP\n\nmcp = FastMCP(”scout”)\nscout = ScoutOrchestrator()\n\n@mcp.tool()\ndef scout_query(question: str) -&gt; str:\n    “”“Ask Scout a question about your data sources.”“”\n    result = scout(question=question)\n    return result.answer\n\nif __name__ == “__main__”:\n    mcp.run()</code>\n        </deckgo-highlight-code>\n<p>That’s it. Clients talk to MCP. MCP routes through your orchestrator. Your orchestrator generates plans, routes to agents, agents call tools, results flow back with full context. You can connect Cursor, Claude, LibreChat or whatever other tool you like.</p>\n<h2><strong>Why This Matters</strong></h2>\n<p>The agent tool sprawl problem isn’t really about tools, it’s about control. When you delegate routing to a base model, you’re outsourcing architectural decisions to a system that can’t learn from feedback.</p>\n<p>The fix then isn’t better prompts at all! It’s an orchestration layer that makes routing decisions observable, programmable, and optimizable.</p>\n<p>This architecture gives you:</p>\n<ul>\n<li><strong>Control</strong> – Routing is code you own, not behavior you hope for</li>\n<li><strong>Aggregation</strong> – Clients see one interface, you manage complexity behind it</li>\n<li><strong>Observability</strong> – Every routing decision is structured data you can analyze</li>\n<li><strong>Modularity</strong> – Ship new agents without touching infrastructure</li>\n<li><strong>A foundation for optimization</strong> – You’re now collecting decision data</li>\n</ul>\n<p>That last point is crucial. Right now this orchestrator works zero shot.</p>\n<p><strong>In a future post, we’ll use DSPy’s GEPA optimization to systematically improve routing accuracy.</strong> I‘ll show you how to collect golden examples, define metrics, and let DSPy automatically tune the planner’s prompts.</p>\n<p>The difference between a demo and production isn’t just reliability — it’s the ability to improve systematically as you learn what your users actually need. And that’s what we’ll build next. Stay tuned!</p>","excerpt":"This is part 5 in a series of posts about differentiable programming for dynamic workflows using DSPy. The code is available here.  Two months ago, Tobi Lütke…","frontmatter":{"date":"November 07, 2025","rawDate":"2025-11-07","substack_post_date":"2025-11-07T22:02:51.942Z","slug":"/blog/solving-agent-tool-sprawl-with-dspy-building-a-shopify-scout-like-system","title":"Solving Agent Tool Sprawl with DSPy: Building a Shopify Scout like System","ispage":false,"ispublished":true,"source_url":"https://viksit.substack.com/p/solving-agent-tool-sprawl-with-dspy","description":"Stop letting LLMs improvise across your tools. Use DSPy based orchestration for control, evals and optimization."}}},"pageContext":{"slug":"/blog/solving-agent-tool-sprawl-with-dspy-building-a-shopify-scout-like-system","next":{"frontmatter":{"slug":"/blog/the-well-behaved-machine","title":"The well behaved machine","date":"2026-09-06","ispublished":true,"ispage":false},"slug":"/blog/the-well-behaved-machine/","topic":"society","kind":"essay"},"previous":{"frontmatter":{"slug":"/blog/the-structural-limits-of-ai","title":"The Structural Limits of AI","date":"2025-10-30","ispublished":true,"ispage":false},"slug":"/blog/the-structural-limits-of-ai/","topic":"agents","kind":"commentary","featureEligible":false}}},
    "staticQueryHashes": ["4202924991"]}