Skip to main content
Glama
Workflow Intelligence MCP

Workflow Intelligence MCP

by coder-aadii

Workflow Intelligence MCP


Executive Summary

Enterprise businesses rely on complex webs of workflow engines, ERP systems, databases, and manual approval chains. While workflow engines like Temporal and n8n excel at executing predefined sequences, organizations face critical operational hurdles:

  • Invisible Inefficiencies: Undetected approval queues, unnecessary activity repetitions, and human handoff delays.

  • Fragile Exception Handling: Workflows that halt abruptly due to minor schema drifts, missing vendor records, or data mismatches, requiring tedious manual triage.

  • Unexplained Metric Deviations: Operational costs spike or SLA cycle times inflate, but operational dashboards only show what happened, not why it happened or which source records caused it.

Workflow Intelligence MCP is a specialized Model Context Protocol server that sits alongside workflow engines as a dedicated process intelligence, exception reasoning, and business decision layer.

┌────────────────────────────────────────────────────────────────────────┐
│                      WORKFLOW INTELLIGENCE MCP                         │
├──────────────────────────┬─────────────────────────┬───────────────────┤
│ 1. Process Discovery     │ 2. Exception Resolver   │ 3. Decision Intel │
│    Engine (`process_`)   │    (`exception_`)       │    (`decision_`)  │
├──────────────────────────┼─────────────────────────┼───────────────────┤
│ • Event log ingestion    │ • Exception triage      │ • KPI deviation   │
│ • PM4Py reconstruction   │ • Context retrieval     │   root-cause      │
│ • Bottleneck detection   │ • Recovery suggestions  │ • DuckDB analysis │
│ • Automation scoring     │ • Escalation routing    │ • Evidence briefs │
└──────────────────────────┴─────────────────────────┴───────────────────┘

Related MCP server: exception-mcp-server

Core Differentiators

  1. Intelligence, Not Execution: Complements existing workflow orchestrators (Temporal, n8n) rather than replacing them.

  2. Deterministic Computing: All metrics, aggregations, process graphs, and numerical KPIs are computed using deterministic code (PM4Py, DuckDB, Pandas, SQL). LLMs are strictly employed for narrative synthesis, report formulation, and natural language explanations—never for raw calculation.

  3. Verifiable Data Provenance: Every insight, recommendation, and brief generated by the server links explicitly to underlying dataset identifiers, record primary keys, and query logic.


System Architecture

The server adheres to a strict, modular layered architecture where MCP handlers remain thin transport layers that delegate directly to isolated application services and adapters.

flowchart TD
    Client["MCP Clients\n(Claude Desktop / Cursor / Custom Agents)"]
    
    subgraph MCP_Protocol ["MCP Protocol Layer"]
        Transport["FastMCP Server\n(STDIO / Streamable HTTP)"]
        Handlers["Thin Tool & Resource Handlers"]
    end
    
    subgraph Validation ["Validation & Security Layer"]
        Pydantic["Pydantic V2 Schemas\n(Input / Output Contracts)"]
        AuthZ["Authorization & Access Policy"]
    end
    
    subgraph Services ["Application Services"]
        PS["ProcessService\n(Process Mining & Reconstruction)"]
        ES["ExceptionService\n(Triage & Root Cause Resolution)"]
        DS["DecisionService\n(KPI & Decision Briefs)"]
        AS["AnalyticsService\n(DuckDB Query Engine)"]
        EVS["EvidenceService\n(Record Matching & Provenance)"]
    end
    
    subgraph Adapters ["Integration Adapters"]
        PMAdapter["PM4Py Adapter"]
        DuckAdapter["DuckDB / SQL Adapter"]
        WorkflowAdapter["Temporal / n8n Adapters"]
        FileAdapter["CSV / JSON / Parquet Loaders"]
    end
    
    subgraph Storage ["Persistence & State"]
        PG[(PostgreSQL)]
        Duck[(In-Memory / Local DuckDB)]
        Redis[(Redis Cache)]
    end

    Client <--> Transport
    Transport --> Handlers
    Handlers --> Pydantic
    Pydantic --> AuthZ
    AuthZ --> Services
    PS --> PMAdapter
    ES --> WorkflowAdapter
    ES --> EVS
    DS --> AS
    AS --> DuckAdapter
    DuckAdapter --> Duck
    WorkflowAdapter --> PG
    WorkflowAdapter --> Redis
    PMAdapter --> FileAdapter

The Three Core MCP Tools

