Loading...
Loading...
Write JavaScript or Python for the n8n Custom Code Tool (@n8n/n8n-nodes-langchain.toolCode) — the AI-agent-callable tool, NOT the workflow Code node. Use when building a Code Tool attached to an AI Agent, writing code that an LLM will invoke, parsing the `query` input, returning a string result, defining an input schema for structured arguments (specifyInputSchema, jsonSchemaExample, DynamicStructuredTool), or troubleshooting errors like "Wrong output type returned", "No execution data available", "The response property should be a string, but it is an object", "Cannot assign to read only property 'name'", or an AI agent that refuses to call the tool. Covers the critical differences between Code node and Code Tool: return format (string vs `[{json:{...}}]`), unavailability of `$fromAI`/`$input`/`$helpers` in the Code Tool sandbox, naming rules for AI invocation, and when to use `toolWorkflow`/HTTP Request Tool instead.
npx skill4agent add czlonkowski/n8n-skills n8n-code-tool@n8n/n8n-nodes-langchain.toolCode| Code node | Custom Code Tool | |
|---|---|---|
| Node type | | |
| Package | | |
| Invoked by | Previous node (workflow flow) | AI Agent (LangChain) |
| Input | | |
| Return | | A string |
| N/A | Not available (see Errors) |
| HTTP helper | | Not exposed to the tool sandbox |
| State | Per-run execution data | No |
// `query` is whatever the AI sent (a string by default)
return `You asked: ${query}`;# `_query` is whatever the AI sent (a string by default)
return f"You asked: {_query}""The response property should be a string, but it is an object"query_query$fromAI()"No execution data available"[{json: {...}}]"Wrong output type returned"specifyInputSchemaspecifyInputSchema: falsequery// Parse a JSON string the AI sent
let params;
try {
params = typeof query === 'string' ? JSON.parse(query) : query;
} catch (e) {
throw new Error('Expected a JSON object. Parser said: ' + e.message);
}
const price = Number(params.price);
const months = Number(params.months);
// ...
return JSON.stringify({ monthly_payment: /* ... */ });specifyInputSchema: trueDynamicStructuredToolquery// query is now an object matching your schema
const price = query.price;
const months = query.months;
const residual_percent = query.residual_percent;
const monthly = computeAnnuity(price, months, residual_percent);
return JSON.stringify({ monthly_payment: monthly });schemaType: "fromJson"jsonSchemaExampleschemaType: "manual"inputSchema// ✅ String
return "42";
// ✅ Number (auto-converted to string by n8n)
return 42;
// ✅ JSON-encoded structured result (recommended for rich output)
return JSON.stringify({ result: 42, currency: "SEK" });
// ❌ Raw object → "The response property should be a string, but it is an object"
return { result: 42 };
// ❌ Workflow item format → "Wrong output type returned"
return [{ json: { result: 42 } }];
// ❌ Array → "The response property should be a string, but it is an object"
return [1, 2, 3];return JSON.stringify({
monthly_payment_sek: 5405,
loan_amount: 351920,
total_cost_of_credit: 63295
});// Option A: throw — n8n surfaces the message to the agent
if (!isFinite(price)) throw new Error('price must be a number, e.g. 439900');
// Option B: return an error string — agent reads it like any tool result
if (!isFinite(price)) return JSON.stringify({ error: 'price must be a number, e.g. 439900' });throw new Error('invalid input')[A-Za-z0-9_]+calculate_car_loanget_weathersearch_ordersCode ToolDeterministiskt beräknar månadskostnad för billån. Anropa med EN JSON-sträng:
{"price":439900,"down_payment":87980,"interest_rate":6.95,"months":36,"residual_percent":50}
Fält: price (SEK), down_payment (SEK), interest_rate (% per år), months, residual_percent (0-99).Deterministically computes the monthly car-loan payment given price, down payment,
annual interest rate, term, and residual percent. Use whenever the user asks for
monthly cost, total credit cost, or loan breakdown."There was an error: 'Cannot assign to read only property \"name\" of object: Error: No execution data available'"$fromAI()$fromAI()toolWorkflowtoolCodequeryspecifyInputSchema"Wrong output type returned"[{ json: { ... } }]return JSON.stringify(output)"The response property should be a string, but it is an object"JSON.stringify()Code ToolMy Toolcalculate_car_loanqueryspecifyInputSchema: true| Helper | Code node | Code Tool |
|---|---|---|
| ✅ | ❌ |
| ✅ | ❌ |
| ✅ | ❌ |
| ❌ | ❌ (despite sitting next to an AI agent) |
| ✅ | ❌ |
| ✅ | ✅ (standard in JS sandbox) |
| ✅ | ❌ |
| ✅ | ❌ |
| ✅ | ❌ |
toolWorkflowtoolWorkflow$fromAI()this.helpers$fromAI()$fromAI()toolWorkflowtoolCode{
"parameters": {
"name": "calculate_car_loan",
"description": "Computes monthly car-loan payment using an annuity formula with residual/balloon. Call with a single JSON string. Example: {\"price\":439900,\"down_payment\":87980,\"interest_rate\":6.95,\"months\":36,\"residual_percent\":50,\"setup_fee\":695,\"monthly_admin_fee\":59}. Required: price, down_payment, interest_rate, months, residual_percent. Optional: setup_fee, monthly_admin_fee (default 0).",
"language": "javaScript",
"jsCode": "let params;\ntry {\n params = typeof query === 'string' ? JSON.parse(query) : query;\n} catch (e) {\n throw new Error('Invalid JSON: ' + e.message);\n}\n\nconst price = Number(params.price);\nconst down_payment = Number(params.down_payment);\nconst interest_rate = Number(params.interest_rate);\nconst months = Number(params.months);\nconst residual_percent= Number(params.residual_percent);\nconst setup_fee = Number(params.setup_fee ?? 0) || 0;\nconst monthly_admin_fee = Number(params.monthly_admin_fee ?? 0) || 0;\n\nif (!isFinite(price) || price <= 0) throw new Error('price must be > 0');\nif (down_payment < 0 || down_payment >= price) throw new Error('down_payment must be in [0, price)');\n\nconst principal = price - down_payment;\nconst residual = price * (residual_percent / 100);\nconst r = interest_rate / 100 / 12;\nconst growth = Math.pow(1 + r, months);\nconst base = r === 0\n ? (principal - residual) / months\n : (principal - residual / growth) * r / (1 - 1 / growth);\nconst monthly_payment = base + monthly_admin_fee;\n\nreturn JSON.stringify({\n monthly_payment_sek: Math.round(monthly_payment),\n loan_amount: Math.round(principal),\n residual_value_sek: Math.round(residual),\n total_cost_of_credit: Math.round(monthly_payment * months + residual + setup_fee - principal)\n});"
},
"type": "@n8n/n8n-nodes-langchain.toolCode",
"typeVersion": 1.3,
"name": "calculate_car_loan"
}ai_toolspecifyInputSchemaget_node({detail: "standard"})@n8n/n8n-nodes-langchain.toolCode@n8n/n8n-nodes-langchain.toolCodenodes-base.codecalculate_car_loanquery_query$fromAI()$input$json$helpersJSON.stringify()ai_tool