콘텐츠로 이동

n8n 기반 AI Agent Builder 설계와 구현

Interactive Diagram

새 탭 ↗

조직 내에서 LLM 기반 Agent를 활용하려는 수요가 늘고 있지만, 실제로 Agent를 만들고 운영하려면 다음과 같은 장벽이 있다:

  • 워크플로우 엔진의 복잡도: n8n, LangChain 등은 강력하지만 학습 곡선이 높음
  • 반복적 보일러플레이트: Prompt 구성, Tool 연결, 실행 파이프라인이 프로젝트마다 중복 (Tool 실행 연결은 이 PoC의 입증 범위 밖)
  • 운영 가시성 부족: 실행 이력, 에러 추적, 비용 관리가 체계적이지 않음

이 PoC의 핵심 질문은 단순했다:

“n8n을 엔진으로 쓰되, 사용자는 n8n을 몰라도 Agent를 만들고 실행할 수 있을까?”


단일 사용자 PoC의 실행·보안 경계

섹션 제목: “단일 사용자 PoC의 실행·보안 경계”

이 글은 인증/인가를 제외한 단일 사용자 설계 PoC다. Builder UI/API, n8n 관리 화면·API·Webhook과 DB는 로컬 또는 접근이 제한된 개발 네트워크에서만 다룬다. 인터넷이나 조직 공용 네트워크에 인증 없는 endpoint를 공개하는 배포 기준이 아니다. 아래 사항은 운영 전 요구사항이며 이 PoC에서 구현·검증했다는 뜻이 아니다.

  • 접근 제어: Builder API 인증/인가와 별도로 n8n 관리/API 접근을 제한하고, Backend만 Webhook을 호출하도록 네트워크를 제한한다. Webhook에도 Basic/Header/JWT 인증 등 해당 버전이 지원하는 인증을 구성하고 클라이언트가 보내도록 구현해야 한다. n8n API 키는 관리 API용이지 Webhook 인증의 대체물이 아니다. 1.94.1의 Webhook 인증 옵션을 기준으로 설정을 대조한다.
  • Credential ID 권한: Provider별 credential ID는 서버가 승인한 매핑으로 선택한다. ID는 API 키 값이 아니지만 그 credential을 사용할 권한을 대신 증명하지도 않는다. 사용자 입력으로 임의 ID를 선택하게 하지 않고 Agent·사용자·n8n project의 credential 사용 권한을 확인해야 한다. Provider API 키와 n8n API 키는 브라우저에 전달하지 않는다.
  • 로그와 데이터: Prompt, dto.input, 응답, 오류·stack과 n8n execution data에 민감정보가 남을 수 있다. 마스킹, 조회 권한, 보존 기간·삭제 정책을 정하고 개발 테스트에는 비식별 데이터를 쓴다. 본문에 로그 호출이 있다는 사실만으로 마스킹이 검증된 것은 아니다.
PlantUML Diagram

이 구성도에서 Tool Selector와 Tool 저장/API는 관리 측면의 모델이다. 아래에 제시한 생성 Workflow에는 Tool 노드나 AI Agent의 Tool 연결이 없으므로, 선택한 Tool을 실행할 수 있다는 뜻은 아니다.

고려사항n8nLangChain/LangGraph자체 구현
Workflow 시각화✅ 내장❌❌
AI Agent 노드✅ 내장✅직접 구현
Tool 연동 (Slack, HTTP 등)✅ 400+SDK 기반직접 구현
Self-hosted✅✅✅
REST API✅❌직접 구현
학습 곡선 (사용자)높음매우 높음낮음

n8n을 선택한 핵심 이유는 REST API로 Workflow를 프로그래밍 방식으로 제어할 수 있다는 점이다. 사용자에게는 n8n을 노출하지 않으면서, 백엔드에서 n8n API를 통해 Workflow를 자동 생성/배포/실행할 수 있다.


Domain-Driven Design의 Layered Architecture 패턴을 적용했다:

PlantUML Diagram

Domain 계층에서 순수 TypeScript 인터페이스로 Repository Port를 정의한다. 프레임워크 의존이 전혀 없다:

