Skip to content

From SQL Generation to Tool Selection: A Domain-Oriented Pattern for MCP Servers

Aug 2026 · 0 citations · 18 references
Computer Science

TL;DR

The Domain-Oriented Tooling Pattern is proposed: instead of generating SQL at query time, the model selects from a small set of domain-aligned tools whose parameterized queries encapsulate schema navigation, joins and business rules on the server side.

Abstract

Agents built on Large Language Models (LLMs) increasingly reach enterprise data through the Model Context Protocol (MCP), and many MCP database servers maximize flexibility by exposing a single generic SQL execution tool. This paper proposes the Domain-Oriented Tooling Pattern: instead of generating SQL at query time, the model selects from a small set of domain-aligned tools whose parameterized queries encapsulate schema navigation, joins and business rules on the server side. We formalize the pattern around three architectural invariants and introduce Model Demotion, the observation that replacing SQL synthesis with intent classification lowers the model tier required to serve routine requests. As a reference implementation we present MCP Blueprint, an open-source framework in which domain tools are defined declaratively as YAML metadata plus external parameterized SQL files. We evaluate the pattern with a public reproducibility benchmark comparing three MCP server designs - raw SQL execution, a thin generic tool pack, and a verticalized domain pack - on four local models (3B-8B) across seventeen customer-facing tasks over the Sakila database (609 completed cells; temperature 0; three repetitions per cell). The verticalized pack reaches a pooled mean score of 0.939 versus 0.666 for raw SQL and 0.605 for the generic pack; the smallest model improves from 0.583 to 0.929, matching or exceeding every larger configuration while cutting cost per correct answer by an order of magnitude. All harness code, prompts, gold answers, frozen packs and per-cell results are publicly available.

View source

Similar papers

Preprint Aug 2026

Hybrid Semantic Tool Discovery for Enterprise MCP Gateway: Architecture and Implementation

Large language model (LLM) agents invoke external tools to retrieve and reason over information beyond pretrained knowledge. The Model Context Protocol (MCP) standardizes how such tools are surfaced, and a proxy MCP server aggregates many backend servers behind a single endpoint providing a secure, governable chokepoint for authentication, policy enforcement, and observability. This architecture creates two compounding challenges: a context-engineering bottleneck where full tool schemas saturate the model context window before any user query, and a tool discoverability barrier where users and agents cannot identify the best tool among 2,000+ indexed tools across 200+ MCP servers. Prompt caching reduces reprocessing cost but neither frees context capacity nor improves accuracy. We present SCOUT (Selective Context Optimization for Universal Tooling), which reframes tool exposure as a context-selection problem, injecting only tools relevant to the current step. SCOUT surfaces two MCP meta-tools -- tool_search and execute_tool -- where tool_search performs hybrid retrieval, fusing BM25 sparse matching with dense vector search via Reciprocal Rank Fusion to return the top-k relevant tools. Backed by zero-downtime catalog update pipelines, SCOUT resolves both context saturation and tool discovery challenges. In production at PayPal, SCOUT reduces MCP tool-token consumption from 140.2k tokens (70.1% of context) to 1.3k tokens (0.8%), a 99% reduction, cutting per-query inference cost at enterprise scale. Because SCOUT is surfaced as standard MCP tools, it is model-agnostic and requires no client-side modifications.

Olympia Saha, Amy Wang, Srinivasan Manoharan · 0 citations
Preprint Aug 2026

DBcover: A White-box SQL Test Generation Framework for Coverage Improvement

Relational Database Management Systems (RDBMSs) are the backbone of modern data-intensive applications, making reliability and robustness critical. However, achieving high coverage in RDBMS testing remains challenging because of large codebases and complex execution logic. Traditional fuzzing relies on random SQL generation and cannot capture the correspondence between SQL inputs and internal execution paths, while symbolic execution suffers from prohibitive cost and scalability limitations. We propose DBcover, an LLM-driven white-box SQL test generation framework based on contextual reasoning. DBcover uses lightweight dynamic analysis to extract SQL-to-path correspondence and call graphs as global context, and collects source-level information around target functions as local context. These contexts are organized in a unified knowledge graph for efficient retrieval and reuse. DBcover then performs two-phase test generation: it first selects a semantically relevant seed whose execution path is close to the uncovered target, and then guides the LLM with global and local context to generate SQL test cases that trigger previously uncovered code regions. Experiments show that DBcover achieves 80.1% and 82.3% coverage on PostgreSQL and MySQL, and is also effective on the enterprise RDBMS KingbaseES, demonstrating its practical applicability to closed-source systems.

Yan-Kai Rong, Shuang Liu, Jinhao Dong et al. · 0 citations
Preprint Aug 2026

AutoSQL: Extracting SQL Templates from Imperative ORM Code in Large-Scale Repositories

