Skip to content

feat: Add n8n workflow automation integration#19

Merged
MervinPraison merged 2 commits intomainfrom
claude/issue-1396-20260416
Apr 16, 2026
Merged

feat: Add n8n workflow automation integration#19
MervinPraison merged 2 commits intomainfrom
claude/issue-1396-20260416

Conversation

@praisonai-triage-agent
Copy link
Copy Markdown
Contributor

Fixes MervinPraison/PraisonAI#1396

Overview

This PR implements bidirectional integration between PraisonAI agents and n8n workflow automation platform, providing access to 400+ integrations (Slack, Gmail, Notion, databases, APIs, etc.).

Key Features

  • N8nWorkflowTool: Execute n8n workflows from PraisonAI agents
  • Function decorators: @tool decorated functions for easy agent integration
  • Error handling: Comprehensive error handling with informative messages
  • Lazy loading: httpx dependency only loaded when n8n tools are used
  • Environment configuration: Support for N8N_URL and N8N_API_KEY env vars
  • Comprehensive tests: Unit tests with mocking and integration test support

Files Added

  • Core Implementation:

    • praisonai_tools/n8n/init.py - Package exports
    • praisonai_tools/n8n/n8n_workflow.py - Main tool implementation
  • Configuration:

    • pyproject.toml - Added n8n optional dependency (httpx>=0.27.0)
    • praisonai_tools/tools/init.py - Added n8n tools to registry
  • Tests & Examples:

    • tests/test_n8n_integration.py - Comprehensive unit tests
    • examples/n8n_integration_example.py - Usage examples
    • docs/n8n_integration.md - Complete documentation

Generated with Claude Code

…aisonAI#1396)

- Add N8nWorkflowTool class for executing n8n workflows
- Add n8n_workflow and n8n_list_workflows decorator functions
- Provides access to 400+ integrations (Slack, Gmail, Notion, databases, APIs)
- Includes comprehensive unit tests with mocking
- Add example usage and documentation
- Optional httpx dependency with lazy loading
- Bidirectional PraisonAI ↔ n8n integration support
@greptile-apps
Copy link
Copy Markdown

greptile-apps bot commented Apr 16, 2026

Greptile Summary

This PR adds a bidirectional n8n workflow automation integration, introducing N8nWorkflowTool, two @tool-decorated helper functions (n8n_workflow and n8n_list_workflows), lazy httpx loading, and proper package wiring — along with tests, examples, and documentation.

The two previously flagged blockers (missing n8n_list_workflows export in praisonai_tools/n8n/__init__.py and the wrong module path in the lazy-loader) are both fully resolved in this revision.

Key changes:

  • praisonai_tools/n8n/n8n_workflow.py — core tool class and decorated functions with synchronous HTTP via httpx, polling for execution completion, and environment-variable-based configuration
  • praisonai_tools/n8n/__init__.py — now correctly exports all three public symbols
  • praisonai_tools/tools/__init__.py — lazy-loader updated to use absolute import path for n8n tools, with a correct praisonai_tools.* prefix check
  • pyproject.tomln8n optional dependency group targeting httpx>=0.27.0
  • One P1 logic bug remains: the execution poller does not exit on \"crashed\" status (an n8n terminal state), causing the caller to wait the full configured timeout before getting an error response
  • Two minor P2 style issues: hardcoded 30 s timeout in list_workflows() vs configurable self.timeout in run(), and local variable tool shadowing the tool decorator import

Confidence Score: 4/5

Safe to merge after the one-line "crashed" status fix; all previously flagged blockers are resolved.

Both prior blocking issues (missing export and wrong module path in lazy-loader) are fully fixed. The remaining P1 is a single-line addition to the terminal-status set in _wait_for_execution; it degrades reliability (unnecessary full-timeout wait on crashed workflows) but does not corrupt data or break the happy path. The two P2 style issues are non-blocking. Overall the integration is well-structured with good test coverage.