domain/agent/agent.interface.ts
export interface IAgent {
id: string;
name: string;
description: string;
status: AgentStatus;
systemPrompt: string;
modelConfig: ModelConfig;
tools: string[];
createdAt: Date;
updatedAt: Date;
}
export interface IAgentRepository {
findAll(page: number, limit: number, status?: AgentStatus): Promise<{ data: IAgent[]; total: number }>;
findById(id: string): Promise<IAgent | null>;
create(agent: Partial<IAgent>): Promise<IAgent>;
update(id: string, agent: Partial<IAgent>): Promise<IAgent | null>;
updateTools(id: string, toolIds: string[]): Promise<IAgent | null>;
delete(id: string): Promise<boolean>;
}
export const AGENT_REPOSITORY = Symbol('AGENT_REPOSITORY');

Service는 Port를 통해서만 데이터에 접근한다. @Inject(AGENT_REPOSITORY)로 NestJS DI 컨테이너가 Adapter를 주입:

domain/agent/agent.service.ts
@Injectable()
export class AgentService {
constructor(
@Inject(AGENT_REPOSITORY)
private readonly agentRepository: IAgentRepository,
) {}
async findAll(page = 1, limit = 20, status?: AgentStatus) {
return this.agentRepository.findAll(page, limit, status);
}
async create(dto: CreateAgentDto) {
return this.agentRepository.create({
name: dto.name,
description: dto.description,
systemPrompt: dto.systemPrompt,
modelConfig: dto.modelConfig,
tools: dto.tools ?? [],
status: 'draft',
});
}
async deactivate(id: string) {
const agent = await this.agentRepository.findById(id);
if (!agent) return null;
if (agent.status === 'inactive') {
throw new BadRequestException('Agent is already inactive');
}
return this.agentRepository.update(id, { status: 'inactive' });
}
}

TypeORM Entity는 테이블과 컬럼을 매핑하는 저장 모델이다. Repository Port인 IAgentRepository를 구현하는 AgentRepositoryImpl이 Adapter 역할을 하며, 아래 Module에서 이 구현을 주입한다. Entity의 jsonb 컬럼으로 ModelConfig를 유연하게 저장한다:

infrastructure/database/entities/agent.entity.ts
@Entity('agents')
export class AgentEntity {
@PrimaryGeneratedColumn('uuid')
id!: string;
@Column({ length: 255 })
name!: string;
@Column({ type: 'varchar', length: 20, default: 'draft' })
status!: AgentStatus;
@Column({ type: 'text', default: '' })
systemPrompt!: string;
@Column({ type: 'jsonb', default: {} })
modelConfig!: ModelConfig;
@ManyToMany(() => ToolEntity, { eager: true })
@JoinTable({
name: 'agent_tools',
joinColumn: { name: 'agent_id' },
inverseJoinColumn: { name: 'tool_id' },
})
toolEntities!: ToolEntity[];
@Column({ type: 'jsonb', default: [] })
tools!: string[];
@CreateDateColumn()
createdAt!: Date;
}

NestJS Module에서 Port와 Adapter를 바인딩한다:

@Module({
providers: [
AgentService,
{ provide: AGENT_REPOSITORY, useClass: AgentRepositoryImpl },
],
})
export class AgentModule {}

Agent의 목표 추상화는 3가지 요소지만, 아래 코드에서 실행 경로로 제시하는 범위는 Prompt와 Config다:

요소설명예시
Prompt시스템 프롬프트 + 변수 템플릿"당신은 {{role}}입니다"
Tool (확장 대상)ID 저장·선택 모델과 실제 n8n Tool 노드 연결은 별개HTTP Request, Slack, Calculator는 연결 예시가 아닌 후보
Config모델 설정 (provider, model, temperature)Gemini 2.5 Flash, temp=0.7

이 추상화의 핵심은 사용자가 n8n Workflow를 전혀 신경 쓰지 않아도 된다는 것이다.

