jpskill.com
🛠️ 開発・MCP コミュニティ

n8n-workflow-sdk

n8nのワークフローをTypeScriptでプログラム的に構築できるSDKで、コードからワークフローを作成したり、自動化パイプラインを構築したり、JSONとTypeScriptを変換したり、n8nのワークフロー作成をアプリケーションに統合したりする際に活用するSkill。

📜 元の英語説明(参考)

Build n8n workflows programmatically with the official TypeScript SDK. Use when a user asks to create n8n workflows from code, generate workflow JSON, build automation pipelines programmatically, convert between n8n JSON and TypeScript, or integrate n8n workflow creation into applications.

🇯🇵 日本人クリエイター向け解説

一言でいうと

n8nのワークフローをTypeScriptでプログラム的に構築できるSDKで、コードからワークフローを作成したり、自動化パイプラインを構築したり、JSONとTypeScriptを変換したり、n8nのワークフロー作成をアプリケーションに統合したりする際に活用するSkill。

※ jpskill.com 編集部が日本のビジネス現場向けに補足した解説です。Skill本体の挙動とは独立した参考情報です。

⚡ おすすめ: コマンド1行でインストール(60秒)

下記のコマンドをコピーしてターミナル(Mac/Linux)または PowerShell(Windows)に貼り付けてください。 ダウンロード → 解凍 → 配置まで全自動。

🍎 Mac / 🐧 Linux
mkdir -p ~/.claude/skills && cd ~/.claude/skills && curl -L -o n8n-workflow-sdk.zip https://jpskill.com/download/15152.zip && unzip -o n8n-workflow-sdk.zip && rm n8n-workflow-sdk.zip
🪟 Windows (PowerShell)
$d = "$env:USERPROFILE\.claude\skills"; ni -Force -ItemType Directory $d | Out-Null; iwr https://jpskill.com/download/15152.zip -OutFile "$d\n8n-workflow-sdk.zip"; Expand-Archive "$d\n8n-workflow-sdk.zip" -DestinationPath $d -Force; ri "$d\n8n-workflow-sdk.zip"

完了後、Claude Code を再起動 → 普通に「動画プロンプト作って」のように話しかけるだけで自動発動します。

💾 手動でダウンロードしたい(コマンドが難しい人向け)
  1. 1. 下の青いボタンを押して n8n-workflow-sdk.zip をダウンロード
  2. 2. ZIPファイルをダブルクリックで解凍 → n8n-workflow-sdk フォルダができる
  3. 3. そのフォルダを C:\Users\あなたの名前\.claude\skills\(Win)または ~/.claude/skills/(Mac)へ移動
  4. 4. Claude Code を再起動

⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。

🎯 このSkillでできること

下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。

📦 インストール方法 (3ステップ)

  1. 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
  2. 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
  3. 3. 展開してできたフォルダを、ホームフォルダの .claude/skills/ に置く
    • · macOS / Linux: ~/.claude/skills/
    • · Windows: %USERPROFILE%\.claude\skills\

Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。

詳しい使い方ガイドを見る →
最終更新
2026-05-18
取得日時
2026-05-18
同梱ファイル
1

📖 Skill本文(日本語訳)

※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。

n8n Workflow SDK

概要

@n8n/workflow-sdk は、プログラムでワークフローを作成、検証、変換するための、n8n (v0.2.0、2026年2月リリース) の公式 TypeScript SDK です。UI でノードをドラッグする代わりに、ワークフローをコードとして定義します。これにより、型安全、バージョン管理、および構成可能になります。AI/LangChain ノードを含むすべての n8n ノードタイプをサポートします。JSON と TypeScript 間の双方向変換が含まれています。

手順

ステップ 1: インストールと基本的なワークフローの作成

npm install @n8n/workflow-sdk
// workflows/data-sync.ts — プログラムによるワークフローの作成
import { WorkflowBuilder, manual, httpRequest, code } from '@n8n/workflow-sdk'

