{
  "id": "QZIcZmlRcDnmEwR2",
  "meta": {
    "templateCredsSetupCompleted": true
  },
  "name": "n8n Cursor AI Coding Workflow: Automatically Generate, Review & Optimize Code",
  "tags": [],
  "nodes": [
    {
      "id": "5c9bbdde-f7ce-40e4-b607-a3c0965ad4aa",
      "name": "Overview & Instructions",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        0,
        -656
      ],
      "parameters": {
        "width": 1180,
        "height": 1676,
        "content": "## \ud83d\udcbb n8n Cursor AI Coding Workflow\n### Automatically Generate, Review & Optimize Code\n\n---\n\n### \ud83d\udccb Description\nA smart, fully automated coding pipeline built inside n8n that leverages Cursor AI to write, refactor, review, and optimize code projects \u2014 triggered by a webhook, schedule, or manual prompt. Every output is versioned, stored, and delivered with a detailed review report.\n\n---\n\n### \ud83c\udfaf What's the Goal?\nEliminate the repetitive overhead of writing boilerplate code, performing code reviews, and refactoring legacy code manually. This workflow turns a plain-text task description into production-ready, reviewed, and optimized code \u2014 automatically and at scale \u2014 using Cursor AI's deep coding intelligence inside n8n.\n\n---\n\n### \ud83d\udca1 Why Does It Matter?\nSoftware teams lose hundreds of hours to boilerplate writing, manual code reviews, and inconsistent refactoring. AI-assisted coding with Cursor is powerful, but still requires manual triggering. By wiring Cursor into n8n, you get a repeatable, auditable, hands-free coding pipeline that integrates directly with your Git repos, Slack, and storage \u2014 making AI code generation a true part of your CI/CD culture, not just a one-off tool.\n\n---\n\n### \u2699\ufe0f How It Works\n1. Webhook or Schedule triggers the flow with a coding task description\n2. Task is classified (Generate / Review / Refactor / Optimize)\n3. Cursor AI API is called with the appropriate system prompt & task\n4. Raw code output is received and parsed\n5. A second Cursor pass performs automated code review & scoring\n6. If quality score passes threshold \u2192 code is committed to GitHub\n7. If score is below threshold \u2192 Cursor runs an optimization pass\n8. Final code + review report saved to Google Drive\n9. Summary logged to Google Sheets\n10. Slack notification sent with code snippet preview & Drive link\n\n---\n\n### \ud83d\udd27 Configuration Requirements\n- **Cursor AI API key** (via Cursor developer access or proxy endpoint)\n- **GitHub Personal Access Token** (for auto-commit & PR creation)\n- **Google Drive OAuth2** (for storing code files & reports)\n- **Google Sheets OAuth2** (for logging task history & quality scores)\n- **Slack Bot Token** (for team notifications)\n- **Optional: OpenAI API key** (for task classification fallback)\n\n---\n\n### \ud83d\ude80 Setup Guide\n1. Import this workflow into your n8n instance\n2. Connect all credentials: Cursor API, GitHub, Google Drive, Google Sheets, Slack\n3. Open the **Set Task Config** node and fill in:\n   - `repo_owner` and `repo_name` (your GitHub target repo)\n   - `target_branch` (e.g. `ai-generated` or `main`)\n   - `quality_threshold` (score 0\u2013100, recommended: 75)\n   - `storage_folder` (Google Drive folder name)\n   - `log_sheet_id` (Google Sheets document ID)\n4. Test with a **manual webhook POST** containing `{ \"task\": \"Write a Python FastAPI CRUD endpoint for users\" }`\n5. Review output in Drive and check Slack notification\n6. Activate the webhook for live use\n7. Optionally activate the daily schedule for batch processing queued tasks\n8. Monitor quality scores in Google Sheets and tune the threshold as needed\n\n"
      },
      "typeVersion": 1
    },
    {
      "id": "a3988c87-b6a7-4046-b1ba-3b2cd7aa0a47",
      "name": "1. Trigger",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        1240,
        -120
      ],
      "parameters": {
        "color": 3,
        "width": 432,
        "height": 760,
        "content": "## 1. Trigger & Task Input\nWebhook or schedule \u2192 receive coding task & prepare config"
      },
      "typeVersion": 1
    },
    {
      "id": "cae6733d-5fa7-401d-bd9f-91655c363c57",
      "name": "2. Classification Phase",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        1728,
        -128
      ],
      "parameters": {
        "color": 5,
        "width": 580,
        "height": 740,
        "content": "## 2. Task Classification\nAI classifies task type: Generate / Review / Refactor / Optimize"
      },
      "typeVersion": 1
    },
    {
      "id": "f116f1ab-cec6-400e-b9ef-bbf65ac28c67",
      "name": "3. Cursor Phase",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        2368,
        -112
      ],
      "parameters": {
        "color": 4,
        "width": 392,
        "height": 720,
        "content": "## 3. Cursor AI Code Generation\nCursor writes, reviews & optimizes code via API"
      },
      "typeVersion": 1
    },
    {
      "id": "aa0268aa-08d1-4c5d-8dea-4ce14ab35bf5",
      "name": "4. Quality Gate",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        2816,
        -80
      ],
      "parameters": {
        "color": 6,
        "width": 180,
        "height": 700,
        "content": "## 4. Quality Gate\nScore check \u2192 auto-optimize if below threshold"
      },
      "typeVersion": 1
    },
    {
      "id": "98cc9340-7e70-44b4-a712-e5c5fa96e5af",
      "name": "5. Output Phase",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        3026,
        -56
      ],
      "parameters": {
        "color": 3,
        "width": 892,
        "height": 696,
        "content": "## 5. Commit, Store, Log & Notify\nGitHub commit \u2192 Drive \u2192 Sheets \u2192 Slack"
      },
      "typeVersion": 1
    },
    {
      "id": "2578ef58-b055-495b-af01-2d8624a56e43",
      "name": "Webhook: Receive Coding Task",
      "type": "n8n-nodes-base.webhook",
      "position": [
        1296,
        288
      ],
      "parameters": {
        "path": "cursor-coding-task",
        "options": {},
        "httpMethod": "POST"
      },
      "typeVersion": 2
    },
    {
      "id": "faf52016-8210-4539-a54a-a6573e9d3bf5",
      "name": "Daily Batch (fallback)",
      "type": "n8n-nodes-base.scheduleTrigger",
      "position": [
        1296,
        480
      ],
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "hours",
              "hoursInterval": 24
            }
          ]
        }
      },
      "typeVersion": 1.3
    },
    {
      "id": "d3afb077-06a9-4533-b4c7-95d7d07a577a",
      "name": "Set Task Config",
      "type": "n8n-nodes-base.set",
      "position": [
        1520,
        384
      ],
      "parameters": {
        "values": {
          "string": [
            {
              "name": "repo_owner",
              "value": "your-github-username"
            },
            {
              "name": "repo_name",
              "value": "your-ai-code-repo"
            },
            {
              "name": "target_branch",
              "value": "ai-generated"
            },
            {
              "name": "language",
              "value": "python"
            },
            {
              "name": "quality_threshold",
              "value": "75"
            },
            {
              "name": "storage_folder",
              "value": "Cursor-AI-Code-Outputs"
            },
            {
              "name": "log_sheet_id",
              "value": "your-google-sheet-id-here"
            },
            {
              "name": "cursor_model",
              "value": "cursor-fast"
            }
          ]
        },
        "options": {}
      },
      "typeVersion": 2
    },
    {
      "id": "cbcc83b3-93a0-4f99-9045-c3761a2d1e37",
      "name": "Parse Classification",
      "type": "n8n-nodes-base.code",
      "position": [
        2192,
        384
      ],
      "parameters": {
        "jsCode": "const raw = $input.item.json.message.content.replace(/```json|```/g, '').trim();\nconst parsed = JSON.parse(raw);\nreturn {\n  task_type: parsed.task_type || 'GENERATE',\n  language: parsed.language || $('Set Task Config').item.json.language,\n  summary: parsed.summary || 'AI Coding Task',\n  original_task: $input.item.json.message.content\n};"
      },
      "typeVersion": 2
    },
    {
      "id": "1af8f58a-b550-45f7-a14a-f6d2997daf6f",
      "name": "Cursor AI: Generate Code",
      "type": "n8n-nodes-base.httpRequest",
      "position": [
        2416,
        384
      ],
      "parameters": {
        "url": "https://api.cursor.sh/v1/chat/completions",
        "options": {},
        "sendBody": true,
        "sendHeaders": true,
        "bodyParameters": {
          "parameters": [
            {
              "name": "model",
              "value": "={{ $('Set Task Config').item.json.cursor_model }}"
            },
            {
              "name": "messages",
              "value": "=[{\"role\": \"system\", \"content\": \"You are an expert \" + $json.language + \" developer. Write clean, production-ready, well-commented code. Include error handling, type hints, and docstrings where appropriate. Return ONLY the code block, no explanation.\"}, {\"role\": \"user\", \"content\": \"Task Type: \" + $json.task_type + \"\\n\\nTask: \" + $('Webhook: Receive Coding Task').item.json.body.task}]"
            },
            {
              "name": "max_tokens",
              "value": "2000"
            }
          ]
        },
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "Bearer {{ $credentials.cursorApiKey }}"
            },
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        }
      },
      "typeVersion": 4.2
    },
    {
      "id": "7b7a6bdc-e1e2-4834-93ad-32a6bf858116",
      "name": "Wait: Processing Delay",
      "type": "n8n-nodes-base.wait",
      "position": [
        1968,
        384
      ],
      "parameters": {},
      "typeVersion": 1.1
    },
    {
      "id": "ba248e93-dfb2-41cf-be6b-5344e9e3cdf1",
      "name": "Cursor AI: Code Review",
      "type": "n8n-nodes-base.httpRequest",
      "position": [
        2640,
        384
      ],
      "parameters": {
        "url": "https://api.cursor.sh/v1/chat/completions",
        "options": {},
        "sendBody": true,
        "sendHeaders": true,
        "bodyParameters": {
          "parameters": [
            {
              "name": "model",
              "value": "={{ $('Set Task Config').item.json.cursor_model }}"
            },
            {
              "name": "messages",
              "value": "=[{\"role\": \"system\", \"content\": \"You are a senior code reviewer. Review the code for: correctness, security, performance, readability, and best practices. Return ONLY valid JSON: {\\\"score\\\": 85, \\\"issues\\\": [\\\"issue1\\\", \\\"issue2\\\"], \\\"suggestions\\\": [\\\"suggestion1\\\"], \\\"summary\\\": \\\"brief review summary\\\"}\"}, {\"role\": \"user\", \"content\": \"Review this code:\\n\\n\" + $('Cursor AI: Generate Code').item.json.choices[0].message.content}]"
            },
            {
              "name": "max_tokens",
              "value": "1000"
            }
          ]
        },
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "Bearer {{ $credentials.cursorApiKey }}"
            },
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        }
      },
      "typeVersion": 4.2
    },
    {
      "id": "1f68cf17-87ca-467a-94c5-f3f979985652",
      "name": "Quality Score OK?",
      "type": "n8n-nodes-base.if",
      "position": [
        2864,
        384
      ],
      "parameters": {
        "conditions": {
          "number": [
            {
              "value1": "={{ JSON.parse($json.choices[0].message.content.replace(/```json|```/g,'')).score }}",
              "value2": "={{ $('Set Task Config').item.json.quality_threshold }}",
              "operation": "largerEqual"
            }
          ]
        }
      },
      "typeVersion": 1
    },
    {
      "id": "b07466db-4658-4024-bc88-75344a9856e6",
      "name": "Cursor AI: Optimize Code",
      "type": "n8n-nodes-base.httpRequest",
      "position": [
        3088,
        480
      ],
      "parameters": {
        "url": "https://api.cursor.sh/v1/chat/completions",
        "options": {},
        "sendBody": true,
        "sendHeaders": true,
        "bodyParameters": {
          "parameters": [
            {
              "name": "model",
              "value": "={{ $('Set Task Config').item.json.cursor_model }}"
            },
            {
              "name": "messages",
              "value": "=[{\"role\": \"system\", \"content\": \"You are an expert code optimizer. Fix all issues from the review and return ONLY the improved, production-ready code block.\"}, {\"role\": \"user\", \"content\": \"Original code:\\n\\n\" + $('Cursor AI: Generate Code').item.json.choices[0].message.content + \"\\n\\nReview issues to fix:\\n\" + $('Cursor AI: Code Review').item.json.choices[0].message.content}]"
            },
            {
              "name": "max_tokens",
              "value": "2000"
            }
          ]
        },
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "Bearer {{ $credentials.cursorApiKey }}"
            },
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        }
      },
      "typeVersion": 4.2
    },
    {
      "id": "0856723d-aff6-44af-ba12-6d797c5c5c14",
      "name": "GitHub: Commit Code",
      "type": "n8n-nodes-base.httpRequest",
      "position": [
        3088,
        288
      ],
      "parameters": {
        "url": "=https://api.github.com/repos/{{ $('Set Task Config').item.json.repo_owner }}/{{ $('Set Task Config').item.json.repo_name }}/contents/ai-code/{{ $now.toFormat('yyyyMMdd-HHmmss') }}.{{ $('Parse Classification').item.json.language === 'python' ? 'py' : $('Parse Classification').item.json.language === 'javascript' ? 'js' : $('Parse Classification').item.json.language }}",
        "options": {},
        "jsonBody": "={\n  \"message\": \"chore: AI-generated code via Cursor \u2014 \" + $('Parse Classification').item.json.summary,\n  \"content\": Buffer.from($('Cursor AI: Generate Code').item.json.choices[0].message.content).toString('base64'),\n  \"branch\": \"{{ $('Set Task Config').item.json.target_branch }}\"\n}",
        "sendBody": true,
        "sendHeaders": true,
        "specifyBody": "json",
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "Bearer {{ $credentials.githubToken }}"
            },
            {
              "name": "Accept",
              "value": "application/vnd.github+json"
            }
          ]
        }
      },
      "typeVersion": 4.2
    },
    {
      "id": "740d1cb8-066b-4597-a8a4-22e72d355d9c",
      "name": "Google Drive: Save Report",
      "type": "n8n-nodes-base.googleDrive",
      "position": [
        3312,
        288
      ],
      "parameters": {
        "name": "=cursor-code-{{ $now.toFormat('yyyyMMdd-HHmmss') }}.md",
        "options": {},
        "folderId": {
          "mode": "string",
          "value": "={{ $('Set Task Config').item.json.storage_folder }}"
        }
      },
      "credentials": {
        "googleDriveOAuth2Api": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 3
    },
    {
      "id": "d0393c2b-2e3c-426f-913e-d13a5638fe43",
      "name": "Google Sheets: Log Result",
      "type": "n8n-nodes-base.googleSheets",
      "position": [
        3536,
        288
      ],
      "parameters": {
        "columns": {
          "value": {
            "Task": "={{ $('Webhook: Receive Coding Task').item.json.body.task }}",
            "Status": "SUCCESS",
            "Language": "={{ $('Parse Classification').item.json.language }}",
            "Task Type": "={{ $('Parse Classification').item.json.task_type }}",
            "Timestamp": "={{ $now.toISO() }}",
            "Drive File ID": "={{ $json.id }}",
            "Quality Score": "={{ JSON.parse($('Cursor AI: Code Review').item.json.choices[0].message.content.replace(/```json|```/g,'')).score }}",
            "Review Summary": "={{ JSON.parse($('Cursor AI: Code Review').item.json.choices[0].message.content.replace(/```json|```/g,'')).summary }}",
            "GitHub Commit URL": "={{ $('GitHub: Commit Code').item.json.content.html_url }}"
          },
          "mappingMode": "defineBelow"
        },
        "options": {},
        "operation": "append",
        "sheetName": {
          "mode": "string",
          "value": "Code Log"
        },
        "documentId": {
          "mode": "string",
          "value": "={{ $('Set Task Config').item.json.log_sheet_id }}"
        }
      },
      "credentials": {
        "googleSheetsOAuth2Api": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 4.4
    },
    {
      "id": "17de541a-94bd-4374-9b03-d7a4c8874872",
      "name": "Notify Slack: Success",
      "type": "n8n-nodes-base.slack",
      "position": [
        3760,
        288
      ],
      "parameters": {
        "text": "={{ '\u2705 Cursor AI Code Generated & Committed!\\n\\n*Task:* ' + $(\\'Webhook: Receive Coding Task\\').item.json.body.task + '\\n*Type:* ' + $(\\'Parse Classification\\').item.json.task_type + '  |  *Language:* ' + $(\\'Parse Classification\\').item.json.language + '\\n*Quality Score:* ' + JSON.parse($(\\'Cursor AI: Code Review\\').item.json.choices[0].message.content.replace(/```json|```/g,\\'\\'.trim()).score + '/100' + '\\n*GitHub:* ' + $(\\'GitHub: Commit Code\\').item.json.content.html_url + '\\n*Drive Report:* Saved \u2705' }}",
        "channel": "ai-code-review",
        "attachments": [],
        "otherOptions": {}
      },
      "credentials": {
        "slackApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1
    },
    {
      "id": "023f07b7-79c7-47b6-baf6-aa8a845f2a4c",
      "name": "Notify Slack: Optimized",
      "type": "n8n-nodes-base.slack",
      "position": [
        3312,
        480
      ],
      "parameters": {
        "text": "={{ '\u26a0\ufe0f Cursor AI Code Quality Below Threshold \u2014 Optimization Applied\\n\\n*Task:* ' + $(\\'Webhook: Receive Coding Task\\').item.json.body.task + '\\n*Original Score:* ' + JSON.parse($(\\'Cursor AI: Code Review\\').item.json.choices[0].message.content.replace(/```json|```/g,\\'\\').trim()).score + '/100 (threshold: ' + $(\\'Set Task Config\\').item.json.quality_threshold + ')\\n*Action:* Auto-optimized by Cursor AI \u2728\\n*Review Issues fixed and new code committed.*' }}",
        "channel": "ai-code-review",
        "attachments": [],
        "otherOptions": {}
      },
      "credentials": {
        "slackApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1
    },
    {
      "id": "bc1706f2-acd7-4a82-8e1a-dd79340b24ce",
      "name": "Create a conversation",
      "type": "@n8n/n8n-nodes-langchain.openAi",
      "position": [
        1744,
        384
      ],
      "parameters": {
        "options": {},
        "messages": {
          "values": [
            {}
          ]
        },
        "resource": "conversation"
      },
      "credentials": {
        "openAiApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 2.1
    }
  ],
  "active": false,
  "settings": {
    "executionOrder": "v1"
  },
  "versionId": "9e8a4d47-7350-4e0c-86d5-adf797ce77e0",
  "connections": {
    "Set Task Config": {
      "main": [
        [
          {
            "node": "Create a conversation",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Quality Score OK?": {
      "main": [
        [
          {
            "node": "GitHub: Commit Code",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Cursor AI: Optimize Code",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "GitHub: Commit Code": {
      "main": [
        [
          {
            "node": "Google Drive: Save Report",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Parse Classification": {
      "main": [
        [
          {
            "node": "Cursor AI: Generate Code",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create a conversation": {
      "main": [
        [
          {
            "node": "Wait: Processing Delay",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Cursor AI: Code Review": {
      "main": [
        [
          {
            "node": "Quality Score OK?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Daily Batch (fallback)": {
      "main": [
        [
          {
            "node": "Set Task Config",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Wait: Processing Delay": {
      "main": [
        [
          {
            "node": "Parse Classification",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Cursor AI: Generate Code": {
      "main": [
        [
          {
            "node": "Cursor AI: Code Review",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Cursor AI: Optimize Code": {
      "main": [
        [
          {
            "node": "Notify Slack: Optimized",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Google Drive: Save Report": {
      "main": [
        [
          {
            "node": "Google Sheets: Log Result",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Google Sheets: Log Result": {
      "main": [
        [
          {
            "node": "Notify Slack: Success",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Webhook: Receive Coding Task": {
      "main": [
        [
          {
            "node": "Set Task Config",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  }
}