PAIML MCP Agent Toolkit (pmat)
Zero-configuration AI context generation system that analyzes any codebase instantly through CLI, MCP, or HTTP interfaces. Built by Pragmatic AI Labs with extreme quality standards and zero tolerance for technical debt.
Toyota Way Success: Achieved 97% complexity reduction in stubs.rs through complete modular refactoring (v0.29.5). Project maintains zero tolerance standards: 0 SATD comments, 0 failing doctests, 0 failing property tests, 72+ comprehensive property tests, and proper separation of concerns across all components. Latest refactoring created dedicated modules (language_analyzer.rs, defect_formatter.rs, dead_code_formatter.rs) eliminating 549 lines of duplicated code while maintaining full functionality β
π Installation
Install pmat using one of the following methods:
-
From Crates.io (Recommended):
-
With the Quick Install Script (Linux only):
|macOS users: Please use
cargo install pmatinstead. Pre-built binaries are only available for Linux. -
From Source:
-
From GitHub Releases: Pre-built binaries for Linux are available on the releases page. macOS and Windows users should use
cargo install pmat.
Requirements
- Rust: 1.80.0 or later
- Git: For repository analysis
π Getting Started
Quick Start
# Analyze current directory
# Get complexity metrics for top 10 files
# Analyze specific files with include patterns
# Test with validated examples (try these!)
# Find technical debt
# Run comprehensive quality checks
Using as a Library
Add to your Cargo.toml:
[]
= "0.31.0"
Basic usage:
use ;
async
Key Features
π Code Analysis
- Deep Context Analysis - Comprehensive AST-based code analysis with defect prediction
- Complexity Analysis - Accurate McCabe cyclomatic and cognitive complexity metrics with AST-based precision
- β v0.28.6+: Fixed algorithm accuracy - now provides 100% correct complexity calculations
- Supports nested control flow, match statements, async functions, and complex branching
- Validated against manual calculations with comprehensive test examples
- Dead Code Detection - Find unused code across your project
- Technical Debt Gradient (TDG) - Quantify and prioritize technical debt
- SATD Detection - Find Self-Admitted Technical Debt in comments
- Code Duplication - Detect exact, renamed, gapped, and semantic clones
π οΈ Refactoring Tools
- AI-Powered Auto Refactoring -
pmat refactor autoachieves extreme quality standards- Single File Mode -
pmat refactor auto --single-file-mode --file path/to/file.rsfor targeted refactoring
- Single File Mode -
- Documentation Cleanup -
pmat refactor docsmaintains Zero Tolerance Quality Standards - Interactive Refactoring - Step-by-step guided refactoring with explanations
- Enforcement Mode - Enforce extreme quality standards using state machines
- Single File Mode -
pmat enforce extreme --file path/to/file.rsfor file-specific enforcement
- Single File Mode -
π Quality Gates & CI/CD Integration
- Lint Hotspot Analysis - Find files with highest defect density using EXTREME Clippy standards
- Single File Mode -
pmat lint-hotspot --file path/to/file.rsfor targeted analysis
- Single File Mode -
- Provability Analysis - Lightweight formal verification with property analysis
- Defect Prediction - ML-based prediction of defect-prone code
- Quality Enforcement - Exit with error codes for CI/CD integration
- NEW: All analyze commands now support
--fail-on-violationfor CI/CD pipelines - Exit code 0 on success, 1 when violations exceed thresholds
- Perfect for GitHub Actions, GitLab CI, Jenkins, and other CI/CD systems
- NEW: All analyze commands now support
π€ Agent Scaffolding (NEW)
- MCP Agent Templates - Generate deterministic MCP-compatible agents
- MCP Tool Server - Standard async MCP server with tool handlers
- State Machine Workflow - Agents with state transitions and invariants
- Deterministic Calculator - Pure computation agents
- Hybrid Analyzer - Deterministic core with AI wrapper
- Interactive Mode - Guided agent creation wizard
- Quality Enforcement - All generated agents meet Toyota Way standards
- Zero SATD comments
- Maximum complexity 10
- Comprehensive property tests
- Feature-Rich Templates - Support for monitoring, tracing, health checks
π§ Language Support
- Rust - Full support with cargo integration
- TypeScript/JavaScript - Modern AST-based analysis
- Python - Comprehensive Python 3 support
- Kotlin - Memory-safe parsing with full language support
- C/C++ - Tree-sitter based analysis
- WebAssembly - WASM binary and text format analysis
- AssemblyScript - TypeScript-like syntax for WebAssembly
- Makefiles - Specialized linting and analysis
π Tool Usage
CLI Interface
# Zero-configuration context generation
# Code analysis
# Analysis commands
# WebAssembly Support
# Project scaffolding
# Refactoring engine
# Demo and visualization
# Quality enforcement
MCP Integration
Using with Claude Code
# Add to Claude Code
Using the pmcp Rust SDK (NEW)
The MCP server can now be run using the pmcp Rust SDK for better type safety and async support:
// Run the MCP server with pmcp SDK
cargo run --example mcp_server_pmcp
// Or use as a library
use ;
use ;
let server = new
.with_tool
.with_tool
// ... add more tools
.build;
// Handle connections
server.handle_connection.await?;
The pmcp SDK provides:
- Type-safe tool definitions with proper async handling
- Built-in JSON-RPC 2.0 protocol implementation
- Automatic request/response serialization
- Connection lifecycle management
- Error handling and logging
Available MCP tools:
generate_template- Generate project files from templatesscaffold_project- Generate complete project structurescaffold_agent- Create MCP-compatible agents with templatesanalyze_complexity- Code complexity metrics with tool compositionanalyze_code_churn- Git history analysisanalyze_dag- Dependency graph generationanalyze_dead_code- Dead code detectionanalyze_deep_context- Comprehensive analysis with tool compositiongenerate_context- Zero-config context generationanalyze_big_o- Big-O complexity analysis with confidence scoresanalyze_makefile_lint- Lint Makefiles with 50+ quality rulesanalyze_proof_annotations- Lightweight formal verificationanalyze_graph_metrics- Graph centrality and PageRank analysisrefactor_interactive- Interactive refactoring with explanations
π MCP Tool Composition (NEW)
AI agents can now chain analysis tools using the --files parameter:
# Step 1: Find complexity hotspots
# Step 2: Deep analyze those specific files (MCP composition)
# Step 3: Target refactoring on problematic files
MCP Agent Workflow Example:
// AI agent discovers hotspots
const hotspots = await ;
// Agent extracts file paths and performs deep analysis
const detailed = await ;
// Agent generates targeted refactoring plan
const refactor = await ;
HTTP API
# Start server
# API endpoints
# POST analysis
π CI/CD Integration
All analyze commands now support --fail-on-violation for seamless CI/CD integration:
GitHub Actions Example
name: Code Quality
on:
jobs:
quality:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: dtolnay/rust-toolchain@stable
- name: Install pmat
run: cargo install pmat
- name: Check Complexity
run: |
pmat analyze complexity \
--max-cyclomatic 15 \
--max-cognitive 10 \
--fail-on-violation
- name: Check Technical Debt
run: pmat analyze satd --strict --fail-on-violation
- name: Check Dead Code
run: |
pmat analyze dead-code \
--max-percentage 10.0 \
--fail-on-violation
- name: Run Quality Gate
run: pmat quality-gate --fail-on-violation
Configurable Thresholds
- Complexity:
--max-cyclomatic(default: 20),--max-cognitive(default: 15) - Dead Code:
--max-percentage(default: 15.0%) - SATD: Fails on ANY technical debt when using
--fail-on-violation
Exit Codes
- 0: Success - no violations found or within thresholds
- 1: Failure - violations exceed configured thresholds
See examples/ci_integration.rs for more CI/CD patterns including GitLab CI, Jenkins, and pre-commit hooks.
Recent Updates
π v0.29.6 - Critical Bug Fixes
- Fixed Quality Gate Bug: Quality gate dead code detection now correctly analyzes code instead of always reporting violations
- Fixed Include Patterns:
--includepatterns now properly work with test directories (e.g.,--include "tests/**/*.rs") - Fixed Clippy Warning: Replaced deprecated
map_orwithis_some_andfor cleaner code
π v0.28.14 - Toyota Way Kaizen Success
- Massive Complexity Reduction: Core
handle_refactor_autofunction complexity reduced from 136 β 21 (84% reduction) - Zero Quality Violations: Project now maintains 0 lint violations, 0 max complexity, 0 SATD comments
- Toyota Way Implementation: Applied Kaizen (continuous improvement), Genchi Genbutsu (go and see), Jidoka (quality at source), and Poka-Yoke (error-proofing) principles
- Code Size Optimization: Net reduction of 3,401 lines while improving functionality and maintainability
- Comprehensive Testing: Added extensive property tests, doctests, and unit tests for all refactored components
- Zero Compromise: No hacks, shortcuts, or technical debt introduced during refactoring
π¦ v0.28.9 - CI/CD Integration & Exit Codes
- CI/CD Support: All analyze commands now support
--fail-on-violationflag - Exit Codes: Commands exit with code 1 when violations exceed thresholds
- Configurable Thresholds: Added
--max-percentagefor dead-code analysis - Examples: Added comprehensive CI/CD examples for GitHub Actions, GitLab CI, Jenkins
- Documentation: Updated all documentation with CI/CD integration patterns
π v0.28.3 - Enhanced Single-File Analysis
- Single File Analysis: Added
--fileflag topmat analyze comprehensivefor analyzing individual files. - Bug Fix: Fixed "No such file or directory" error in single-file refactor mode by using dynamic executable path detection.
- Test Improvements: Fixed stack overflow issues in CLI tests by using wildcard pattern matching.
- Documentation: Updated CLI reference with new single-file analysis capabilities.
π¦ v0.28.2 - Quality Gate Improvements
- Quality Gate Tests: Added comprehensive integration tests for CI/CD quality gates.
- Public API: Made quality gate structs public for better testing support.
- Doctests: Added doctests for quality gate and DAG generation functions.
- Bug Fixes: Fixed mermaid test failures and unused import warnings.
π v0.26.3 - Quality Uplift
- SATD Elimination: Removed all TODO/FIXME/HACK comments from implementation.
- Complexity Reduction: All functions now below a cyclomatic complexity of 20.
- Extreme Linting:
make lintpasses with pedantic and nursery standards. - Single File Mode: Enhanced support for targeted quality improvements.
π§Ή v0.26.1 - Documentation Cleanup (pmat refactor docs)
- AI-assisted documentation cleanup to maintain Zero Tolerance Quality Standards.
- Identifies and removes temporary files, outdated reports, and build artifacts.
- Interactive mode for reviewing files before removal with automatic backups.
π₯ v0.26.0 - New Analysis Commands
- Graph Metrics:
pmat analyze graph-metricsfor centrality analysis. - Name Similarity:
pmat analyze name-similarityfor fuzzy name matching. - Symbol Table:
pmat analyze symbol-tablefor symbol extraction. - Code Duplication:
pmat analyze duplicatesfor detecting duplicate code.
Toyota Way Quality Standards
This project exemplifies the Toyota Way philosophy through disciplined quality practices:
Kaizen (ζΉε) - Continuous Improvement
- 84% Complexity Reduction: Achieved through systematic refactoring
- Zero Quality Violations: Maintained through iterative improvement
- Net -3,401 Lines: Simplified while enhancing functionality
Genchi Genbutsu (ηΎε°ηΎη©) - Go and See
- Data-Driven Decisions: Used actual metrics to identify complexity hotspots
- Root Cause Analysis: Fixed underlying architectural issues, not symptoms
- Measurement-Based: Every improvement verified through quantitative analysis
Jidoka (θͺεε) - Quality at Source
- ZERO SATD: No TODO, FIXME, HACK, or placeholder implementations
- ZERO High Complexity: No function exceeds cyclomatic complexity of 20
- ZERO Known Defects: All code must be fully functional
- ZERO Incomplete Features: Only complete, tested features are merged
Poka-Yoke (γγ«γ¨γ±) - Error Prevention
- Comprehensive Testing: Property tests, doctests, and unit tests prevent regressions
- Automated Quality Gates: CI/CD integration prevents quality degradation
- Type Safety: Rust's type system eliminates entire categories of errors
π Output Formats
- JSON - Structured data for tools and APIs
- Markdown - Human-readable reports
- SARIF - Static analysis format for IDEs
- Mermaid - Dependency graphs and diagrams
π― Use Cases
For AI Agents
- Context Generation: Give AI perfect project understanding
- Code Analysis: Deterministic metrics and facts
- Template Generation: Scaffolding with best practices
For Developers
- Code Reviews: Automated complexity and quality analysis
- Technical Debt: SATD detection and prioritization
- Onboarding: Quick project understanding
- CI/CD: Integrate quality gates and analysis
For Teams
- Documentation: Auto-generated project overviews
- Quality Gates: Automated quality scoring
- Dependency Analysis: Visual dependency graphs
- Project Health: Comprehensive health metrics
π¦ CI/CD Quality Gates
GitHub Actions Integration
# .github/workflows/quality.yml
- name: Run Quality Gate
run: |
pmat quality-gate \
--checks complexity,satd,security,dead-code \
--max-complexity-p99 20 \
--fail-on-violation
Available Quality Checks
- complexity - Cyclomatic complexity thresholds
- satd - Self-admitted technical debt (TODO/FIXME/HACK)
- security - Hardcoded passwords and API keys
- dead-code - Unused functions and variables
- entropy - Code diversity metrics
- duplicates - Code duplication detection
- coverage - Test coverage thresholds
- sections - Required documentation sections
- provability - Formal verification readiness
π Documentation
Explore our comprehensive documentation to get the most out of pmat.
Getting Started
- Architecture: Understand the system design and principles.
- CLI Reference: View the full command-line interface guide.
- API Documentation: Browse the complete Rust API documentation on docs.rs.
Usage Guides
- Feature Overview: Discover all available features.
- MCP Integration: Learn how to integrate
pmatwith AI agents. - CI/CD Integration: Set up quality gates in your CI/CD pipeline.
Development
- Contributing Guide: Read our guidelines for contributing to the project.
- Release Process: Follow our step-by-step release workflow.
π οΈ System Operations
Memory Management
For systems with low swap space, we provide a configuration tool:
π§ͺ Testing
The project uses a distributed test architecture for fast feedback:
# Run specific test suites
# Run all tests in parallel
# Coverage analysis
π€ Contributing
We welcome contributions! Please see our Contributing Guide for details.
Quick Start for Contributors
# Clone and setup
# Install dependencies
# Run tests
# Check code quality
Development Workflow
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Make your changes following our Zero Tolerance Quality Standards
- Run quality checks before committing:
- Submit a pull request with a clear description of changes
Note: The make test command runs comprehensive testing including:
- β‘ Fast unit and integration tests
- π Documentation tests (doctests)
- π² Property-based tests
- π All cargo examples
See CONTRIBUTING.md for detailed guidelines.
π License
Licensed under either of:
- Apache License, Version 2.0 (LICENSE-APACHE)
References
- MIT license (LICENSE-MIT)
at your option.
Built with β€οΈ by Pragmatic AI Labs