1. Process Discovery Engine (process_*)

Ingests operational event logs, reconstructs execution paths using process mining, identifies systemic bottlenecks, and calculates objective automation suitability scores.

Tool Name

Parameters

Output Schema

Purpose

process_analyze_business_process

source_uri (str)case_id_col (str)activity_col (str)timestamp_col (str)

ProcessAnalysisResult

Ingests event logs, computes transition matrices, case statistics, and path variants.

process_identify_bottlenecks

source_uri (str)threshold_std_dev (float, default 2.0)

BottleneckReport

Detects abnormal queue durations, repeated task loops, and departmental handoff delays.

process_score_automation_opportunities

source_uri (str)min_frequency (int, default 10)

AutomationScoreReport

Evaluates repetitive activities against volume, variance, and manual touchpoints to rank automation targets.

Example Invocations & Output

// Tool: process_identify_bottlenecks
{
  "source_uri": "sample-data/procurement_events.csv",
  "threshold_std_dev": 2.0
}
// Response
{
  "total_cases_analyzed": 1420,
  "bottlenecks": [
    {
      "stage": "Finance Approval -> Vendor Selection",
      "avg_duration_hours": 74.2,
      "baseline_duration_hours": 12.0,
      "deviation_score": 3.8,
      "primary_cause": "Pending manual budget verification",
      "affected_case_count": 312
    }
  ],
  "recommendations": [
    "Introduce automated budget pre-checks for purchase requisitions under $5,000."
  ]
}

2. Workflow Exception Resolver (exception_*)

Investigates execution failures across automated pipelines, fetches contextual records from databases or workflow histories, reconciles discrepancies, and determines safe recovery or escalation paths.

Tool Name

Parameters

Output Schema

Purpose

exception_investigate_workflow

case_id (str)workflow_type (str)failure_payload (dict)

ExceptionInvestigationResult

Classifies failures (validation, API timeout, record mismatch) and gathers case history.

exception_recommend_resolution

exception_id (str)policy_context (dict, optional)

ResolutionPlan

Produces actionable remediation steps (e.g., entity deduplication, automated retry, or manual correction).

exception_escalate_case

case_id (str)reason (str)target_department (str)

EscalationResult

Routes unresolvable or high-risk exceptions to authorized human operators with full audit context.

Example Invocation & Output

// Tool: exception_investigate_workflow
{
  "case_id": "PO-10042",
  "workflow_type": "purchase_order_creation",
  "failure_payload": {
    "error_code": "VENDOR_RECORD_MISMATCH",
    "submitted_name": "ABC Logistics LLC",
    "tax_identifier": "TX-992140"
  }
}
// Response
{
  "investigation_id": "INV-8831",
  "case_id": "PO-10042",
  "root_cause_category": "Data Discrepancy",
  "explanation": "Submitted vendor 'ABC Logistics LLC' matches registered entity 'ABC Logistics Global Inc' with 98% confidence on tax ID 'TX-992140'.",
  "matched_records": [
    { "entity_id": "VEND-00412", "registered_name": "ABC Logistics Global Inc" }
  ],
  "can_auto_resolve": true,
  "recommended_action": "Remap vendor_id to VEND-00412 and resume workflow step: dispatch_po."
}

3. Business Decision Intelligence (decision_*)

Executes high-performance analytical queries using embedded DuckDB to evaluate business KPI shifts, identify underlying contributing segments, and produce verifiable decision briefs.

Tool Name

Parameters

Output Schema

Purpose

decision_analyze_kpi_performance

metric_name (str)source_uri (str)timeframe_current (str)timeframe_baseline (str)timeframe_column (str, default "timeframe")custom_expression (str, optional)

PerformanceAnalysisResult

Evaluates deterministic KPI variance across periods over any CSV/Parquet dataset with zero hardcoding.

decision_explain_kpi_deviation

metric_name (str)source_uri (str)timeframe_current (str)timeframe_baseline (str)observed_delta (float)timeframe_column (str, default "timeframe")dimension (str, optional)custom_expression (str, optional)

DeviationExplanation

Explains variance drivers with dynamic dimension inference and statistical significance indicators.

decision_generate_brief

topic (str)metric_ids (list[str])

DecisionBrief

Synthesizes verified numbers, root causes, and recommended actions into an executive-ready brief with SHA-256 provenance links.

Example Output: Structured Decision Brief

# Operational Decision Brief: Q3 Procurement Cost Inflation
**Generated:** 2026-11-12 | **Target:** Operations & Procurement Leadership