praisonai_tools/n8n/n8n_workflow.py — specifically the _wait_for_execution status check on line 136 and the hardcoded timeout in list_workflows on line 160.

Important Files Changed

Filename Overview
praisonai_tools/n8n/n8n_workflow.py Core implementation with N8nWorkflowTool class and two @tool-decorated functions; has a P1 bug where "crashed" execution status is not handled in the polling loop, plus two minor style issues.
praisonai_tools/n8n/init.py Package exports n8n_workflow, n8n_list_workflows, and N8nWorkflowTool — all three now correctly imported from n8n_workflow.py (previous missing-export issue is fixed).
praisonai_tools/tools/init.py Lazy-loading registry updated with absolute module path for n8n tools; the getattr handler correctly detects praisonai_tools.* prefix and uses import_module with the absolute path, fixing the previous ModuleNotFoundError issue.
pyproject.toml Adds n8n optional dependency group requiring httpx>=0.27.0; straightforward and correct.
tests/test_n8n_integration.py Comprehensive unit tests covering init, env vars, error handling, HTTP errors, timeouts, and workflow listing via mocked httpx; good coverage for the happy paths and error paths.

Sequence Diagram

sequenceDiagram
    participant Agent as PraisonAI Agent
    participant TF as n8n_workflow()
    participant Tool as N8nWorkflowTool
    participant N8N as n8n REST API

    Agent->>TF: n8n_workflow(workflow_id, input_data)
    TF->>Tool: N8nWorkflowTool(url, api_key, timeout)
    TF->>Tool: tool.run(workflow_id, input_data)
    Tool->>N8N: POST /api/v1/workflows/{id}/execute
    N8N-->>Tool: {executionId, status: running}
    alt wait_for_completion=True
        loop Poll every 2s up to timeout
            Tool->>N8N: GET /api/v1/executions/{executionId}
            N8N-->>Tool: {status: running|success|error|canceled}
            Note over Tool,N8N: crashed not handled — keeps polling
        end
    end
    Tool-->>TF: execution result dict
    TF-->>Agent: result / error dict

    Agent->>TF: n8n_list_workflows()
    TF->>Tool: N8nWorkflowTool(url, api_key)
    TF->>Tool: tool.list_workflows()
    Tool->>N8N: GET /api/v1/workflows
    N8N-->>Tool: {data: [...workflows]}
    Tool-->>TF: workflows dict
    TF-->>Agent: workflows / error dict
Loading

Reviews (2): Last reviewed commit: "fix: resolve critical n8n integration is..." | Re-trigger Greptile

Comment thread praisonai_tools/n8n/__init__.py Outdated
Comment thread praisonai_tools/tools/__init__.py Outdated
@MervinPraison
Copy link
Copy Markdown
Owner

Additional Findings: n8n Management & Node Creation

After deeper analysis, here are additional integration capabilities:


n8n Workflow SDK (@n8n/workflow-sdk)

n8n provides a TypeScript SDK for programmatic workflow creation:

import { WorkflowBuilder, manual, httpRequest } from '@n8n/workflow-sdk';

const workflow = new WorkflowBuilder()
  .withName('My Workflow')
  .addTrigger(manual())
  .then(httpRequest({ url: 'https://api.example.com/data' }))
  .build();

Key Features:

  • Fluent builder API
  • Full type safety
  • Control flow: ifElse(), switchCase(), splitInBatches()
  • AI/LangChain node integration

n8n Custom Node CLI (@n8n/node-cli)

Create custom n8n nodes programmatically:

npm create @n8n/node@latest
# Interactive scaffolding for custom nodes

Templates:

  • declarative/custom — JSON-based configuration
  • programmatic/example — Full TypeScript control

Full n8n Management API

