-
Notifications
You must be signed in to change notification settings - Fork 0
refactor(mcp): migrate adapters to service layer with dependency injection #160
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
Merged
Conversation
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
Create comprehensive service layer to eliminate code duplication between CLI and MCP, improve testability, and provide consistent APIs. Services Created: - StatsService: Repository statistics retrieval - HealthService: Component health checks - MetricsService: Analytics and metrics queries - SearchService: Semantic code search (eliminates 4x duplication) - GitHubService: GitHub operations (eliminates 3x duplication) - CoordinatorService: Subagent setup (eliminates 100% duplicate code) - GitHistoryService: Git history indexing and search Key Improvements: - Dependency injection pattern throughout (no constructor mocking) - 62 comprehensive tests with 100% coverage - Zero biome-ignore comments - Consistent behavior across CLI and MCP - Single source of truth for each operation Technical Details: - All services use factory pattern for dependency injection - Dynamic imports to avoid cross-package TypeScript issues - Clean separation of concerns - Proper resource cleanup (close methods) - Configurable options with sensible defaults Files Changed: - packages/core/src/services/ (7 services + 7 test files) - packages/core/src/index.ts (export services) - packages/core/src/storage/path.ts (add metrics path) Stats: - Production code: 1,374 lines - Test code: 1,681 lines - Tests: 62 passing - Build: ✅ Clean (5.046s) - Lint: ✅ 108 files, 0 errors Closes #148
- Create @lytics/dev-agent-types for GitHub types - Refactor GitHubService to use dependency injection - Update all adapters and tests to use new service patterns - Fix tsconfigs to exclude tests from dist builds - Clean stale build artifacts - Define GitHubIndexerInstance interface for type safety - Fix findRelated to return GitHubSearchResult[] with real scores - Add comprehensive tests for related action Changes: - GitHubService.findRelated() returns GitHubSearchResult[] (not GitHubDocument[]) - All mocks properly typed as GitHubIndexerInstance - Added adapter tests for 'related' action with score validation - Fixed search method to pass options directly Tests: All 1927 passing Build: All 9 packages clean Lint: All clean Net: -141 lines
- Optimize dev stats to read JSON directly (0.7s vs 7s, 10x faster) - Add visual progress bars and percentages to language breakdown - Display summary line with repo, files, components, storage, and age - Show git context (branch, commit, remote) in stats output - Add health indicators and actionable next steps - Upgrade dev storage info with clean table format and status icons - Remove logger timestamps from user-facing commands for cleaner output Bug Fixes: - Fix dev update bug where totalDocuments was set to batch size instead of querying actual LanceDB vector count, causing stats to show incorrect totals - Calculate total components from byLanguage sum for accuracy Output Improvements: - Consistent hybrid style across commands (gh CLI + docker inspired) - Tables for structured data with visual status indicators (✓, ⚠, ✗) - Progressive disclosure (important info first) - Human-readable sizes and relative timestamps - Maintained consistency with existing dev gh commands Breaking Changes: - dev stats no longer has 'show' subcommand (stats is now direct command) - Removed --verbose flag (detailed table is now default) Affects: #148 (Dashboard & Visualization epic)
- Remove logger timestamps from mcp list/install/uninstall commands - Add docker ps-inspired table format for mcp list - Clean install/uninstall success messages with next steps - Add health check spinner for server status - Fix variable name collision (output -> stdoutData/stderrData) Output Improvements: - mcp list: Tabular format with NAME, STATUS, COMMAND columns - mcp install: Clean success message with next steps and config path - mcp uninstall: Brief confirmation with restart reminder - Consistent with dev stats and dev storage info styles Before: [08:30:20] INFO MCP Servers in Cursor: [08:30:20] INFO dev-agent [08:30:20] INFO Command: dev mcp start After: NAME STATUS COMMAND dev-agent ✓ Active dev mcp start Total: 68 logger calls removed from MCP commands Affects: temp/cli-output-improvements-plan.md (Phase 2 complete)
- Remove logger timestamps from compact and clean commands - Add before/after comparison table for compact operations - Show file sizes and total storage to be removed in clean - Display optimization savings and performance metrics - Consistent styling with dev stats and dev mcp commands Output Improvements: - compact: Table comparing vectors, storage size, fragments with change percentages - clean: List of files with sizes, total to remove, clear warnings - Both commands now follow hybrid output style (docker + gh CLI inspired) Total logger calls removed: ~27 (12 from compact, 15 from clean) Affects: temp/cli-output-improvements-plan.md (Phases 3-4 complete)
- Remove logger timestamps from git stats command - Add clean summary with commit count and storage info - Consistent styling with other enhanced commands Affects: temp/cli-output-improvements-plan.md (Phase 5 complete)
Add comprehensive help text to major commands with: - Real-world examples with actual command syntax - Clear descriptions of what users will see - Related commands and tools - Setup instructions (for mcp) - Storage structure explanation (for storage) Commands Enhanced: - dev github --help Examples, related MCP tool info - dev mcp --help Setup steps, 9 available tools list - dev stats --help What statistics are shown - dev storage --help Storage location and structure Impact: - Improves discoverability without external docs - Always available (no website needed) - Context-aware help for each command - Zero maintenance (lives with code) Completes Option 1 from CLI documentation strategy. Next: CLI Quickstart page (separate PR)
Migrate two more MCP adapters to use the service layer with dependency injection for better testability and consistency. Adapters Refactored: - ExploreAdapter: Now uses SearchService for search() and findSimilar() - RefsAdapter: Now uses SearchService for all call graph queries Changes: - ExploreAdapterConfig: searchService replaces repositoryIndexer - RefsAdapterConfig: searchService replaces repositoryIndexer - Updated adapter instantiation in MCP server and CLI - Updated test mocks from mockIndexer to mockSearchService - Fixed similar code tests to use findSimilar() method - Removed unused imports (chalk, formatBytes, loadConfig) in CLI Benefits: - Consistent service layer usage across adapters - Better testability with dependency injection - Easier to mock for unit tests - Reduced coupling to implementation details Adapters by Refactoring Status: ✅ Service Layer (5/9): - SearchAdapter → SearchService - StatusAdapter → StatsService, GitHubService - GitHubAdapter → GitHubService - ExploreAdapter → SearchService - RefsAdapter → SearchService ⏭️ Thin Wrappers (4/9 - no refactor needed): - MapAdapter: Utility wrapper around generateCodebaseMap - HistoryAdapter: Uses GitIndexer (would need GitHistoryService) - PlanAdapter: Utility wrapper around assembleContext - HealthAdapter: Different interface than HealthService The remaining 4 adapters are already well-designed as thin wrappers around core utilities. Further refactoring would add complexity without providing testability or maintainability benefits. Tests: All 1918 tests passing Lint: No warnings or errors
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Summary
Refactored 5 of 9 MCP adapters to use the service layer with dependency injection for better testability and consistency.
Adapters Refactored ✅ (5/9)
SearchServiceStatsService,GitHubServiceGitHubServiceSearchServiceSearchServiceChanges
ExploreAdapter
SearchServiceinstead ofRepositoryIndexerfindSimilar()to usesearchService.findSimilar()RefsAdapter
SearchServiceinstead ofRepositoryIndexerTest Updates
mockIndexerwithmockSearchServicefindSimilar()Lint Fixes
clean.ts,compact.ts,git.tsRemaining Adapters ⏭️ (4/9 - Already Well-Designed)
The following adapters are thin wrappers around utilities and don't benefit from service layer refactoring:
generateCodebaseMap()utilityGitIndexer(would need newGitHistoryService)assembleContext()utilityHealthServiceBenefits
✅ Eliminated 100+ lines of duplicate indexer initialization code
✅ Consistent dependency injection pattern
✅ Better testability (easy to mock services)
✅ Reduced coupling to implementation details
✅ Zero lint warnings or errors
Testing
Related
Part of Dashboard & Visualization epic (#148)