### Executive Summary
Procurement processing costs experienced an increase of **+28.4%** ($68,000 vs. $52,000 baseline).

### Key Contributing Drivers (Verified via DuckDB)
- **Emergency Expedited Shipping:** Accounted for **64%** of cost increase across 32 purchase orders.
- **Supplier Off-Contract Orders:** Department 'Engineering Hardware' placed 41% of requests outside preferred vendor catalogs.

### Supporting Evidence & Provenance
- Dataset: `sample-data/procurement_costs.csv`
- Records Evaluated: 1,420 transactions
- Verified Calculation: `AVG(cost_per_order)` shifted from $49.52 to $65.21 ($p < 0.01$).

### Recommended Interventions
1. Implement vendor catalog constraints for requisitions exceeding $2,500.
2. Automate lead-time notifications to eliminate rush-order delivery fees.

MCP Resources & Prompts

In addition to tools, Workflow Intelligence MCP exposes standardized protocol primitives:

MCP Resources

  • workflow://process-maps/{process_name}: Dynamic Directly-Follows Graphs resolved from any registered event log in sample-data/.

  • workflow://exceptions/active: Real-time index of open workflow exceptions and priority queues from ExceptionRepository.

  • workflow://metrics/kpi-definitions: Deterministic SQL definitions and calculation formulas.

  • workflow://audit/recent: Recent immutable audit trail entries capturing system decisions and escalations.

MCP Prompts

  • process_bottleneck_review: Pre-structured prompt for comprehensive operational workflow analysis.

  • exception_triage_session: Interactive step-by-step assistant for reconciling ambiguous case failures.

  • management_decision_brief: Standardized template for generating executive operational reports.


End-to-End Walkthrough: Procurement Lifecycle

The server demonstrates its integrated intelligence loop through a single end-to-end procurement process:

Step 1: Discover
Event Logs Ingested ──► PM4Py detects 74-hour approval queues in Finance.
                        Score ranking identifies 'Requisition Approval' as #1 automation target.
        │
        ▼
Step 2: Resolve
Execution Halts    ──► A high-value PO fails at vendor dispatch.
                        Exception service triages fuzzy vendor mismatch, retrieves tax record,
                        and safely auto-heals the workflow with full audit logging.
        │
        ▼
Step 3: Decide
Quarterly Review   ──► Executive asks: 'Why did procurement costs spike 28%?'
                        Decision Intelligence queries transaction logs, attributes the increase
                        to rush delivery fees caused by the upstream approval bottleneck,
                        and drafts an evidence-backed decision brief.

Installation & Quickstart

Prerequisites

  • Python >= 3.12

  • Docker & Docker Compose (Optional, for containerized deployment)

1. Local Setup

# Clone the repository
git clone git@github-coder-aadii:coder-aadii/Workflow-Intelligence-MCP.git
cd Workflow-Intelligence-MCP

# Create and activate virtual environment
python3 -m venv .venv
source .venv/bin/activate

# Install package and dependencies in editable mode
pip install -e ".[dev]"

2. Environment Configuration

cp .env.example .env
# Edit .env to set your database or analytical paths

3. Running the Server

Run via Standard I/O (STDIO)

python -m workflow_intelligence.server

Run via Streamable HTTP (SSE / Remote)

python -m workflow_intelligence.server --transport sse --port 8000

MCP Client Configuration

Claude Desktop Configuration

Add the server definition to your claude_desktop_config.json:

{
  "mcpServers": {
    "workflow-intelligence": {
      "command": "/path/to/Workflow-Intelligence-MCP/.venv/bin/python",
      "args": ["-m", "workflow_intelligence.server"],
      "env": {
        "WORKFLOW_ENV": "development",
        "DATABASE_URL": "postgresql+asyncpg://postgres:postgres@localhost:5432/workflow_intelligence"
      }
    }
  }
}

Cursor IDE Configuration

In Cursor's Features > MCP Servers settings:

  • Name: workflow-intelligence

  • Type: command

  • Command: python -m workflow_intelligence.server


Environment Variables Reference

Variable

Description

Default

WORKFLOW_ENV

Application environment (development, staging, production)

development

SERVER_TRANSPORT

MCP transport mechanism (stdio, sse)

stdio

SERVER_HOST

Host address for SSE transport

127.0.0.1

SERVER_PORT

Port for SSE transport

8000

DATABASE_URL

PostgreSQL connection string