Endpoint Purpose
POST /api/v1/workflows Create workflow
PUT /api/v1/workflows/{id} Update workflow
DELETE /api/v1/workflows/{id} Delete workflow
POST /api/v1/workflows/{id}/activate Activate
POST /api/v1/workflows/{id}/deactivate Deactivate
GET /api/v1/executions List executions
POST /api/v1/executions/{id}/retry Retry execution
POST /api/v1/executions/{id}/stop Stop execution
GET /api/v1/credentials List credentials
POST /api/v1/credentials Create credential

Proposed: n8n Management Tools for PraisonAI

from praisonaiagents.tools import tool

@tool
def n8n_create_workflow(name: str, nodes: list, connections: dict) -> dict:
    """Create a new n8n workflow."""
    ...

@tool
def n8n_list_workflows(active: bool = None) -> list:
    """List all n8n workflows."""
    ...

@tool
def n8n_activate_workflow(workflow_id: str) -> dict:
    """Activate an n8n workflow."""
    ...

@tool
def n8n_get_executions(workflow_id: str = None, status: str = None) -> list:
    """Get workflow execution history."""
    ...

This enables agents to fully manage n8n — create, update, activate, and monitor workflows programmatically.


Related Issue

See #1397 for the unique Visual Workflow Editor feature — converting PraisonAI YAML to n8n JSON for visual preview/editing.

not in praisonaiagents, but in praisonai-tools @claude validate

@github-actions
Copy link
Copy Markdown
Contributor

github-actions bot commented Apr 16, 2026

Claude finished @MervinPraison's task —— View job


n8n Integration Validation Complete ✅

I've successfully validated and fixed all critical issues identified in the n8n integration PR.

Todo List:

  • Read repository structure and understand tool patterns
  • Examine n8n integration files and identify issues
  • Fix P0: Missing n8n_list_workflows export in __init__.py
  • Fix P0: Incorrect module path in tools registry
  • Fix P1: Timeout handling in _wait_for_execution
  • Fix P1: Test mocking for lazy imports
  • Validate fixes by testing imports
  • Commit and push fixes to PR branch

Issues Fixed:

P0 Critical Issues:

  1. Missing Export: Added n8n_list_workflows to praisonai_tools/n8n/__init__.py exports
  2. Module Path: Fixed tools registry to use absolute path "praisonai_tools.n8n.n8n_workflow" and updated __getattr__ to handle absolute imports

P1 Issues:
3. Timeout Logic: Fixed _wait_for_execution to respect user's timeout parameter instead of hardcoded 60s
4. Test Mocking: Updated test fixture to mock httpx in sys.modules to properly intercept lazy imports

Summary:

The n8n integration is now ready for merge. All blocking issues have been resolved:

  • Import errors are fixed
  • Module registry works correctly
  • Timeout behavior follows user configuration
  • Test mocking properly handles lazy imports

The integration provides access to 400+ n8n integrations through two @tool-decorated functions that follow the established praisonai-tools patterns.

Fixes committed: 88624d6

--- | Branch: claude/issue-1396-20260416

- Export n8n_list_workflows from __init__.py (fixes ImportError)
- Fix module path in tools registry to use absolute imports
- Update __getattr__ to handle absolute module paths
- Fix timeout parameter not being used in _wait_for_execution
- Update test mocking to work with lazy imports

Addresses P0 and P1 issues identified in code review.

Co-authored-by: Mervin Praison <MervinPraison@users.noreply.github.com>
execution = response.json()
status = execution.get("status")

if status in ["success", "error", "canceled"]:
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 "crashed" status causes full-timeout wait

The polling loop only exits early for "success", "error", and "canceled". n8n's REST API also returns "crashed" for workflows that fail with an unhandled exception. When a workflow crashes, the poller will keep polling until max_wait seconds are exhausted (default 60 s) before returning a timeout error — instead of exiting immediately.

Suggested change
if status in ["success", "error", "canceled"]:
if status in ["success", "error", "canceled", "crashed"]:

@MervinPraison MervinPraison merged commit 442a0d7 into main Apr 16, 2026
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Integration: n8n Workflow Automation — Bidirectional Integration

1 participant