IAgent.tools, updateTools()와 AgentEntity의 관계는 Tool 목록의 저장·선택 모델이다. 이 글의 buildAgentWorkflow() 구현은 tools 입력을 받지만 생성한 Workflow에 Tool 노드나 ai_tool 연결을 추가하지 않는다. Tool API 테스트도 목록·Agent 할당을 검사할 뿐 실제 n8n Tool 호출을 검증하지 않는다. 따라서 아래 Workflow 예시의 범위는 Webhook → AI Agent + Chat Model → 응답 구성까지이며, Tool 실행 연결은 별도의 구현·검증 과제로 남는다.

Agent를 배포하면, buildAgentWorkflow() 함수가 Agent 설정을 n8n Workflow JSON으로 변환한다:

아래 그래프는 Tool 연결이 없는 생성 경로를 설명한다. 그림과 TypeScript 발췌만으로 배포 성공이나 Tool 실행을 검증했다고 보지 않는다.

PlantUML Diagram

제시된 TypeScript 발췌는 LLM Provider에 따른 Chat Model 노드 생성 분기를 보여준다. Tool 노드 생성은 이 분기에 포함되지 않는다:

packages/n8n-client/src/templates/agent-workflow.ts
function buildChatModelNode(input: AgentWorkflowInput): N8nNode {
if (input.provider === 'anthropic') {
return {
name: 'Chat Model',
type: '@n8n/n8n-nodes-langchain.lmChatAnthropic',
typeVersion: 1.2,
parameters: {
model: input.model || 'claude-sonnet-4-20250514',
options: {
temperature: input.temperature ?? 0.7,
maxTokensToSample: input.maxTokens ?? 4096,
},
},
credentials: {
anthropicApi: { id: input.credentialId || '', name: 'Anthropic API' },
},
};
}
// Default: Gemini
return {
name: 'Chat Model',
type: '@n8n/n8n-nodes-langchain.lmChatGoogleGemini',
typeVersion: 1,
parameters: {
modelName: input.model || 'models/gemini-2.5-flash',
options: {
temperature: input.temperature ?? 0.7,
maxOutputTokens: input.maxTokens ?? 2048,
},
},
credentials: {
googlePalmApi: { id: input.credentialId || '', name: 'Google AI (Gemini)' },
},
};
}

제시된 N8nIntegrationService 발췌는 이 템플릿으로 Workflow를 생성·활성화하려는 경로를 보여준다:

infrastructure/n8n/n8n-integration.service.ts
async deployAgent(input: DeployAgentInput): Promise<DeployResult> {
const webhookPath = `agent-${input.agentId}`;
const workflowDef = buildAgentWorkflow({
agentId: input.agentId,
agentName: input.agentName,
systemPrompt: input.systemPrompt,
model: input.model,
provider: input.provider ?? 'gemini',
webhookPath,
credentialId,
});
// Sequential reuse — update if found, otherwise create
const existing = await this.findWorkflowByName(workflowDef.name!);
let workflow: N8nWorkflow;
if (existing) {
workflow = await this.client.updateWorkflow(existing.id, workflowDef);
} else {
workflow = await this.client.createWorkflow(workflowDef);
}
if (!workflow.active) {
await this.client.activateWorkflow(workflow.id);
}
// ...
}

이름 조회 후 update/create하는 코드는 같은 이름의 Workflow 하나를 찾을 수 있는 순차 호출에서 재사용하려는 흐름이다. 조회와 생성이 원자적이지 않아 동시 요청이 모두 create할 수 있고, 중복 이름·설정 업데이트 충돌도 막지 않는다. 실행마다 rendered를 공유 Workflow에 배포하므로 동시 실행에서는 한 요청의 system prompt가 다른 요청에 의해 덮어써질 수도 있다. Workflow 재사용은 Webhook 재호출의 중복 LLM 실행·비용을 막는 실행 멱등성과도 별개다. 저장된 workflow ID와 Agent/config revision 매핑, 배포 직렬화 또는 요청별 격리, 실행 idempotency key와 timeout 후 재시도·상태 복구는 후속 설계·검증 과제다.

Agent 실행은 6단계 파이프라인으로 구성된다. ExecutionService가 전체 흐름을 오케스트레이션한다:

PlantUML Diagram