// 簡単なデータ同期ワークフローを構築します
const workflow = new WorkflowBuilder()
  .withName('Daily Data Sync')
  .addTrigger(manual())
  .then(httpRequest({
    url: 'https://api.example.com/users',
    method: 'GET',
    headers: {
      Authorization: '={{ $env.API_KEY }}',      // 環境変数のための n8n 式
    },
  }))
  .then(code({
    language: 'typescript',
    code: `
      // API レスポンスを内部形式に変換します
      return items.map(item => ({
        json: {
          id: item.json.id,
          email: item.json.email,
          name: \`\${item.json.firstName} \${item.json.lastName}\`,
          active: item.json.status === 'active',
          syncedAt: new Date().toISOString(),
        }
      }))
    `,
  }))
  .build()

// workflow は、インポート可能な有効な n8n JSON オブジェクトになりました
console.log(JSON.stringify(workflow, null, 2))

ステップ 2: 制御フロー — 分岐とマージ

// workflows/lead-routing.ts — 分岐のある条件付きワークフロー
import {
  WorkflowBuilder, webhook, ifElse, merge,
  httpRequest, node, sticky,
} from '@n8n/workflow-sdk'

const workflow = new WorkflowBuilder()
  .withName('Lead Routing')

  // 受信 webhook でトリガー
  .addTrigger(webhook({
    path: 'new-lead',
    method: 'POST',
    responseMode: 'onReceived',
  }))

  // リードスコアに基づいて分岐
  .then(ifElse({
    conditions: {
      combinator: 'and',
      conditions: [
        { leftValue: '={{ $json.score }}', operator: 'gte', rightValue: 80 },
      ],
    },
  }))

  // True ブランチ — 高価値リード → Salesforce + Slack 通知
  .onTrue(
    httpRequest({
      url: 'https://mycompany.salesforce.com/api/leads',
      method: 'POST',
      body: '={{ JSON.stringify($json) }}',
    })
  )

  // False ブランチ — 低スコアリード → 育成キャンペーンに追加
  .onFalse(
    httpRequest({
      url: 'https://api.mailchimp.com/3.0/lists/abc123/members',
      method: 'POST',
      body: '={{ JSON.stringify({ email_address: $json.email, status: "subscribed" }) }}',
    })
  )

  // ドキュメントを追加
  .addSticky(sticky({
    content: '## Lead Routing\n高スコアリード (≥80) は Salesforce に送られます。\nそれ以外は育成キャンペーンに参加します。',
    width: 300,
    height: 150,
  }))

  .build()

ステップ 3: AI/LangChain ワークフロー

// workflows/ai-support-agent.ts — ツールとメモリを備えた AI エージェント
import {
  WorkflowBuilder, webhook,
  languageModel, memory, tool, outputParser,
  node,
} from '@n8n/workflow-sdk'

const workflow = new WorkflowBuilder()
  .withName('AI Support Agent')

  .addTrigger(webhook({ path: 'support', method: 'POST' }))

  // LangChain コンポーネントを備えた AI Agent ノード
  .then(node('n8n-nodes-langchain.agent', {
    text: '={{ $json.message }}',
    systemMessage: `あなたは SaaS 製品の役に立つカスタマーサポートエージェントです。
      利用可能なツールを使用して、アカウント情報と
      ナレッジベースの記事を検索します。簡潔で役に立つようにしてください。`,
  }))

  // LLM をアタッチ
  .withSub(languageModel('openAi', {
    model: 'gpt-4o',
    temperature: 0.3,
  }))

  // 会話メモリをアタッチ
  .withSub(memory('windowBuffer', {
    sessionKey: '={{ $json.userId }}',
    windowSize: 20,      // 最後の 20 件のメッセージを記憶
  }))

  // エージェントが使用できるツールをアタッチ
  .withSub(tool('httpRequest', {
    name: 'lookup_account',
    description: 'メールまたは ID で顧客アカウントを検索',
    url: 'https://api.myapp.com/accounts/{{ $fromAi("query") }}',
    method: 'GET',
  }))
  .withSub(tool('httpRequest', {
    name: 'search_knowledge_base',
    description: 'ヘルプ記事のナレッジベースを検索',
    url: 'https://api.myapp.com/kb/search?q={{ $fromAi("query") }}',
    method: 'GET',
  }))

  // 構造化された出力を解析
  .then(outputParser('structured', {
    schema: {
      answer: { type: 'string', description: '顧客への回答' },
      category: { type: 'string', description: '問題のカテゴリ: 請求、技術、一般' },
      escalate: { type: 'boolean', description: '人間のエージェントにエスカレートするかどうか' },
    },
  }))

  .build()

