π¨βπ» Development Guide
Contributing to the SFCC Development MCP Server project
π Getting Started
Prerequisites
- Node.js 18 or higher
- npm 8 or higher
- Git for version control
- TypeScript knowledge recommended
Local Development Setup
# Clone the repository
git clone https://github.com/taurgis/sfcc-dev-mcp.git
cd sfcc-dev-mcp
# Install dependencies
npm install
# Build TypeScript
npm run build
# Run tests
npm test
# Start in development mode
npm run dev -- --dw-json /Users/username/sfcc-project/dw.jsonποΈ Project Architecture
Surface: 36+ specialized tools spanning documentation, best practices, SFRA, cartridge generation, runtime logs, job logs, system & custom objects, site preferences, and code versions.
Directory Structure
sfcc-dev-mcp/
βββ src/
β βββ main.ts # CLI entry point
β βββ index.ts # Package exports
β βββ core/ # Core MCP server & tool definitions
β β βββ server.ts # MCP server (registers handlers, capability gating)
β β βββ tool-definitions.ts # All tool schemas grouped by category
β β βββ handlers/ # Modular tool handlers
β β βββ base-handler.ts
β β βββ docs-handler.ts
β β βββ best-practices-handler.ts
β β βββ sfra-handler.ts
β β βββ log-handler.ts
β β βββ job-log-handler.ts
β β βββ system-object-handler.ts
β β βββ code-version-handler.ts
β β βββ cartridge-handler.ts
β βββ clients/ # API & domain clients (logic, not routing)
β β βββ base/ # Shared HTTP + auth
β β β βββ http-client.ts
β β β βββ ocapi-auth-client.ts
β β β βββ oauth-token.ts
β β βββ logs/ # Modular log system (composition)
β β β βββ log-client.ts # Orchestrator
β β β βββ webdav-client-manager.ts # WebDAV auth + setup
β β β βββ log-file-reader.ts # Range / tail reads
β β β βββ log-file-discovery.ts # Listing & filtering
β β β βββ log-processor.ts # Parsing & normalization
β β β βββ log-analyzer.ts # Pattern & health analysis
β β β βββ log-formatter.ts # Output shaping
β β β βββ log-constants.ts # Central constants/config
β β β βββ log-types.ts # Type definitions
β β βββ docs/ # Modular documentation system
β β β βββ documentation-scanner.ts
β β β βββ class-content-parser.ts
β β β βββ class-name-resolver.ts
β β β βββ referenced-types-extractor.ts
β β β βββ index.ts
β β βββ docs-client.ts
β β βββ sfra-client.ts
β β βββ best-practices-client.ts
β β βββ cartridge-generation-client.ts
β β βββ ocapi/
β β β βββ site-preferences-client.ts
β β β βββ system-objects-client.ts
β β βββ ocapi-client.ts
β β βββ log-client.ts # Backwards compat wrapper
β βββ best-practices-client.ts # (already listed above? keep once)
β βββ services/ # Dependency injection service layer
β β βββ file-system-service.ts
β β βββ path-service.ts
β β βββ index.ts
β βββ tool-configs/ # Tool grouping & category configs
β β βββ docs-tool-config.ts
β β βββ sfra-tool-config.ts
β β βββ best-practices-tool-config.ts
β β βββ log-tool-config.ts
β β βββ job-log-tool-config.ts
β β βββ system-object-tool-config.ts
β β βββ cartridge-tool-config.ts
β β βββ code-version-tool-config.ts
β βββ config/
β β βββ configuration-factory.ts # Mode & capability resolution
β β βββ dw-json-loader.ts # Secure dw.json loading
β βββ utils/
β β βββ cache.ts
β β βββ logger.ts
β β βββ path-resolver.ts
β β βββ query-builder.ts
β β βββ utils.ts
β β βββ validator.ts
β βββ types/
β βββ types.ts
βββ tests/ # Jest + MCP YAML + programmatic tests
β βββ *.test.ts
β βββ mcp/yaml/*.mcp.yml # Declarative tool tests
β βββ mcp/node/*.programmatic.test.js
β βββ servers/webdav/ # Mock WebDAV server fixtures
βββ docs/ # SFCC & best practices markdown sources
βββ docs-site/ # React + Vite documentation site
βββ scripts/ # Conversion & build scripts
βββ ai-instructions/ # AI platform instruction setsConfiguration & Capability Gating (src/config/)
- configuration-factory.ts: Determines operating mode & derives capabilities (
canAccessLogs,canAccessJobLogs,canAccessOCAPI,canAccessSitePrefs). - dw-json-loader.ts: Safe credential ingestion, prevents accidental misuse.
- Capability Gating: No credentials β docs & best practice tools only; WebDAV creds β runtime + job logs; Data API creds β system & custom objects, site preferences, code versions.
- Least Privilege: Tools requiring unavailable capabilities never registered.
Adding New Tools (Updated Flow)
- Define schema in correct category array inside
tool-definitions.ts. - Decide placement β extend existing handler or create new handler extending
BaseToolHandler. - Implement logic inside a client/service (keep handler thin).
- Register handler only if new category (update
registerHandlers()inserver.ts). - Discover response format: Run with
npx aegis query [tool]BEFORE writing tests; capture real JSON shape. - Add tests: Jest unit + YAML (docs & full mode as applicable) + programmatic Node tests if complex.
- Update docs: This page + README + copilot instructions when categories/counts change.
Testing Strategy
Programmatic MCP tests must use Node test runner (e.g. node --test tests/mcp/node/your-test.programmatic.test.js) β do NOT invoke via npm test -- file (Jest only).
Unit Tests
# Run all tests
npm test
# Run specific test file
npm test base-http-client.test.ts
# Run with coverage
npm run test:coverage
# Watch mode for development
npm run test:watchAvailable Test Scripts
# Core testing scripts from package.json
npm test # Run all tests with Jest
npm run test:watch # Run tests in watch mode
npm run test:coverage # Run tests with coverage report
# Linting and code quality
npm run lint # Check code style
npm run lint:fix # Auto-fix linting issues
npm run lint:check # Check with zero warningsManual Testing
# Test with real SFCC instance (create your own test-dw.json)
npm run dev -- --dw-json /Users/username/sfcc-project/test-dw.json --debug
# Test documentation-only mode
npm run dev -- --debugπ Documentation Updates
Updating SFCC Documentation
1. Add/Update Markdown Files in docs/:
# Add new class documentation
echo "# NewClass\n\nDescription..." > docs/dw_catalog/NewClass.md2. Run Documentation Conversion:
# Convert and process documentation (requires axios and cheerio)
npm run convert-docs
# Test with limited conversion
npm run convert-docs:test
# Limited conversion (5 files)
npm run convert-docs:limit3. Test Documentation Tools:
# Test documentation access with your changes
npm run dev -- --debug true
# Then use MCP client to test get_sfcc_class_info with "NewClass"Updating Documentation Site
The documentation site (docs-site/) is a React + Vite app. Deployment is handled by GitHub Actions after changes are pushed to the default branch.
- Edit Content: Modify or add pages/components under
docs-site/. - Local Preview:bash
cd docs-site npm install npm run dev # Opens Vite dev server (default http://localhost:5173) - Build (optional check):bash
cd docs-site npm run build # Generates dist/ with static assets - Push Changes: CI workflow publishes the built site to GitHub Pages.
- Search Index / Sitemap: Automatically generated via build scripts (
generate:search-index,generate:sitemap).
π― Coding Standards
TypeScript Guidelines
// Use explicit types
interface ToolParams {
readonly query: string;
readonly limit?: number;
}
// Use proper error handling
async function riskyOperation(): Promise<Result> {
try {
return await performOperation();
} catch (error) {
this.logger.error('Operation failed', { error: error.message });
throw new OperationError('Failed to perform operation', error);
}
}
// Use meaningful names
const searchProductsByCategory = (categoryId: string) => {
// Implementation
};Code Organization
- Single Responsibility: Each class/function has one clear purpose
- Dependency Injection: Use constructor injection for dependencies
- Error Boundaries: Proper error handling at service boundaries
- Logging: Comprehensive logging for debugging and monitoring
Git Workflow
# Create feature branch from develop
git checkout develop
git pull origin develop
git checkout -b feature/new-tool-name
# Make atomic commits
git add src/clients/my-client.ts
git commit -m "feat: add my new tool implementation"
git add tests/my-client.test.ts
git commit -m "test: add unit tests for my new tool"
git add docs-site/tools.md
git commit -m "docs: update tools documentation"
# Push and create PR to develop branch
git push origin feature/new-tool-nameCommit Message Convention:
feat:- New featuresfix:- Bug fixesdocs:- Documentation updatestest:- Test additions/modificationsrefactor:- Code refactoringchore:- Build process or auxiliary tool changes
π§ͺ Testing Best Practices
Test Structure
describe('FeatureName', () => {
let client: MyClient;
let mockHttpClient: jest.Mocked<HttpClient>;
beforeEach(() => {
mockHttpClient = createMockHttpClient();
client = new MyClient(mockHttpClient, mockLogger);
});
describe('methodName', () => {
it('should handle success case', async () => {
// Arrange
const input = { query: 'test' };
const mockResponse = { data: 'mock response' };
mockHttpClient.get.mockResolvedValue(mockResponse);
// Act
const result = await client.methodName(input);
// Assert
expect(result).toBeDefined();
expect(mockHttpClient.get).toHaveBeenCalledWith('/expected/path');
});
it('should handle error case', async () => {
// Arrange
const input = { query: 'test' };
mockHttpClient.get.mockRejectedValue(new Error('Network error'));
// Act & Assert
await expect(client.methodName(input)).rejects.toThrow('Network error');
});
});
});Mock Strategy
// Mock external dependencies using Jest
const mockLogger = {
info: jest.fn(),
error: jest.fn(),
debug: jest.fn(),
warn: jest.fn()
};
// Use factories for complex mocks
const createMockSFCCResponse = (overrides = {}) => ({
statusCode: 200,
headers: { 'content-type': 'application/json' },
data: 'Mock response data',
...overrides
});Testing Coverage Overview
- Unit Clients: HTTP/auth, OCAPI subclients, docs, SFRA, best practices, cartridge generation.
- Handlers: Each modular handler has focused tests (error shaping, capability filtering).
- Log System: Discovery, reader, processor, analyzer, formatter modules.
- Job Logs: Parsing & multi-level consolidation logic.
- MCP Protocol Tests: YAML declarative + programmatic (Node) in
tests/mcp/. - WebDAV Mock: Integration environment for log + job retrieval.
Handler Architecture
- BaseToolHandler: Central timing, error normalization, logger integration.
- Category Isolation: Each functional domain kept small & cohesive.
- Extensibility: New feature area β new handler; minimal churn to existing code.
- Testing Benefit: Handlers test orchestration; clients test domain logic.
Services & Dependency Injection
- FileSystemService & PathService: Abstract Node APIs for test isolation.
- Client Composition: Pass services or mocks explicitlyβno hidden globals.
- Deterministic Tests: Avoids brittle fs/path mocking at module level.
Log & Job Log Architecture
- Reader: Range tail reads minimize bandwidth.
- Processor: Normalizes raw lines β structured entries.
- Analyzer: Pattern extraction, severity grouping, health scoring.
- Formatter: Produces human-oriented summaries for MCP output.
- Job Logs: Unified multi-level log files consolidated logically.
Tool Config Modules
Each tool-configs/*.ts file groups logically related tool definitions or export sets, enabling cleaner segregation and future dynamic registration strategies.
Caching & Performance
- cache.ts: In-memory response caching (documentation & static lookups).
- log-cache.ts: Specialized transient caching for recently tailed segments.
- Avoid Premature I/O: Lazy fetch patterns in log discovery & system objects.
- Capability Filter: Reduces surface area β fewer accidental expensive calls.
π Release Process
Version Management
# Update version
npm version patch # 1.0.0 β 1.0.1
npm version minor # 1.0.0 β 1.1.0
npm version major # 1.0.0 β 2.0.0
# Push tags
git push origin main --tagsRelease Checklist
1. Update Documentation
- README.md tool counts & feature surface (36+ phrasing)
ai-instructions/github-copilot/copilot-instructions.mdarchitecture updates.github/copilot-instructions.md(sync architecture + counts)- Configuration & Features pages updated if capability surface changed
- CHANGELOG.md entry (if present)
2. Testing
- All unit tests pass (
npm test) - Linting passes (
npm run lint:check) - Manual testing with real SFCC instance
- Documentation-only mode validation
- Build succeeds (
npm run build)
3. Build & Package
- TypeScript compilation successful
- Package size reasonable
- Dependencies audit clean (
npm audit)
4. Release
- GitHub release with changelog
- npm publish (automated via
.github/workflows/publish.yml) - Documentation deployment (automated)
π€ Contributing Guidelines
Before Contributing
- Check Existing Issues: Search for existing issues or discussions
- Discuss Large Changes: Open an issue for significant modifications
- Follow Conventions: Adhere to established coding and commit patterns
Pull Request Process
- Fork & Branch: Create feature branch from
develop - Implement Changes: Follow coding standards and testing requirements
- Update Documentation: Ensure documentation reflects changes
- Test Thoroughly: All tests must pass (
npm test,npm run lint:check) - Submit PR: Provide clear description and link to related issues
Code Review
- GitHub Actions: CI pipeline must pass (see
.github/workflows/ci.yml) - Code Quality: ESLint and TypeScript checks must pass
- Test Coverage: Maintain or improve test coverage
- Documentation: Ensure user-facing changes are documented
π Performance Considerations
Optimization Guidelines
- Caching Strategy: Implement intelligent caching for API responses
- Rate Limiting: Respect SFCC API limits and implement backoff
- Memory Management: Monitor memory usage, especially for large datasets
- Asynchronous Operations: Use proper async/await patterns
Monitoring
// Performance monitoring example
const startTime = Date.now();
try {
const result = await performOperation();
this.metrics.recordSuccess('operation_name', Date.now() - startTime);
return result;
} catch (error) {
this.metrics.recordError('operation_name', Date.now() - startTime);
throw error;
}π Security Considerations
Credential Handling
- No Hardcoding: Never commit credentials to repository
- Secure Storage: Use appropriate credential storage mechanisms
- Minimal Permissions: Request only necessary permissions
- Rotation Support: Design for credential rotation
Input Validation
// Validate all inputs using proper TypeScript types
import { ToolResponse, ValidationError } from '../types/types.js';
interface ToolParams {
readonly query: string;
readonly limit?: number;
}
function validateToolInput(input: unknown): ToolParams {
if (!input || typeof input !== 'object') {
throw new ValidationError('Input must be an object');
}
const { query, limit } = input as any;
if (!query || typeof query !== 'string') {
throw new ValidationError('Query is required and must be a string');
}
if (query.length > 1000) {
throw new ValidationError('Query must be 1000 characters or less');
}
if (limit !== undefined && (typeof limit !== 'number' || limit < 1 || limit > 100)) {
throw new ValidationError('Limit must be a number between 1 and 100');
}
return { query, limit };
}Next Steps
- π Contributing Guidelines - Detailed contribution process
- ποΈ Issues & Features - Report bugs or request features
- π¬ Discussions - Community discussions and Q&A
- π GitHub Actions - View CI/CD pipeline status