발췌의 rendered는 계산만 보이고, deployAgent({ ... })의 인자와 message·startTime 정의는 생략되어 있다. 과거 글의 원본 저장소 참조를 따라 비공개 원본의 revision f752fc290906b80f49f4f7cd19f81992a42e0552에서 execution.service.ts, n8n-integration.service.ts, agent-workflow.ts를 읽어 다음 매핑을 확인했다. 이는 소스 확인이며 실행 성공의 증거가 아니다. 원본은 공개 접근이 되지 않으므로 독자가 확인할 수 있도록 민감정보 없는 대응만 정리한다.

값확인한 전달 경로의미와 한계
dto.inputexecution input 저장 및 renderTemplate(agent.systemPrompt, variables)의 변수 입력as Record<string, string>은 타입 단언이지 런타임 입력 검증이 아님
rendereddeployAgent({ systemPrompt: rendered, ... }) → buildAgentWorkflow() → AI Agent parameters.options.systemMessageAI Agent의 system prompt; 원본은 renderedPrompt에도 저장
messagedto.input.message ?? rendered → executeAgent(path, message) → Webhook JSON { message }명시적 message가 없으면 rendered를 사용자 입력에도 재사용; system prompt와 같은 역할이라는 뜻은 아님
Webhook bodyAI Agent의 text: '={{ $json.body.message }}'사용자 Prompt용 expression; 실제 평가·모델 응답은 미검증
startTime원본 내부 실행 함수 시작의 Date.now()durationMs 계산 기준; 발췌에는 정의가 생략됨

원본 템플릿의 Webhook은 typeVersion: 2, AI Agent는 typeVersion: 1이다. 아래 발췌는 생략을 유지하며, 위 매핑이 입력 검증·AI Agent의 Prompt 설정·Tool 연결까지 올바르게 동작함을 보장하지 않는다. 소스 위치: apps/api/src/domain/execution/execution.service.ts, packages/n8n-client/src/templates/agent-workflow.ts (비공개).

domain/execution/execution.service.ts
async execute(dto: CreateExecutionDto): Promise<ExecutionRecord> {
// 1. Validate — Agent 존재 + active 여부
const agent = await this.agentRepo.findById(dto.agentId);
if (!agent) throw new NotFoundException(`Agent ${dto.agentId} not found`);
if (agent.status !== 'active') {
throw new BadRequestException(`Agent is not active (status: ${agent.status})`);
}
// 2. Create execution record (pending)
const execution = await this.executionRepo.create({
agentId: dto.agentId, input: dto.input, status: 'pending',
});
// 3. Render prompt — 변수 치환
const variables = dto.input as Record<string, string>;
const { text: rendered } = renderTemplate(agent.systemPrompt || '', variables);
await this.logService.log(execution.id, 'render', 'Prompt rendered');
// 4. Deploy workflow (sequential reuse)
const deployResult = await this.n8nService.deployAgent({ ... });
await this.logService.log(execution.id, 'deploy', `Workflow: ${deployResult.workflowId}`);
// 5. Execute via webhook
const result = await this.n8nService.executeAgent(deployResult.webhookPath, message);
await this.logService.log(execution.id, 'execute', 'Webhook executed');
// 6. Save result (completed)
const durationMs = Date.now() - startTime;
return this.executionRepo.update(execution.id, {
status: 'completed', output: result, durationMs,
});
}

발췌 코드에는 render, deploy, execute 로그 호출과 성공 시 completed 저장이 보인다. validate·complete의 step별 input/output 저장이나 예외 시 failed 전환은 이 발췌에 나타나지 않으므로 보장하지 않는다. ...로 생략한 호출부도 실행 가능한 완전한 코드가 아니다.


LayerTechnology선택 이유
FrontendNext.js 16App Router, Server Components
BackendNestJSDI, Module 시스템, TypeORM 통합
DatabasePostgreSQL 16JSON 컬럼 활용 (modelConfig, tools)
Workflown8n 1.94.1REST API, AI Agent 노드, Self-hosted
LLMGemini 2.5 FlashFree Tier, 빠른 응답 속도
Monorepopnpm workspaceshared 패키지 공유
  • 디렉터리n8n-poc/
    • 디렉터리apps/
      • 디렉터리api/ NestJS Backend (Port 3001)
        • 디렉터리src/
          • 디렉터리domain/ Service + Port interfaces
            • …
          • 디렉터리infrastructure/ TypeORM adapters, n8n 연동
            • …
          • 디렉터리interface/ Controllers
            • …
      • 디렉터리web/ Next.js Frontend (Port 3000)
        • …
    • 디렉터리packages/
      • 디렉터리shared/ 공유 타입, DTO, prompt utils, masking
        • …
      • 디렉터리n8n-client/ n8n REST API 클라이언트 + workflow template
        • …
    • 디렉터리docker/
      • docker-compose.yml PostgreSQL + n8n

