-
Notifications
You must be signed in to change notification settings - Fork 315
Add aggregate_records DML tool and query-timeout to MCP server #3179
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
Copilot
wants to merge
34
commits into
main
Choose a base branch
from
copilot/add-aggregate-records-tool
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+3,211
−140
Draft
Changes from all commits
Commits
Show all changes
34 commits
Select commit
Hold shift + click to select a range
2d96151
Initial plan
Copilot eaaa522
Changes before error encountered
Copilot f855e96
Add first/after pagination support to aggregate_records tool
Copilot 3573321
Add exhaustive tool instructions and all 13 spec example tests
Copilot f66bf3f
Changes before error encountered
Copilot 829a630
Changes before error encountered
Copilot 3ccc748
Update query-timeout default to 30s, add converter support, apply tim…
Copilot 381899d
Fix group key collision using \\0 delimiter, add #nullable enable to …
Copilot fde4d65
Fix nullable warnings in AggregateRecordsToolTests.cs
Copilot ba371d5
Add null check for errorType in AggregateRecordsToolTests
Copilot d340cb4
Apply validation fixes and additional tests from copilot/update-aggre…
41ccb2f
Refactor using directives in AggregateRecordsTool.cs to improve code …
eb99aba
Enhance AggregateRecordsTool to build SQL aggregate queries, improvin…
006f17a
Rewrite aggregate tests for SQL-level aggregation
d35088c
Fix negative cursor offset and add first max validation
ef7fd0d
Refactor AggregateRecordsTool to use engine query builder pattern
c5920c7
Fix SQL generation bugs in AggregateRecordsTool
203fde1
Add comprehensive blog scenario tests from DAB MCP blog
fab587f
Tighten tool description and parameter docs to remove duplication
5c93f92
Add early field validation and FieldNotFound error helper
d1268f2
Rename truncated variables to descriptive names
5390471
Remove hallucinated first > 100000 validation
b55cdde
Clean up extra blank line from validation removal
7f4e259
Add AggregateRecordsTool documentation for SQL-level aggregations
d83ded2
Simplify sequence diagram and expand design decisions
1327150
Merge branch 'main' into copilot/add-aggregate-records-tool
souvikghosh04 6815b65
Changes before error encountered
Copilot c7010ff
Removing duplicate registration from stdio which is failing runs
souvikghosh04 5038cc7
update snapshot test files
souvikghosh04 ecbb2fa
Merge branch 'main' into copilot/add-aggregate-records-tool
souvikghosh04 88968f6
Initial plan
Copilot b87be6f
Fixes from code reviews
souvikghosh04 38c773d
Snapshot files and test fixes
souvikghosh04 7b85658
Add AggregateRecords and query-timeout properties to Service.Tests sn…
souvikghosh04 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
783 changes: 783 additions & 0 deletions
783
src/Azure.DataApiBuilder.Mcp/BuiltInTools/AggregateRecordsTool.cs
Large diffs are not rendered by default.
Oops, something went wrong.
51 changes: 51 additions & 0 deletions
51
src/Azure.DataApiBuilder.Mcp/BuiltInTools/AggregateRecordsTool.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,51 @@ | ||
| # AggregateRecordsTool | ||
|
|
||
| MCP tool that computes SQL-level aggregations (COUNT, AVG, SUM, MIN, MAX) on DAB entities. All aggregation is pushed to the database engine — no in-memory computation. | ||
|
|
||
| ## Class Structure | ||
|
|
||
| | Member | Kind | Purpose | | ||
| |---|---|---| | ||
| | `ToolType` | Property | Returns `ToolType.BuiltIn` for reflection-based discovery. | | ||
| | `_validFunctions` | Static field | Allowlist of aggregation functions: count, avg, sum, min, max. | | ||
| | `GetToolMetadata()` | Method | Returns the MCP `Tool` descriptor (name, description, JSON input schema). | | ||
| | `ExecuteAsync()` | Method | Main entry point — validates input, resolves metadata, authorizes, builds the SQL query via the engine's `IQueryBuilder.Build(SqlQueryStructure)`, executes it, and formats the response. | | ||
| | `ComputeAlias()` | Static method | Produces the result column alias: `"count"` for count(\*), otherwise `"{function}_{field}"`. | | ||
| | `DecodeCursorOffset()` | Static method | Decodes a base64 opaque cursor string to an integer offset for OFFSET/FETCH pagination. Returns 0 on any invalid input. | | ||
| | `BuildPaginatedResponse()` | Private method | Formats a grouped result set into `{ items, endCursor, hasNextPage }` when `first` is provided. | | ||
| | `BuildSimpleResponse()` | Private method | Formats a scalar or grouped result set without pagination. | | ||
|
|
||
| ## ExecuteAsync Sequence | ||
|
|
||
| ```mermaid | ||
| sequenceDiagram | ||
| participant Client as MCP Client | ||
| participant Tool as AggregateRecordsTool | ||
| participant Engine as DAB Engine | ||
| participant DB as Database | ||
|
|
||
| Client->>Tool: ExecuteAsync(arguments) | ||
| Tool->>Tool: Validate inputs & check tool enabled | ||
| Tool->>Engine: Resolve entity metadata & validate fields | ||
| Tool->>Engine: Authorize (column-level permissions) | ||
| Tool->>Engine: Build SQL via queryBuilder.Build(SqlQueryStructure) | ||
| Tool->>Tool: Post-process SQL (ORDER BY, pagination) | ||
| Tool->>DB: ExecuteQueryAsync → JSON result | ||
| alt Paginated (first provided) | ||
| Tool-->>Client: { items, endCursor, hasNextPage } | ||
| else Simple | ||
| Tool-->>Client: { entity, result: [{alias: value}] } | ||
| end | ||
|
|
||
| Note over Tool,Client: On error: TimeoutError, OperationCanceled, or DatabaseOperationFailed | ||
| ``` | ||
|
|
||
| ## Key Design Decisions | ||
|
|
||
| - **No in-memory aggregation.** The engine's `GroupByMetadata` / `AggregationColumn` types drive SQL generation via `queryBuilder.Build(structure)`. All aggregation is performed by the database. | ||
| - **COUNT(\*) workaround.** The engine's `Build(AggregationColumn)` doesn't support `*` as a column name (it produces invalid SQL like `count([].[*])`), so the primary key column is used instead. `COUNT(pk)` ≡ `COUNT(*)` since PK is NOT NULL. | ||
| - **ORDER BY post-processing.** Neither the GraphQL nor REST code paths support ORDER BY on an aggregate expression, so this tool inserts `ORDER BY {func}({col}) ASC|DESC` into the generated SQL before `FOR JSON PATH`. | ||
| - **TOP vs OFFSET/FETCH.** SQL Server forbids both in the same query. When pagination (`first`) is used, `TOP N` is stripped via regex before appending `OFFSET/FETCH NEXT`. | ||
| - **Early field validation.** All user-supplied field names (aggregation field, groupby fields) are validated against the entity's metadata before authorization or query building, so typos surface immediately with actionable guidance. | ||
| - **Timeout vs cancellation.** `TimeoutException` (from `query-timeout` config) and `OperationCanceledException` (from client disconnect) are handled separately with distinct model-facing messages. Timeouts guide the model to narrow filters or paginate; cancellations suggest retry. | ||
| - **Database support.** Only MsSql / DWSQL — matches the engine's GraphQL aggregation support. PostgreSQL, MySQL, and CosmosDB return an `UnsupportedDatabase` error. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.