Suboptimal SQL queries can significantly degrade the performance of cloud systems, motivating the extraction and auditing of SQL statements before deployment. However, Go ORM frameworks construct SQL imperatively through scattered method-call sequences, making it difficult to statically recover the resulting SQL templates. We present AutoSQL, a system that reconstructs SQL templates from Go ORM code. AutoSQL constructs a Code Index, a directed graph that captures structural dependencies between functions, types, and global variables as navigable edges. It then traces upstream call chains from ORM invocation sites to identify database-interacting functions as entry points. For each entry point, an LLM agent traverses the Code Index to collect code slices that influence SQL generation, switching to pattern-based search when the graph cannot resolve a retrieval goal. We call this strategy Hybrid Context Retrieval. Once sufficient context is collected, the agent synthesizes SQL templates. Evaluation on a benchmark of 579 test-covered entry points and 1,186 runtime-traced SQL statements from five large-scale Go repositories shows that AutoSQL achieves 68.04% to 72.18% recall, exceeding the static reachability baseline by 11.80% to 15.94% and outperforming existing methods by 8.52% to 21.50%.

Junsong Pu, Yichen Li, Zhuangbin Chen et al. · 0 citations
Open access May 2026

SafeQL: Search-based Refinement for Safe and Efficient LLM-based Text-to-SQL

Large language models (LLMs) have advanced Text-to-SQL by enabling natural language interfaces to databases without task-specific fine-tuning. However, existing LLM-based systems remain unreliable, often generating SQL queries that are invalid under the database schema, referencing non-existent tables, attributes, functions, or values. Such errors persist because interactions with the database management system (DBMS) are typically limited to error messages, leaving it in a largely passive role during query refinement. This paper proposes SafeQL, a search-based refinement paradigm that redefines the role of the DBMS as an active guide in the refinement process. Instead of regenerating entire queries after execution failure, SafeQL interprets DBMS feedback to incrementally repair only the erroneous components. Each refinement step is formulated as a guided search within a safe query space , where candidate queries are progressively validated through DBMS execution, thereby converging to an executable query and preventing repeated regeneration of errors. Experiments on the Bird and Spider benchmarks show that SafeQL significantly improves execution accuracy and efficiency compared to regeneration-based methods.

Geonho Lee, Min-Soo Kim · 0 citations
Open access Jul 2026

Token-Aware API Design Patterns for Model Context Protocol Integration in Enterprise Distributed Systems

Autonomous software agents operating through the Model Context Protocol (MCP) reveal a fundamental architectural mismatch between conventional REST API design and the finite context windows of Large Language Model (LLM) inference engines. Enterprise backend services originally optimized for browser-based applications typically return payloads enriched with deeply nested relational structures, verbose infrastructure metadata, and redundant serialization artifacts. While acceptable for human-operated interfaces, these responses unnecessarily consume LLM context capacity when delivered through MCP servers, increasing inference costs, reducing reasoning efficiency, and limiting the number of actionable interactions that autonomous agents can perform. This article investigates serialization-boundary optimization as a critical architectural concern for MCP-native systems and proposes four composable backend design patterns: Semantic Envelope, infrastructure metadata pruning, dynamic token-aware pagination, and GraphQL interface projections. Together, these patterns restructure API responses to maximize semantic density while minimizing token consumption without modifying underlying domain models or persistence layers. The implementation is demonstrated in enterprise environments built on Spring Boot and Hibernate, illustrating seamless integration with existing software architectures. Experimental evaluation using production entity structures from a peer-to-peer car-sharing marketplace processing millions of vehicle transactions annually shows token reductions ranging from 34% to 86% across the proposed patterns, a 40% decrease in API pagination cycles, and a 97% reduction in response latency through a two-tier semantic caching strategy deployed over an 11.5-million-row persistence layer sustaining approximately 48,900 read operations per minute. These findings demonstrate that context-aware serialization significantly improves LLM agent efficiency while preserving enterprise scalability, interoperability, and maintainability. The proposed framework provides a practical engineering vocabulary and reference architecture for designing token-efficient, MCP-native backend systems capable of supporting the next generation of autonomous AI agents in large-scale enterprise environments.

Nikhil Bharadwaj Ramashasthri · 0 citations
Open access Jul 2026

Feedback-Driven SQL Optimization with Validated Query Rewrites

Cost-based query optimizers are essential for relational database systems, but SQL formulation can still affect selected execution plans and runtime, especially in recurring analytical workloads and machine-generated queries. This paper proposes a feedback-driven lifecycle for SQL optimization, based on empirically validated query rewrites. The contribution of the presented approach is a persistent candidate-management process that covers the path from candidate intake to provenance recording, structural admissibility checks, empirical result-equivalence validation, paired runtime evidence, guarded activation, retention, rejection, and later deactivation. Candidate rewrites may come from deterministic rules, local large language models, manual alternatives, or external rewrite systems; the source is recorded but does not determine acceptance. The evaluation uses a controlled research implementation with deterministic-rule cases, repeated TPC-H SF1 runs, a real-world-style anti-pattern corpus, and JOB/IMDB. The results show conservative behavior on mature analytical templates, including mostly withheld TPC-H candidates with one held-out positive case, stable evidence for selected anti-patterns, and comparable but non-identical JOB/IMDB positives across runs. The findings support a source-neutral lifecycle in which alternative SQL formulations are admitted, measured, retained, activated, or rejected according to accumulated evidence rather than the generating mechanism.

Martin Kostov, K. Kaloyanova · 0 citations

Related blog posts