postgresql+asyncpg://postgres:postgres@localhost:5432/workflow_intel

DUCKDB_PATH

Path to persistent DuckDB file (or :memory:)

:memory:

REDIS_URL

Redis URL for workflow caching

redis://localhost:6379/0

LOG_LEVEL

Structured logging verbosity (DEBUG, INFO, WARNING)

INFO


Repository Structure

workflow-intelligence-mcp/
├── src/
│   └── workflow_intelligence/
│       ├── server.py                   # FastMCP server entrypoint & lifecycle
│       ├── config.py                   # Pydantic Settings configuration
│       ├── dependencies.py             # Dependency injection container
│       │
│       ├── tools/                      # Thin MCP tool endpoints
│       │   ├── process_discovery.py    # process_* endpoints
│       │   ├── exception_resolver.py   # exception_* endpoints
│       │   └── decision_intelligence.py# decision_* endpoints
│       │
│       ├── resources/                  # MCP Resources (process maps, metrics)
│       ├── prompts/                    # MCP Prompt templates
│       │
│       ├── services/                   # Core business logic
│       │   ├── process_service.py      # PM4Py wrappers & mining logic
│       │   ├── exception_service.py    # Failure classification & resolution
│       │   ├── decision_service.py     # KPI root-cause & decision engine
│       │   ├── analytics_service.py    # DuckDB deterministic calculations
│       │   ├── evidence_service.py     # Provenance tracking & record matching
│       │   └── reporting_service.py    # Markdown briefs and visual reports
│       │
│       ├── adapters/                   # Integration boundaries
│       │   ├── process_mining/         # PM4Py adapter
│       │   ├── analytics/              # DuckDB engine adapter
│       │   ├── database/               # SQLAlchemy persistence adapter
│       │   └── workflow_engine/        # Temporal and n8n connectors
│       │
│       └── schemas/                    # Pydantic V2 IO contracts
│
├── tests/
│   ├── unit/                          # Service algorithms & validation tests
│   ├── integration/                   # Adapters & storage tests
│   ├── protocol/                      # MCP server tool invocation tests
│   └── fixtures/                      # Mock event logs & transaction data
│
├── sample-data/                       # Datasets for demonstrations & tests
├── demo/                              # Walkthrough scripts & client configs
├── .gitignore
├── pyproject.toml
├── README.md
├── AGENTS.md                          # Agent operating guide
└── LICENSE

Testing & Quality Assurance

The codebase enforces a 4-layer testing regime:

# Run complete test suite
pytest

# Run unit tests only
pytest tests/unit

# Run MCP protocol tests (verifies tool discovery & schema contracts)
pytest tests/protocol

# Run with test coverage
pytest --cov=workflow_intelligence --cov-report=term-missing

Roadmap

  • Initial design, protocol architecture, and AGENTS.md operational manual.

  • v0.1.0 (MVP): Core Pydantic schemas, PM4Py CSV log reconstruction, DuckDB analytics service, FastMCP STDIO server.

  • v0.5.0 (Engineering Maturity): PostgreSQL repository persistence, Temporal/n8n mock connectors, MCP Resources & Prompts, Docker Compose setup.

  • v1.0.0 (Production Ready): Complete CI/CD GitHub Actions, end-to-end procurement demo with synthetic ERP datasets, OpenTelemetry tracing.

  • v1.0.1 (Enterprise Hardening): Zero-hardcoding, dynamic SQL metric injection, universal dataset support (Amul dairy cold-chain benchmarks).


Contributing

Contributions are welcome! Please ensure that:

  1. All business logic is encapsulated within src/workflow_intelligence/services/, not inside tool handlers.

  2. Calculations and aggregations remain 100% deterministic.

  3. Every new tool is backed by unit and protocol tests.

  4. Read AGENTS.md for full architectural conventions.


License

This project is licensed under the Apache 2.0 License.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    Related MCP Connectors

    Related MCP Servers

    • F
      license
      Not graded
      quality
      C
      maintenance
      Enables users to investigate infrastructure incidents in plain English, correlate observability and deploy data with runbooks, and get evidence-backed root-cause proposals with approval-gated remediation.
      5
      -
    • A
      license
      B
      quality
      C
      maintenance
      Enables AI clients to analyze software test results and defect records, producing explainable GO, CONDITIONAL_GO, or NO_GO release-readiness recommendations with deterministic risk scoring, failed-test retrieval, defect hotspot ranking, and regression test planning.
      4
      MIT