n8n API의 contract와 특정 환경에서 보고한 현상을 구분해야 한다. 이 글의 버전 표기는 1.94.1이며, 아래 확인은 그 release tag의 공식 소스와 2.0 변경 문서에 근거한다. 과거에 비교한 2.x의 정확한 patch 버전, 대기·500 오류의 요청/로그는 남아 있지 않아 재현 결과로 제시하지 않는다.

Webhook 경로는 노드 설정에 따라 달라진다

섹션 제목: “Webhook 경로는 노드 설정에 따라 달라진다”
POST /webhook/{workflowId}/webhook/{userDefinedPath}

이 경로는 1.94.1 전체의 고정 규칙이 아니다. 원본 템플릿은 노드 이름이 Webhook이고 webhookId를 지정하지 않았다. 1.94.1의 getNodeWebhookPath()는 이 경우 {workflowId}/{소문자 node.name}/{path}를 사용하므로 위 형태가 된다. webhookId가 있고 isFullPath가 true이면 설정한 path만 쓰고, 그렇지 않으면 {webhookId}/{path}를 쓴다. 동적 path도 별도 분기를 거치므로 다른 Workflow에 이 URL을 그대로 적용하지 않는다.

/webhook/은 기본 production endpoint이고 test URL과 구분한다. 1.94.1에서는 production 호출 전 Workflow 활성화가 필요하다(Webhook 노드의 안내). 실제 주소는 n8n이 표시한 URL과 Webhook 노드 JSON, reverse proxy/base URL·endpoint 설정을 대조한다. 아래 E2E 도식의 URL도 이 PoC 템플릿에 한정한 의도한 경로다.

Task runners는 AI Agent 자체의 필수 조건이 아니다

섹션 제목: “Task runners는 AI Agent 자체의 필수 조건이 아니다”
docker-compose.yml
N8N_RUNNERS_ENABLED: 'true' # Task runners 활성화; AI Agent 필수 조건 아님

1.94.1의 TaskRunnersConfig 기본값은 false다. Task runners는 Code 노드의 코드 실행을 위한 기능이며, AI Agent 자체를 켜는 스위치가 아니다(공식 Task runners 설명). 같은 버전의 Tools Agent V1 실행 코드는 Chat Model과 LangChain executor를 사용한다. Code 노드·코드 기반 Tool의 runner 요구사항과 Agent 자체의 실행 조건을 혼동하지 않는다.

기존 기록의 “설정이 없으면 무한 대기”는 이 환경 변수의 필수성을 입증하지 않는다. 해당 요청, AI Agent 설정과 로그가 없어 원인은 미확인이다. 이 변수만 바꾸는 해결책 대신 모델 credential·연결, Prompt 설정, 실행 오류·timeout을 각각 확인해야 한다.

2.0 변경 문서는 UI의 Activate/Deactivate를 Publish/Unpublish로 바꾸고 저장된 draft와 실행 버전을 구분한다. 그러나 “API activate 외에 별도 publish 호출이 항상 필요하다”는 설명은 틀리다. 확인한 2.0.0 Public API의 activateWorkflow handler와 Workflow service는 POST /api/v1/workflows/{id}/activate에서 선택한 versionId(생략하면 현재 workflow.versionId)를 activeVersionId로 설정하고 활성화한다. 즉 이 endpoint가 실행 버전의 publish 역할을 수행한다.

