@awesomate/hosting-mcp 0.12.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/dist/index.js +204 -8
  2. package/package.json +2 -2
  3. package/skill/awesomate-app-builder/SKILL.md +5 -1
  4. package/skill/awesomate-credentials/SKILL.md +1 -1
  5. package/skill/awesomate-hosting/SKILL.md +50 -159
  6. package/skill/awesomate-hosting/references/connect-troubleshooting.md +77 -0
  7. package/skill/awesomate-hosting/references/multi-account.md +33 -0
  8. package/skill/awesomate-hosting/references/rest-fallback.md +30 -0
  9. package/skill/awesomate-hosting/scripts/bootstrap.mjs +27 -7
  10. package/skill/awesomate-n8n/SKILL.md +153 -147
  11. package/skill/awesomate-n8n/evals/ai-agent-build/graders/grader.md +31 -0
  12. package/skill/awesomate-n8n/evals/ai-agent-build/prompt.md +1 -0
  13. package/skill/awesomate-n8n/evals/build-form-email/graders/grader.md +30 -0
  14. package/skill/awesomate-n8n/evals/build-form-email/prompt.md +1 -0
  15. package/skill/awesomate-n8n/evals/datatable-dedupe/graders/grader.md +32 -0
  16. package/skill/awesomate-n8n/evals/datatable-dedupe/prompt.md +2 -0
  17. package/skill/awesomate-n8n/evals/diagnose-failure/graders/grader.md +27 -0
  18. package/skill/awesomate-n8n/evals/diagnose-failure/prompt.md +2 -0
  19. package/skill/awesomate-n8n/evals/essentials-upsell/graders/grader.md +27 -0
  20. package/skill/awesomate-n8n/evals/essentials-upsell/prompt.md +2 -0
  21. package/skill/awesomate-n8n/evals/live-change-promote/graders/grader.md +35 -0
  22. package/skill/awesomate-n8n/evals/live-change-promote/prompt.md +2 -0
  23. package/skill/awesomate-n8n/evals/possibilities-grounded/graders/grader.md +28 -0
  24. package/skill/awesomate-n8n/evals/possibilities-grounded/prompt.md +1 -0
  25. package/skill/awesomate-n8n/evals/validated-not-done/graders/grader.md +27 -0
  26. package/skill/awesomate-n8n/evals/validated-not-done/prompt.md +2 -0
  27. package/skill/awesomate-n8n/evals/vars-not-env/graders/grader.md +26 -0
  28. package/skill/awesomate-n8n/evals/vars-not-env/prompt.md +2 -0
  29. package/skill/awesomate-n8n/evals/webhook-body-fix/graders/grader.md +26 -0
  30. package/skill/awesomate-n8n/evals/webhook-body-fix/prompt.md +3 -0
  31. package/skill/awesomate-n8n/references/ai-agents.md +135 -0
  32. package/skill/awesomate-n8n/references/datatables.md +105 -0
  33. package/skill/awesomate-n8n/references/{node-recipes.md → platform-notes.md} +56 -7
  34. package/skill/awesomate-n8n/references/possibilities.md +83 -0
  35. package/skill/awesomate-n8n/references/testing-policy.md +115 -0
  36. package/skill/awesomate-n8n/references/troubleshooting.md +69 -0
  37. package/skill/awesomate-n8n/references/upgrade-loop.md +98 -0
  38. package/skill/awesomate-n8n/references/vendor/MANIFEST.json +26 -0
  39. package/skill/awesomate-n8n/references/vendor/code-node/BUILTIN_FUNCTIONS.md +779 -0
  40. package/skill/awesomate-n8n/references/vendor/code-node/COMMON_PATTERNS.md +1123 -0
  41. package/skill/awesomate-n8n/references/vendor/code-node/DATA_ACCESS.md +797 -0
  42. package/skill/awesomate-n8n/references/vendor/code-node/ERROR_PATTERNS.md +776 -0
  43. package/skill/awesomate-n8n/references/vendor/code-node/SKILL.md +703 -0
  44. package/skill/awesomate-n8n/references/vendor/expressions/COMMON_MISTAKES.md +406 -0
  45. package/skill/awesomate-n8n/references/vendor/expressions/EXAMPLES.md +496 -0
  46. package/skill/awesomate-n8n/references/vendor/expressions/SKILL.md +525 -0
  47. package/skill/awesomate-n8n/references/vendor/node-configuration/DEPENDENCIES.md +743 -0
  48. package/skill/awesomate-n8n/references/vendor/node-configuration/OPERATION_PATTERNS.md +926 -0
  49. package/skill/awesomate-n8n/references/vendor/node-configuration/SKILL.md +583 -0
  50. package/skill/awesomate-n8n/references/vendor/validation/ERROR_CATALOG.md +781 -0
  51. package/skill/awesomate-n8n/references/vendor/validation/FALSE_POSITIVES.md +695 -0
  52. package/skill/awesomate-n8n/references/vendor/validation/SKILL.md +414 -0
  53. package/skill/awesomate-n8n/references/vendor/workflow-patterns/SKILL.md +413 -0
  54. package/skill/awesomate-n8n/references/vendor/workflow-patterns/ai_agent_workflow.md +797 -0
  55. package/skill/awesomate-n8n/references/vendor/workflow-patterns/database_operations.md +798 -0
  56. package/skill/awesomate-n8n/references/vendor/workflow-patterns/http_api_integration.md +747 -0
  57. package/skill/awesomate-n8n/references/vendor/workflow-patterns/scheduled_tasks.md +786 -0
  58. package/skill/awesomate-n8n/references/vendor/workflow-patterns/webhook_processing.md +558 -0
