Skip to content

Local code intelligence for developers and AI agents. Connect code, docs and infrastructure in a persistent graph, with CBM Lens, MCP tools, agent integrations and change-aware test selection.

Add offset/limit pagination to search_graph and search_code

Martin Vogelf10239a004b2
diff --git a/internal/store/search.go b/internal/store/search.go
index 3712ee203..0eb252acf 100644
--- a/internal/store/search.go
+++ b/internal/store/search.go
@@ -8,16 +8,17 @@ import (
// SearchParams defines structured search parameters.
type SearchParams struct {
- Project string
- Label string
- NamePattern string
- FilePattern string
- Relationship string
- Direction string // "inbound", "outbound", "any"
- MinDegree int
- MaxDegree int
- Limit int
- ExcludeEntryPoints bool // when true, exclude nodes with is_entry_point=true
+ Project string
+ Label string
+ NamePattern string
+ FilePattern string
+ Relationship string
+ Direction string // "inbound", "outbound", "any"
+ MinDegree int
+ MaxDegree int
+ Limit int
+ Offset int
+ ExcludeEntryPoints bool // when true, exclude nodes with is_entry_point=true
}
// SearchResult is a node with edge degree info.
@@ -28,11 +29,16 @@ type SearchResult struct {
ConnectedNames []string
}
-// Search executes a parameterized search query.
-func (s *Store) Search(params SearchParams) ([]*SearchResult, error) {
- // Limit=0 means no limit; use a high ceiling for SQL
- unlimited := params.Limit <= 0
- if unlimited {
+// SearchOutput wraps search results with total count for pagination.
+type SearchOutput struct {
+ Results []*SearchResult
+ Total int
+}
+
+// Search executes a parameterized search query with pagination support.
+func (s *Store) Search(params SearchParams) (*SearchOutput, error) {
+ // Limit=0 means use default; use a high ceiling for SQL
+ if params.Limit <= 0 {
params.Limit = 100000
}
@@ -64,7 +70,11 @@ func (s *Store) Search(params SearchParams) ([]*SearchResult, error) {
if params.NamePattern != "" || hasDegreeFilter {
sqlLimit = 10000 // fetch enough rows for Go-side filtering
} else {
- sqlLimit = params.Limit
+ // Fetch enough for offset + limit
+ sqlLimit = params.Offset + params.Limit
+ if sqlLimit > 100000 {
+ sqlLimit = 100000
+ }
}
query := fmt.Sprintf(`
@@ -102,14 +112,8 @@ func (s *Store) Search(params SearchParams) ([]*SearchResult, error) {
}
}
- // Apply limit after name filtering (but not when degree filters are active,
- // since degree filtering happens in the loop below with its own limit check)
- if !hasDegreeFilter && len(nodes) > params.Limit {
- nodes = nodes[:params.Limit]
- }
-
- // Build results with degree info
- var results []*SearchResult
+ // Build all qualifying results (before offset/limit) for accurate total count
+ var allResults []*SearchResult
for _, n := range nodes {
sr := &SearchResult{Node: n}
@@ -157,13 +161,25 @@ func (s *Store) Search(params SearchParams) ([]*SearchResult, error) {
connRows.Close()
}
- results = append(results, sr)
- if len(results) >= params.Limit {
- break
- }
+ allResults = append(allResults, sr)
+ }
+
+ total := len(allResults)
+
+ // Apply offset and limit
+ start := params.Offset
+ if start > total {
+ start = total
+ }
+ end := start + params.Limit
+ if end > total {
+ end = total
}
- return results, nil
+ return &SearchOutput{
+ Results: allResults[start:end],
+ Total: total,
+ }, nil
}
// globToLike converts a glob pattern to SQL LIKE pattern.
diff --git a/internal/store/store_test.go b/internal/store/store_test.go
index f264d5a12..327f0ac1e 100644
--- a/internal/store/store_test.go
+++ b/internal/store/store_test.go
@@ -251,29 +251,55 @@ func TestSearch(t *testing.T) {
s.UpsertNode(&Node{Project: "test", Label: "Class", Name: "OrderService", QualifiedName: "test.service.OrderService", FilePath: "service.go"})
// Search by label
- results, err := s.Search(SearchParams{Project: "test", Label: "Function"})
+ output, err := s.Search(SearchParams{Project: "test", Label: "Function"})
if err != nil {
t.Fatalf("Search: %v", err)
}
- if len(results) != 2 {
- t.Errorf("expected 2 functions, got %d", len(results))
+ if len(output.Results) != 2 {
+ t.Errorf("expected 2 functions, got %d", len(output.Results))
+ }
+ if output.Total != 2 {
+ t.Errorf("expected total=2, got %d", output.Total)
}
// Search by name pattern
- results, err = s.Search(SearchParams{Project: "test", NamePattern: ".*Submit.*"})
+ output, err = s.Search(SearchParams{Project: "test", NamePattern: ".*Submit.*"})
if err != nil {
t.Fatalf("Search: %v", err)
}
- if len(results) != 1 {
- t.Errorf("expected 1 match, got %d", len(results))
+ if len(output.Results) != 1 {
+ t.Errorf("expected 1 match, got %d", len(output.Results))
}
// Search by file pattern
- results, err = s.Search(SearchParams{Project: "test", FilePattern: "service*"})
+ output, err = s.Search(SearchParams{Project: "test", FilePattern: "service*"})
if err != nil {
t.Fatalf("Search: %v", err)
}
- if len(results) != 2 {
- t.Errorf("expected 2 nodes in service.go, got %d", len(results))
+ if len(output.Results) != 2 {
+ t.Errorf("expected 2 nodes in service.go, got %d", len(output.Results))
+ }
+
+ // Search with offset/limit pagination
+ output, err = s.Search(SearchParams{Project: "test", Limit: 1})
+ if err != nil {
+ t.Fatalf("Search: %v", err)
+ }
+ if len(output.Results) != 1 {
+ t.Errorf("expected 1 result with limit=1, got %d", len(output.Results))
+ }
+ if output.Total != 3 {
+ t.Errorf("expected total=3, got %d", output.Total)
+ }
+
+ output, err = s.Search(SearchParams{Project: "test", Limit: 1, Offset: 1})
+ if err != nil {
+ t.Fatalf("Search: %v", err)
+ }
+ if len(output.Results) != 1 {
+ t.Errorf("expected 1 result with limit=1 offset=1, got %d", len(output.Results))
+ }
+ if output.Total != 3 {
+ t.Errorf("expected total=3, got %d", output.Total)
}
}
diff --git a/internal/tools/code_search.go b/internal/tools/code_search.go
index 9b6cd278b..bf1bcbc45 100644
--- a/internal/tools/code_search.go
+++ b/internal/tools/code_search.go
@@ -30,10 +30,8 @@ func (s *Server) handleSearchCode(_ context.Context, req *mcp.CallToolRequest) (
}
fileGlob := getStringArg(args, "file_pattern")
- maxResults := getIntArg(args, "max_results", 0)
- if maxResults <= 0 {
- maxResults = 100000 // no limit
- }
+ maxResults := getIntArg(args, "max_results", 100)
+ offset := getIntArg(args, "offset", 0)
isRegex := false
if v, ok := args["regex"]; ok {
@@ -80,22 +78,40 @@ func (s *Server) handleSearchCode(_ context.Context, req *mcp.CallToolRequest) (
}
}
- var matches []codeMatch
+ // Collect all matches up to offset+maxResults for accurate total count
+ fetchLimit := offset + maxResults
+ var allMatches []codeMatch
for _, relPath := range filePaths {
- if len(matches) >= maxResults {
+ if len(allMatches) >= fetchLimit {
break
}
absPath := filepath.Join(root, relPath)
- fileMatches := searchFile(absPath, relPath, pattern, re, isRegex, maxResults-len(matches))
- matches = append(matches, fileMatches...)
+ fileMatches := searchFile(absPath, relPath, pattern, re, isRegex, fetchLimit-len(allMatches))
+ allMatches = append(allMatches, fileMatches...)
+ }
+
+ total := len(allMatches)
+ hasMore := total >= fetchLimit
+
+ // Apply offset and limit
+ start := offset
+ if start > total {
+ start = total
+ }
+ end := start + maxResults
+ if end > total {
+ end = total
}
+ pageMatches := allMatches[start:end]
return jsonResult(map[string]any{
"pattern": pattern,
- "total": len(matches),
- "truncated": len(matches) >= maxResults,
- "matches": matches,
+ "total": total,
+ "limit": maxResults,
+ "offset": offset,
+ "has_more": hasMore,
+ "matches": pageMatches,
"files_count": len(filePaths),
}), nil
}
diff --git a/internal/tools/search.go b/internal/tools/search.go
index 04e98bd38..e5986aabd 100644
--- a/internal/tools/search.go
+++ b/internal/tools/search.go
@@ -22,7 +22,8 @@ func (s *Server) handleSearchGraph(_ context.Context, req *mcp.CallToolRequest)
Direction: getStringArg(args, "direction"),
MinDegree: getIntArg(args, "min_degree", -1),
MaxDegree: getIntArg(args, "max_degree", -1),
- Limit: getIntArg(args, "limit", 0), // 0 = no limit
+ Limit: getIntArg(args, "limit", 100),
+ Offset: getIntArg(args, "offset", 0),
ExcludeEntryPoints: getBoolArg(args, "exclude_entry_points"),
}
@@ -55,16 +56,18 @@ func (s *Server) handleSearchGraph(_ context.Context, req *mcp.CallToolRequest)
}
var allResults []resultEntry
+ totalAcrossProjects := 0
for _, p := range projects {
if projectFilter != "" && p.Name != projectFilter {
continue
}
params.Project = p.Name
- results, searchErr := s.store.Search(params)
+ output, searchErr := s.store.Search(params)
if searchErr != nil {
continue
}
- for _, r := range results {
+ totalAcrossProjects += output.Total
+ for _, r := range output.Results {
entry := resultEntry{
Project: p.Name,
Name: r.Node.Name,
@@ -82,7 +85,10 @@ func (s *Server) handleSearchGraph(_ context.Context, req *mcp.CallToolRequest)
}
return jsonResult(map[string]any{
- "total": len(allResults),
- "results": allResults,
+ "total": totalAcrossProjects,
+ "limit": params.Limit,
+ "offset": params.Offset,
+ "has_more": params.Offset+params.Limit < totalAcrossProjects,
+ "results": allResults,
}), nil
}
diff --git a/internal/tools/tools.go b/internal/tools/tools.go
index 9b0ca0766..85ebcf5cc 100644
--- a/internal/tools/tools.go
+++ b/internal/tools/tools.go
@@ -145,7 +145,11 @@ func (s *Server) registerTools() {
},
"limit": {
"type": "integer",
- "description": "Max results to return. If omitted, returns all matching results."
+ "description": "Max results to return per page (default: 100)."
+ },
+ "offset": {
+ "type": "integer",
+ "description": "Number of results to skip for pagination (default: 0). Use with limit to page through results."
}
}
}`),
@@ -238,7 +242,11 @@ func (s *Server) registerTools() {
},
"max_results": {
"type": "integer",
- "description": "Maximum number of matches to return. If omitted, returns all matches."
+ "description": "Maximum number of matches to return per page (default: 100)."
+ },
+ "offset": {
+ "type": "integer",
+ "description": "Number of matches to skip for pagination (default: 0). Use with max_results to page through results."
}
},
"required": ["pattern"]