이 PoC 원본 클라이언트도 /api/v1/workflows/{id}/activate를 호출한다. 2.x로 옮길 때는 active boolean만 보고 업데이트된 draft가 실행 중이라고 판단하지 말고 실행 버전과 Webhook 등록을 확인해야 한다. 여기서는 2.0.0 소스의 의미만 확인했으며, PoC의 2.x 호환성이나 과거 비교 환경의 성공·실패를 검증하지 않았다. 본문의 1.94.1은 당시 설계 기록이지 새 배포에 권장하는 버전은 아니다.

1.94.1의 Google Gemini Chat Model 노드는 Google AI (Gemini) API 키를 googlePalmApi credential type으로 참조한다. 이름은 Palm이지만 이 노드도 같은 타입을 사용한다. 타입 이름과 credential ID가 맞는지는 별도로 확인한다.

Workflow 생성의 settings contract와 오류 상태

섹션 제목: “Workflow 생성의 settings contract와 오류 상태”

1.94.1의 Public API POST /api/v1/workflows Workflow schema는 name, nodes, connections, settings를 필수로 선언한다. 따라서 설정이 없더라도 settings: {}를 포함하는 것이 이 API contract에 맞다. 원본 클라이언트의 create/update도 { settings: {}, ...workflow }로 payload를 구성한다.

다만 “누락하면 500”은 일반 규칙이 아니다. 같은 버전의 생성 endpoint 명세는 잘못된 요청에 400을 문서화한다. 과거 기록의 500은 실제 request body·응답·서버 로그가 없어 확인하지 못한 환경 관찰로 남긴다. 이 필수 필드를 내부 /rest API나 모든 n8n 버전의 동작으로 확대하지 않는다.


다음은 검증 대상인 의도한 경로다. 이 글에는 재현 가능한 실행 기록, 측정 환경, 실패 테스트 결과가 없으므로 실제 E2E 성공으로 단정하지 않는다:

PlantUML Diagram
  • 성공 경로 확인: Agent를 active로 설정하고 익명 입력으로 실행한 뒤, API 응답·저장된 execution의 completed 상태와 output을 애플리케이션 실행 ID로 대조한다. n8n 실행은 별도 ID를 가질 수 있으므로 workflow ID와 시각·로그로 연결하고 혼동하지 않는다. 이 글은 해당 기록을 제공하지 않는다.
  • 응답 시간 확인: 요청 시작/종료 시각과 durationMs를 반복 측정해 분포·환경을 함께 기록한다. 측정 자료가 없어 특정 초 단위 수치를 주장하지 않는다.
  • 로그·실패 확인: DB에서 render·deploy·execute 로그와 민감정보 마스킹을 확인한다. Webhook 실패를 주입해 execution이 pending에 남지 않고 failed와 안전한 오류 정보로 전환되는지도 별도로 테스트해야 한다. 제시된 성공 경로 코드에는 그 실패 전환이 없다.

가설본문에서 확인되는 범위
n8n 위에 Agent 추상화가 성립하는가?Prompt/Config를 Workflow로 매핑하는 코드와 구조를 제시; 실제 실행 결과는 제공하지 않음
Prompt + Tool + Workflow 모델이 실용적인가?Tool 목록·할당 모델은 있지만 생성 Workflow에는 Tool 연결이 없으므로 Tool 실행은 이 PoC에서 확인되지 않음
최소한의 Builder UI가 가능한가?UI 구성은 제시하지만 동작 검증 기록은 제공하지 않음
  • 멀티테넌시: 단일 사용자 PoC
  • RBAC: 인증/인가 없음
  • 비용 최적화: 토큰 사용량 추적 없음
  • Prompt 버저닝: 변경 이력 관리 없음
  • 멀티 Agent: Agent 간 협업/체이닝
  • Tool 실행 연결: 선택한 Tool을 n8n 노드·credential·AI Agent 연결로 변환하고 실제 호출을 검증하는 작업

이 PoC를 기반으로 Backstage IDP로 AI Agent Builder 통합에서는 Backstage IDP 플러그인으로 통합하여, 조직 내부의 개발자 포털에서 AI Agent를 관리하는 구조를 만들어본다.


소스 접근 범위: 저장소는 공개 접근이 되지 않아 이 글에는 민감정보를 제외한 코드 발췌만 담았다. 이 글의 코드·도식은 실행 결과를 대체하지 않는다.