@@ -0,0 +1,797 @@
1
+ <!--
2
+ VENDORED from n8n-builder@d293559 (n8n-workflow-patterns/ai_agent_workflow.md) — DO NOT EDIT HERE.
3
+ Edit the source in ~/Projects/n8n-builder, then re-run:
4
+ node mcp/scripts/sync-n8n-references.mjs --write
5
+
6
+ Awesomate platform overrides — where this file conflicts with
7
+ ../platform-notes.md, platform-notes wins:
8
+ - $env is BLOCKED fleet-wide → use {{ $vars.key || 'fallback' }}
9
+ - Task runners are ON → no $helpers in Code nodes; use HTTP Request nodes
10
+ - Webhook payloads live at $json.body
11
+ - saveExecutionProgress must stay false
12
+ -->
13
+
14
+ # AI Agent Workflow Pattern
15
+
16
+ **Use Case**: Build AI agents with tool access, memory, and reasoning capabilities.
17
+
18
+ ---
19
+
20
+ ## Pattern Structure
21
+
22
+ ```
23
+ Trigger → AI Agent (Model + Tools + Memory) → [Process Response] → Output
24
+ ```
25
+
26
+ **Key Characteristic**: AI-powered decision making with tool use
27
+
28
+ ---
29
+
30
+ ## Core AI Connection Types
31
+
32
+ n8n supports **8 AI connection types** for building agent workflows:
33
+
34
+ 1. **ai_languageModel** - The LLM (OpenAI, Anthropic, etc.)
35
+ 2. **ai_tool** - Functions the agent can call
36
+ 3. **ai_memory** - Conversation context
37
+ 4. **ai_outputParser** - Parse structured outputs
38
+ 5. **ai_embedding** - Vector embeddings
39
+ 6. **ai_vectorStore** - Vector database
40
+ 7. **ai_document** - Document loaders
41
+ 8. **ai_textSplitter** - Text chunking
42
+
43
+ ---
44
+
45
+ ## Core Components
46
+
47
+ ### 1. Trigger
48
+ **Options**:
49
+ - **Webhook** - Chat interfaces, API calls (most common)
50
+ - **Manual** - Testing and development
51
+ - **Schedule** - Periodic AI tasks
52
+
53
+ ### 2. AI Agent Node
54
+ **Purpose**: Orchestrate LLM with tools and memory
55
+
56
+ **Configuration**:
57
+ ```javascript
58
+ {
59
+ agent: "conversationalAgent", // or "openAIFunctionsAgent"
60
+ promptType: "define",
61
+ text: "You are a helpful assistant that can search docs, query databases, and send emails."
62
+ }
63
+ ```
64
+
65
+ **Connections**:
66
+ - **ai_languageModel input** - Connected to LLM node
67
+ - **ai_tool inputs** - Connected to tool nodes
68
+ - **ai_memory input** - Connected to memory node (optional)
69
+
70
+ ### 3. Language Model
71
+ **Available providers**:
72
+ - OpenAI (GPT-4, GPT-3.5)
73
+ - Anthropic (Claude)
74
+ - Google (Gemini)
75
+ - Local models (Ollama, LM Studio)
76
+
77
+ **Example** (OpenAI Chat Model):
78
+ ```javascript
79
+ {
80
+ model: "gpt-4",
81
+ temperature: 0.7,
82
+ maxTokens: 1000
83
+ }
84
+ ```
85
+
86
+ ### 4. Tools (ANY Node Can Be a Tool!)
87
+ **Critical insight**: Connect ANY n8n node to agent via `ai_tool` port
88
+
89
+ **Common tool types**:
90
+ - HTTP Request - Call APIs
91
+ - Database nodes - Query data
92
+ - Code - Custom functions
93
+ - Search nodes - Web/document search
94
+ - Pre-built tool nodes (Calculator, Wikipedia, etc.)
95
+
96
+ ### 5. Memory (Optional but Recommended)
97
+ **Purpose**: Maintain conversation context
98
+
99
+ **Types**:
100
+ - **Buffer Memory** - Store recent messages
101
+ - **Window Buffer Memory** - Store last N messages
102
+ - **Summary Memory** - Summarize conversation
103
+
104
+ ### 6. Output Processing
105
+ **Purpose**: Format AI response for delivery
106
+
107
+ **Common patterns**:
108
+ - Return directly (chat response)
109
+ - Store in database (conversation history)
110
+ - Send to communication channel (Slack, email)
111
+
112
+ ---
113
+
114
+ ## Common Use Cases
115
+
116
+ ### 1. Conversational Chatbot
117
+ **Flow**: Webhook (chat message) → AI Agent → Webhook Response
118
+
119
+ **Example** (Customer support bot):
120
+ ```
121
+ 1. Webhook (path: "chat", POST)
122
+ - Receives: {user_id, message, session_id}
123
+
124
+ 2. Window Buffer Memory (load context by session_id)
125
+
126
+ 3. AI Agent
127
+ ├─ OpenAI Chat Model (gpt-4)
128
+ ├─ HTTP Request Tool (search knowledge base)
129
+ ├─ Database Tool (query customer orders)
130
+ └─ Window Buffer Memory (conversation context)
131
+
132
+ 4. Code (format response)
133
+
134
+ 5. Webhook Response (send reply)
135
+ ```
136
+
137
+ **AI Agent prompt**:
138
+ ```
139
+ You are a customer support assistant.
140
+ You can:
141
+ 1. Search the knowledge base for answers
142
+ 2. Look up customer orders
143
+ 3. Provide shipping information
144
+
145
+ Be helpful and professional.
146
+ ```
147
+
148
+ ### 2. Document Q&A
149
+ **Flow**: Upload docs → Embed → Store → Query with AI
150
+
151
+ **Example** (Internal documentation assistant):
152
+ ```
153
+ Setup Phase (run once):
154
+ 1. Read Files (load documentation)
155
+ 2. Text Splitter (chunk into paragraphs)
156
+ 3. Embeddings (OpenAI Embeddings)
157
+ 4. Vector Store (Pinecone/Qdrant) (store vectors)
158
+
159
+ Query Phase (recurring):
160
+ 1. Webhook (receive question)
161
+ 2. AI Agent
162
+ ├─ OpenAI Chat Model (gpt-4)
163
+ ├─ Vector Store Tool (search similar docs)
164
+ └─ Buffer Memory (context)
165
+ 3. Webhook Response (answer with citations)
166
+ ```
167
+
168
+ ### 3. Data Analysis Assistant
169
+ **Flow**: Request → AI Agent (with data tools) → Analysis → Visualization
170
+
171
+ **Example** (SQL analyst agent):
172
+ ```
173
+ 1. Webhook (data question: "What were sales last month?")
174
+
175
+ 2. AI Agent
176
+ ├─ OpenAI Chat Model (gpt-4)
177
+ ├─ Postgres Tool (execute queries)
178
+ └─ Code Tool (data analysis)
179
+
180
+ 3. Code (generate visualization data)
181
+
182
+ 4. Webhook Response (answer + chart data)
183
+ ```
184
+
185
+ **Postgres Tool Configuration**:
186
+ ```javascript
187
+ {
188
+ name: "query_database",
189
+ description: "Execute SQL queries to analyze sales data. Use SELECT queries only.",
190
+ // Node executes AI-generated SQL
191
+ }
192
+ ```
193
+
194
+ ### 4. Workflow Automation Agent
195
+ **Flow**: Command → AI Agent → Execute actions → Report
196
+
197
+ **Example** (DevOps assistant):
198
+ ```
199
+ 1. Slack (slash command: /deploy production)
200
+
201
+ 2. AI Agent
202
+ ├─ OpenAI Chat Model (gpt-4)
203
+ ├─ HTTP Request Tool (GitHub API)
204
+ ├─ HTTP Request Tool (Deploy API)
205
+ └─ Postgres Tool (deployment logs)
206
+
207
+ 3. Agent actions:
208
+ - Check if tests passed
209
+ - Create deployment
210
+ - Log deployment
211
+ - Notify team
212
+
213
+ 4. Slack (deployment status)
214
+ ```
215
+
216
+ ### 5. Email Processing Agent
217
+ **Flow**: Email received → AI Agent → Categorize → Route → Respond
218
+
219
+ **Example** (Support ticket router):
220
+ ```
221
+ 1. Email Trigger (new support email)
222
+
223
+ 2. AI Agent
224
+ ├─ OpenAI Chat Model (gpt-4)
225
+ ├─ Vector Store Tool (search similar tickets)
226
+ └─ HTTP Request Tool (create Jira ticket)
227
+
228
+ 3. Agent actions:
229
+ - Categorize urgency (low/medium/high)
230
+ - Find similar past tickets
231
+ - Create ticket in appropriate project
232
+ - Draft response
233
+
234
+ 4. Email (send auto-response)
235
+ 5. Slack (notify assigned team)
236
+ ```
237
+
238
+ ---
239
+
240
+ ## Tool Configuration
241
+
242
+ ### Making ANY Node an AI Tool
243
+
244
+ **Critical concept**: Any n8n node can become an AI tool!
245
+
246
+ **Requirements**:
247
+ 1. Connect node to AI Agent via `ai_tool` port (NOT main port)
248
+ 2. Configure tool name and description
249
+ 3. Define input schema (optional)
250
+
251
+ **Example** (HTTP Request as tool):
252
+ ```javascript
253
+ {
254
+ // Tool metadata (for AI)
255
+ name: "search_github_issues",
256
+ description: "Search GitHub issues by keyword. Returns issue titles and URLs.",
257
+
258
+ // HTTP Request configuration
259
+ method: "GET",
260
+ url: "https://api.github.com/search/issues",
261
+ sendQuery: true,
262
+ queryParameters: {
263
+ "q": "={{$json.query}} repo:{{$json.repo}}",
264
+ "per_page": "5"
265
+ }
266
+ }
267
+ ```
268
+
269
+ **How it works**:
270
+ 1. AI Agent sees tool: `search_github_issues(query, repo)`
271
+ 2. AI decides to use it: `search_github_issues("bug", "n8n-io/n8n")`
272
+ 3. n8n executes HTTP Request with parameters
273
+ 4. Result returned to AI Agent
274
+ 5. AI Agent processes result and responds
275
+
276
+ ### Pre-built Tool Nodes
277
+
278
+ **Available in @n8n/n8n-nodes-langchain**:
279
+
280
+ - **Calculator Tool** - Math operations
281
+ - **Wikipedia Tool** - Wikipedia search
282
+ - **Serper Tool** - Google search
283
+ - **Wolfram Alpha Tool** - Computational knowledge
284
+ - **Custom Tool** - Define with Code node
285
+
286
+ **Example** (Calculator Tool):
287
+ ```
288
+ AI Agent
289
+ ├─ OpenAI Chat Model
290
+ └─ Calculator Tool (ai_tool connection)
291
+
292
+ User: "What's 15% of 2,847?"
293
+ AI: *uses calculator tool* → "426.05"
294
+ ```
295
+
296
+ ### Database as Tool
297
+
298
+ **Pattern**: Postgres/MySQL node connected as ai_tool
299
+
300
+ **Configuration**:
301
+ ```javascript
302
+ {
303
+ // Tool metadata
304
+ name: "query_customers",
305
+ description: "Query customer database. Use SELECT queries to find customer information by email, name, or ID.",
306
+
307
+ // Postgres config
308
+ operation: "executeQuery",
309
+ query: "={{$json.sql}}", // AI provides SQL
310
+ // Security: Use read-only database user!
311
+ }
312
+ ```
313
+
314
+ **Safety**: Create read-only DB user for AI tools!
315
+
316
+ ```sql
317
+ CREATE USER ai_readonly WITH PASSWORD 'secure_password';
318
+ GRANT SELECT ON customers, orders TO ai_readonly;
319
+ -- NO INSERT, UPDATE, DELETE access
320
+ ```
321
+
322
+ ### Code Node as Tool
323
+
324
+ **Pattern**: Custom Python/JavaScript function
325
+
326
+ **Example** (Data processor):
327
+ ```javascript
328
+ // Tool metadata
329
+ {
330
+ name: "process_csv",
331
+ description: "Process CSV data and return statistics. Input: csv_string"
332
+ }
333
+
334
+ // Code node
335
+ const csv = $input.first().json.csv_string;
336
+ const lines = csv.split('\n');
337
+ const data = lines.slice(1).map(line => line.split(','));
338
+
339
+ return [{
340
+ json: {
341
+ row_count: data.length,
342
+ columns: lines[0].split(','),
343
+ summary: {
344
+ // Calculate statistics
345
+ }
346
+ }
347
+ }];
348
+ ```
349
+
350
+ ---
351
+
352
+ ## Memory Configuration
353
+
354
+ ### Buffer Memory
355
+ **Stores all messages** (until cleared)
356
+
357
+ ```javascript
358
+ {
359
+ memoryType: "bufferMemory",
360
+ sessionKey: "={{$json.body.user_id}}" // Per-user memory
361
+ }
362
+ ```
363
+
364
+ ### Window Buffer Memory
365
+ **Stores last N messages** (recommended)
366
+
367
+ ```javascript
368
+ {
369
+ memoryType: "windowBufferMemory",
370
+ sessionKey: "={{$json.body.session_id}}",
371
+ contextWindowLength: 10 // Last 10 messages
372
+ }
373
+ ```
374
+
375
+ ### Summary Memory
376
+ **Summarizes old messages** (for long conversations)
377
+
378
+ ```javascript
379
+ {
380
+ memoryType: "summaryMemory",
381
+ sessionKey: "={{$json.body.session_id}}",
382
+ maxTokenLimit: 2000
383
+ }
384
+ ```
385
+
386
+ **How it works**:
387
+ 1. Conversation grows beyond limit
388
+ 2. AI summarizes old messages
389
+ 3. Summary stored, old messages discarded
390
+ 4. Saves tokens while maintaining context
391
+
392
+ ---
393
+
394
+ ## Agent Types
395
+
396
+ ### 1. Conversational Agent
397
+ **Best for**: General chat, customer support
398
+
399
+ **Features**:
400
+ - Natural conversation flow
401
+ - Memory integration
402
+ - Tool use with reasoning
403
+
404
+ **When to use**: Most common use case
405
+
406
+ ### 2. OpenAI Functions Agent
407
+ **Best for**: Tool-heavy workflows, structured outputs
408
+
409
+ **Features**:
410
+ - Optimized for function calling
411
+ - Better tool selection
412
+ - Structured responses
413
+
414
+ **When to use**: Multiple tools, need reliable tool calling
415
+
416
+ ### 3. ReAct Agent
417
+ **Best for**: Step-by-step reasoning
418
+
419
+ **Features**:
420
+ - Think → Act → Observe loop
421
+ - Visible reasoning process
422
+ - Good for debugging
423
+
424
+ **When to use**: Complex multi-step tasks
425
+
426
+ ---
427
+
428
+ ## Prompt Engineering for Agents
429
+
430
+ ### System Prompt Structure
431
+ ```
432
+ You are a [ROLE].
433
+
434
+ You can:
435
+ - [CAPABILITY 1]
436
+ - [CAPABILITY 2]
437
+ - [CAPABILITY 3]
438
+
439
+ Guidelines:
440
+ - [GUIDELINE 1]
441
+ - [GUIDELINE 2]
442
+
443
+ Format:
444
+ - [OUTPUT FORMAT]
445
+ ```
446
+
447
+ ### Example (Customer Support)
448
+ ```
449
+ You are a customer support assistant for Acme Corp.
450
+
451
+ You can:
452
+ - Search the knowledge base for answers
453
+ - Look up customer orders and shipping status
454
+ - Create support tickets for complex issues
455
+
456
+ Guidelines:
457
+ - Be friendly and professional
458
+ - If you don't know something, say so and offer to create a ticket
459
+ - Always verify customer identity before sharing order details
460
+
461
+ Format:
462
+ - Keep responses concise
463
+ - Use bullet points for multiple items
464
+ - Include relevant links when available
465
+ ```
466
+
467
+ ### Example (Data Analyst)
468
+ ```
469
+ You are a data analyst assistant with access to the company database.
470
+
471
+ You can:
472
+ - Query sales, customer, and product data
473
+ - Perform data analysis and calculations
474
+ - Generate summary statistics
475
+
476
+ Guidelines:
477
+ - Write efficient SQL queries (always use LIMIT)
478
+ - Explain your analysis methodology
479
+ - Highlight important trends or anomalies
480
+ - Use read-only queries (SELECT only)
481
+
482
+ Format:
483
+ - Provide numerical answers with context
484
+ - Include query used (for transparency)
485
+ - Suggest follow-up analyses when relevant
486
+ ```
487
+
488
+ ---
489
+
490
+ ## Error Handling
491
+
492
+ ### Pattern 1: Tool Execution Errors
493
+ ```
494
+ AI Agent (continueOnFail on tool nodes)
495
+ → IF (tool error occurred)
496
+ └─ Code (log error)
497
+ └─ Webhook Response (user-friendly error)
498
+ ```
499
+
500
+ ### Pattern 2: LLM API Errors
501
+ ```
502
+ Main Workflow:
503
+ AI Agent → Process Response
504
+
505
+ Error Workflow:
506
+ Error Trigger
507
+ → IF (rate limit error)
508
+ └─ Wait → Retry
509
+ → ELSE
510
+ └─ Notify Admin
511
+ ```
512
+
513
+ ### Pattern 3: Invalid Tool Outputs
514
+ ```javascript
515
+ // Code node - validate tool output
516
+ const result = $input.first().json;
517
+
518
+ if (!result || !result.data) {
519
+ throw new Error('Tool returned invalid data');
520
+ }
521
+
522
+ return [{ json: result }];
523
+ ```
524
+
525
+ ---
526
+
527
+ ## Performance Optimization
528
+
529
+ ### 1. Choose Right Model
530
+ ```
531
+ Fast & cheap: GPT-3.5-turbo, Claude 3 Haiku
532
+ Balanced: GPT-4, Claude 3 Sonnet
533
+ Powerful: GPT-4-turbo, Claude 3 Opus
534
+ ```
535
+
536
+ ### 2. Limit Context Window
537
+ ```javascript
538
+ {
539
+ memoryType: "windowBufferMemory",
540
+ contextWindowLength: 5 // Only last 5 messages
541
+ }
542
+ ```
543
+
544
+ ### 3. Optimize Tool Descriptions
545
+ ```javascript
546
+ // ❌ Vague
547
+ description: "Search for things"
548
+
549
+ // ✅ Clear and concise
550
+ description: "Search GitHub issues by keyword and repository. Returns top 5 matching issues with titles and URLs."
551
+ ```
552
+
553
+ ### 4. Cache Embeddings
554
+ For document Q&A, embed documents once:
555
+
556
+ ```
557
+ Setup (run once):
558
+ Documents → Embed → Store in Vector DB
559
+
560
+ Query (fast):
561
+ Question → Search Vector DB → AI Agent
562
+ ```
563
+
564
+ ### 5. Async Tools for Slow Operations
565
+ ```
566
+ AI Agent → [Queue slow tool request]
567
+ → Return immediate response
568
+ → [Background: Execute tool + notify when done]
569
+ ```
570
+
571
+ ---
572
+
573
+ ## Security Considerations
574
+
575
+ ### 1. Read-Only Database Tools
576
+ ```sql
577
+ -- Create limited user for AI tools
578
+ CREATE USER ai_agent_ro WITH PASSWORD 'secure';
579
+ GRANT SELECT ON public.* TO ai_agent_ro;
580
+ -- NO write access!
581
+ ```
582
+
583
+ ### 2. Validate Tool Inputs
584
+ ```javascript
585
+ // Code node - validate before execution
586
+ const query = $json.query;
587
+
588
+ if (query.toLowerCase().includes('drop ') ||
589
+ query.toLowerCase().includes('delete ') ||
590
+ query.toLowerCase().includes('update ')) {
591
+ throw new Error('Invalid query - write operations not allowed');
592
+ }
593
+ ```
594
+
595
+ ### 3. Rate Limiting
596
+ ```
597
+ Webhook → IF (check user rate limit)
598
+ ├─ [Within limit] → AI Agent
599
+ └─ [Exceeded] → Error (429 Too Many Requests)
600
+ ```
601
+
602
+ ### 4. Sanitize User Input
603
+ ```javascript
604
+ // Code node
605
+ const userInput = $json.body.message
606
+ .trim()
607
+ .substring(0, 1000); // Max 1000 chars
608
+
609
+ return [{ json: { sanitized: userInput } }];
610
+ ```
611
+
612
+ ### 5. Monitor Tool Usage
613
+ ```
614
+ AI Agent → Log Tool Calls
615
+ → IF (suspicious pattern)
616
+ └─ Alert Admin + Pause Agent
617
+ ```
618
+
619
+ ---
620
+
621
+ ## Testing AI Agents
622
+
623
+ ### 1. Start with Manual Trigger
624
+ Replace webhook with manual trigger:
625
+ ```
626
+ Manual Trigger
627
+ → Set (mock user input)
628
+ → AI Agent
629
+ → Code (log output)
630
+ ```
631
+
632
+ ### 2. Test Tools Independently
633
+ Before connecting to agent:
634
+ ```
635
+ Manual Trigger → Tool Node → Verify output format
636
+ ```
637
+
638
+ ### 3. Test with Standard Questions
639
+ Create test suite:
640
+ ```
641
+ 1. "Hello" - Test basic response
642
+ 2. "Search for bug reports" - Test tool calling
643
+ 3. "What did I ask before?" - Test memory
644
+ 4. Invalid input - Test error handling
645
+ ```
646
+
647
+ ### 4. Monitor Token Usage
648
+ ```javascript
649
+ // Code node - log token usage
650
+ console.log('Input tokens:', $node['AI Agent'].json.usage.input_tokens);
651
+ console.log('Output tokens:', $node['AI Agent'].json.usage.output_tokens);
652
+ ```
653
+
654
+ ### 5. Test Edge Cases
655
+ - Empty input
656
+ - Very long input
657
+ - Tool returns no results
658
+ - Tool returns error
659
+ - Multiple tool calls in sequence
660
+
661
+ ---
662
+
663
+ ## Common Gotchas
664
+
665
+ ### 1. ❌ Wrong: Connecting tools to main port
666
+ ```
667
+ HTTP Request → AI Agent // Won't work as tool!
668
+ ```
669
+
670
+ ### ✅ Correct: Use ai_tool connection type
671
+ ```
672
+ HTTP Request --[ai_tool]--> AI Agent
673
+ ```
674
+
675
+ ### 2. ❌ Wrong: Vague tool descriptions
676
+ ```
677
+ description: "Get data" // AI won't know when to use this
678
+ ```
679
+
680
+ ### ✅ Correct: Specific descriptions
681
+ ```
682
+ description: "Query customer orders by email address. Returns order ID, status, and shipping info."
683
+ ```
684
+
685
+ ### 3. ❌ Wrong: No memory for conversations
686
+ ```
687
+ Every message is standalone - no context!
688
+ ```
689
+
690
+ ### ✅ Correct: Add memory
691
+ ```
692
+ Window Buffer Memory --[ai_memory]--> AI Agent
693
+ ```
694
+
695
+ ### 4. ❌ Wrong: Giving AI write access
696
+ ```
697
+ Postgres (full access) as tool // AI could DELETE data!
698
+ ```
699
+
700
+ ### ✅ Correct: Read-only access
701
+ ```
702
+ Postgres (read-only user) as tool // Safe
703
+ ```
704
+
705
+ ### 5. ❌ Wrong: Unbounded tool responses
706
+ ```
707
+ Tool returns 10MB of data → exceeds token limit
708
+ ```
709
+
710
+ ### ✅ Correct: Limit tool output
711
+ ```javascript
712
+ {
713
+ query: "SELECT * FROM table LIMIT 10" // Only 10 rows
714
+ }
715
+ ```
716
+
717
+ ---
718
+
719
+ ## Real Template Examples
720
+
721
+ From n8n template library (234 AI templates):
722
+
723
+ **Simple Chatbot**:
724
+ ```
725
+ Webhook → AI Agent (GPT-4 + Memory) → Webhook Response
726
+ ```
727
+
728
+ **Document Q&A**:
729
+ ```
730
+ Setup: Files → Embed → Vector Store
731
+ Query: Webhook → AI Agent (GPT-4 + Vector Store Tool) → Response
732
+ ```
733
+
734
+ **SQL Analyst**:
735
+ ```
736
+ Webhook → AI Agent (GPT-4 + Postgres Tool) → Format → Response
737
+ ```
738
+
739
+ Browse the n8n template library (n8n.io/workflows) for more examples!
740
+
741
+ ---
742
+
743
+ ## Checklist for AI Agent Workflows
744
+
745
+ ### Planning
746
+ - [ ] Define agent purpose and capabilities
747
+ - [ ] List required tools (APIs, databases, etc.)
748
+ - [ ] Design conversation flow
749
+ - [ ] Plan memory strategy (per-user, per-session)
750
+ - [ ] Consider token costs
751
+
752
+ ### Implementation
753
+ - [ ] Choose appropriate LLM model
754
+ - [ ] Write clear system prompt
755
+ - [ ] Connect tools via ai_tool ports (NOT main)
756
+ - [ ] Add tool descriptions
757
+ - [ ] Configure memory (Window Buffer recommended)
758
+ - [ ] Test each tool independently
759
+
760
+ ### Security
761
+ - [ ] Use read-only database access for tools
762
+ - [ ] Validate tool inputs
763
+ - [ ] Sanitize user inputs
764
+ - [ ] Add rate limiting
765
+ - [ ] Monitor for abuse
766
+
767
+ ### Testing
768
+ - [ ] Test with diverse inputs
769
+ - [ ] Verify tool calling works
770
+ - [ ] Check memory persistence
771
+ - [ ] Test error scenarios
772
+ - [ ] Monitor token usage and costs
773
+
774
+ ### Deployment
775
+ - [ ] Add error handling
776
+ - [ ] Set up logging
777
+ - [ ] Monitor performance
778
+ - [ ] Set cost alerts
779
+ - [ ] Document agent capabilities
780
+
781
+ ---
782
+
783
+ ## Summary
784
+
785
+ **Key Points**:
786
+ 1. **8 AI connection types** - Use ai_tool for tools, ai_memory for context
787
+ 2. **ANY node can be a tool** - Connect to ai_tool port
788
+ 3. **Memory is essential** for conversations (Window Buffer recommended)
789
+ 4. **Tool descriptions matter** - AI uses them to decide when to call tools
790
+ 5. **Security first** - Read-only database access, validate inputs
791
+
792
+ **Pattern**: Trigger → AI Agent (Model + Tools + Memory) → Output
793
+
794
+ **Related**:
795
+ - [webhook_processing.md](webhook_processing.md) - Receiving chat messages
796
+ - [http_api_integration.md](http_api_integration.md) - Tools that call APIs
797
+ - [database_operations.md](database_operations.md) - Database tools for agents