ステップ 4: 分割とマージによるバッチ処理


// workflows/bulk-enrichment.ts — レコードをバッチで処理
import {
  WorkflowBuilder, schedule, httpRequest,
  splitInBatches, merge, code, node,
} from '@n8n/workflow-sdk'

const workflow = new WorkflowBuilder()
  .withName('Contact Enrichment Pipeline')

  // 毎晩午前 2 時に実行
  .addTrigger(schedule({ rule: { interval: [{ field: 'hours', triggerAtHour: 2 }] } }))

  // エンリッチメントが必要な連絡先を取得
  .then(httpRequest({
    url: 'https://api.myapp.com/contacts?needs_enrichment=true&limit=500',
    method: 'GET',
  }))

  // API レート制限を尊重するために 50 のバッチで処理
  .then(splitInBatches({ batchSize: 50 }))

  // Clearbit 経由で各連絡先をエンリッチ
  .then(httpRequest({
    url: 'https://person.clearbit.com/v2/people/find',
    method: 'GET',
    queryParameters: { email: '={{ $json.email }}' },
    headers: { Authorization: '={{ $env.CLEARBIT_KEY }}' },
    options: { batching: { batch: { batchSize: 10, batchInterval: 1000 } } },
  }))

  // 変換して保存
  .then(code({
    language: 'typescript',
    code: `
      return items.map(item => ({
        json: {
          contactId: item.json.contactId,
          company: item.json.company?

(原文はここで切り詰められています)
📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開

n8n Workflow SDK

Overview

@n8n/workflow-sdk is the official TypeScript SDK from n8n (v0.2.0, released February 2026) for programmatically creating, validating, and converting workflows. Instead of dragging nodes in the UI, define workflows as code — type-safe, version-controlled, and composable. Supports all n8n node types including AI/LangChain nodes. Includes bidirectional conversion between JSON and TypeScript.

Instructions

Step 1: Install and Create a Basic Workflow

npm install @n8n/workflow-sdk
// workflows/data-sync.ts — Programmatic workflow creation
import { WorkflowBuilder, manual, httpRequest, code } from '@n8n/workflow-sdk'

// Build a simple data sync workflow
const workflow = new WorkflowBuilder()
  .withName('Daily Data Sync')
  .addTrigger(manual())
  .then(httpRequest({
    url: 'https://api.example.com/users',
    method: 'GET',
    headers: {
      Authorization: '={{ $env.API_KEY }}',      // n8n expression for env variable
    },
  }))
  .then(code({
    language: 'typescript',
    code: `
      // Transform API response to internal format
      return items.map(item => ({
        json: {
          id: item.json.id,
          email: item.json.email,
          name: \`\${item.json.firstName} \${item.json.lastName}\`,
          active: item.json.status === 'active',
          syncedAt: new Date().toISOString(),
        }
      }))
    `,
  }))
  .build()

// workflow is now a valid n8n JSON object ready to import
console.log(JSON.stringify(workflow, null, 2))

Step 2: Control Flow — Branching and Merging

// workflows/lead-routing.ts — Conditional workflow with branches
import {
  WorkflowBuilder, webhook, ifElse, merge,
  httpRequest, node, sticky,
} from '@n8n/workflow-sdk'

const workflow = new WorkflowBuilder()
  .withName('Lead Routing')

  // Trigger on incoming webhook
  .addTrigger(webhook({
    path: 'new-lead',
    method: 'POST',
    responseMode: 'onReceived',
  }))

  // Branch based on lead score
  .then(ifElse({
    conditions: {
      combinator: 'and',
      conditions: [
        { leftValue: '={{ $json.score }}', operator: 'gte', rightValue: 80 },
      ],
    },
  }))

  // True branch — high-value lead → Salesforce + Slack notification
  .onTrue(
    httpRequest({
      url: 'https://mycompany.salesforce.com/api/leads',
      method: 'POST',
      body: '={{ JSON.stringify($json) }}',
    })
  )

  // False branch — low-score lead → add to nurture campaign
  .onFalse(
    httpRequest({
      url: 'https://api.mailchimp.com/3.0/lists/abc123/members',
      method: 'POST',
      body: '={{ JSON.stringify({ email_address: $json.email, status: "subscribed" }) }}',
    })
  )

  // Add documentation
  .addSticky(sticky({
    content: '## Lead Routing\nHigh-score leads (≥80) go to Salesforce.\nOthers enter nurture campaign.',
    width: 300,
    height: 150,
  }))

  .build()

Step 3: AI/LangChain Workflows

// workflows/ai-support-agent.ts — AI agent with tools and memory
import {
  WorkflowBuilder, webhook,
  languageModel, memory, tool, outputParser,
  node,
} from '@n8n/workflow-sdk'

const workflow = new WorkflowBuilder()
  .withName('AI Support Agent')

  .addTrigger(webhook({ path: 'support', method: 'POST' }))

  // AI Agent node with LangChain components
  .then(node('n8n-nodes-langchain.agent', {
    text: '={{ $json.message }}',
    systemMessage: `You are a helpful customer support agent for a SaaS product.
      Use the available tools to look up account information and
      knowledge base articles. Be concise and helpful.`,
  }))

  // Attach LLM
  .withSub(languageModel('openAi', {
    model: 'gpt-4o',
    temperature: 0.3,
  }))

  // Attach conversation memory
  .withSub(memory('windowBuffer', {
    sessionKey: '={{ $json.userId }}',
    windowSize: 20,      // remember last 20 messages
  }))

  // Attach tools the agent can use
  .withSub(tool('httpRequest', {
    name: 'lookup_account',
    description: 'Look up customer account by email or ID',
    url: 'https://api.myapp.com/accounts/{{ $fromAi("query") }}',
    method: 'GET',
  }))
  .withSub(tool('httpRequest', {
    name: 'search_knowledge_base',
    description: 'Search the knowledge base for help articles',
    url: 'https://api.myapp.com/kb/search?q={{ $fromAi("query") }}',
    method: 'GET',
  }))

  // Parse structured output
  .then(outputParser('structured', {
    schema: {
      answer: { type: 'string', description: 'The response to the customer' },
      category: { type: 'string', description: 'Issue category: billing, technical, general' },
      escalate: { type: 'boolean', description: 'Whether to escalate to human agent' },
    },
  }))

  .build()

Step 4: Batch Processing with Split and Merge

// workflows/bulk-enrichment.ts — Process records in batches
import {
  WorkflowBuilder, schedule, httpRequest,
  splitInBatches, merge, code, node,
} from '@n8n/workflow-sdk'

const workflow = new WorkflowBuilder()
  .withName('Contact Enrichment Pipeline')

  // Run every night at 2 AM
  .addTrigger(schedule({ rule: { interval: [{ field: 'hours', triggerAtHour: 2 }] } }))

  // Fetch contacts that need enrichment
  .then(httpRequest({
    url: 'https://api.myapp.com/contacts?needs_enrichment=true&limit=500',
    method: 'GET',
  }))

  // Process in batches of 50 to respect API rate limits
  .then(splitInBatches({ batchSize: 50 }))

  // Enrich each contact via Clearbit
  .then(httpRequest({
    url: 'https://person.clearbit.com/v2/people/find',
    method: 'GET',
    queryParameters: { email: '={{ $json.email }}' },
    headers: { Authorization: '={{ $env.CLEARBIT_KEY }}' },
    options: { batching: { batch: { batchSize: 10, batchInterval: 1000 } } },
  }))

  // Transform and save
  .then(code({
    language: 'typescript',
    code: `
      return items.map(item => ({
        json: {
          contactId: item.json.contactId,
          company: item.json.company?.name,
          title: item.json.title,
          linkedIn: item.json.linkedin?.handle,
          enrichedAt: new Date().toISOString(),
        }
      }))
    `,
  }))

  .then(httpRequest({
    url: 'https://api.myapp.com/contacts/bulk-update',
    method: 'PATCH',
    body: '={{ JSON.stringify($json) }}',
  }))

  .build()

Step 5: Convert Between JSON and TypeScript

// tools/convert.ts — Bidirectional workflow conversion
import {
  generateWorkflowCode,
  parseWorkflowCode,
  validateWorkflow,
} from '@n8n/workflow-sdk'

// JSON → TypeScript (import existing workflows as code)
const existingWorkflowJson = require('./exported-workflow.json')
const tsCode = generateWorkflowCode(existingWorkflowJson)
console.log(tsCode)
// Outputs clean TypeScript using WorkflowBuilder API

// TypeScript → JSON (deploy code-defined workflows)
const workflowJson = parseWorkflowCode(tsCode)
console.log(JSON.stringify(workflowJson, null, 2))
// Outputs valid n8n JSON ready for import

// Validate before deploying
const errors = validateWorkflow(workflowJson)
if (errors.length > 0) {
  console.error('Validation errors:', errors)
  process.exit(1)
}
console.log('Workflow is valid ✓')

Step 6: Deploy Workflows via n8n API

// deploy.ts — Push SDK-built workflows to n8n instance
import { WorkflowBuilder } from '@n8n/workflow-sdk'

async function deployWorkflow(workflow: ReturnType<WorkflowBuilder['build']>) {
  const response = await fetch(`${process.env.N8N_URL}/api/v1/workflows`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-N8N-API-KEY': process.env.N8N_API_KEY!,
    },
    body: JSON.stringify(workflow),
  })

  const result = await response.json()
  console.log(`Deployed: ${result.name} (ID: ${result.id})`)

  // Activate the workflow
  await fetch(`${process.env.N8N_URL}/api/v1/workflows/${result.id}/activate`, {
    method: 'PATCH',
    headers: { 'X-N8N-API-KEY': process.env.N8N_API_KEY! },
  })

  console.log(`Activated: ${result.name}`)
  return result.id
}

// Deploy all workflows from code
const workflows = [
  require('./workflows/data-sync'),
  require('./workflows/lead-routing'),
  require('./workflows/ai-support-agent'),
]

for (const wf of workflows) {
  await deployWorkflow(wf)
}

Guidelines

  • @n8n/workflow-sdk v0.2.0 is an early release (Feb 2026) — API may evolve. Pin the version.
  • Use generateWorkflowCode() to migrate existing JSON workflows to code — great for version control.
  • validateWorkflow() catches node configuration errors before deployment — use in CI.
  • n8n expressions (={{ }}) work in all string parameters — reference previous node data with $json, $env, $fromAi().
  • AI/LangChain nodes use .withSub() to attach language models, memory, and tools to agent nodes.
  • The SDK outputs standard n8n JSON — deploy via the n8n REST API or import through the UI.
  • License is Sustainable Use (n8n proprietary), not open source — check terms for your use case.
  • For workflow-as-code patterns: keep workflows in a workflows/ directory, validate in CI, deploy with a script.