Technical
Claude Tool Use for ERP Tasks: Safe Read and Write Actions
How to give Claude function calling access to your ERP without giving it the keys: narrow tools, argument validation in code, approval gates for writes, and a log entry for every call. Includes a Python example against Odoo.
Kalvyai Engineering · · 6 min read

On this page
Tool use (often called function calling) lets Claude ask your code to run an action, such as "find this customer" or "create a draft quotation". The model never touches the ERP directly. It returns a structured request, your code decides whether to run it, and you send the result back.
That last part is where most of the safety work lives. This post covers how we structure tools for ERP work: separating reads from writes, validating every argument in code, limiting what the model can do, and logging every call. The example uses Python and Odoo's XML-RPC API, but the pattern carries over to ERPNext or Shopify.
How tool use works in one paragraph
You send Claude a list of tools, each with a name, a description and an input_schema (JSON Schema). If Claude decides a tool is needed, the response contains a tool_use content block with an id, the tool name and an input object, and stop_reason is tool_use. Your code runs the action and replies with a tool_result block that references the same tool_use_id. You repeat until Claude returns a normal answer. Claude only proposes calls; your code executes them.
Split tools into read and write
The first design decision is to treat read tools and write tools differently.
- Read tools (search customers, get order status, check stock) can usually run immediately. The worst case is that the model sees data the agent's ERP user is allowed to see.
- Write tools (create a quotation, update a price, post a payment) change business records. By default these should not execute when the model asks. They should create a pending request that a person approves.
Keep the two kinds of tools separate in code, so you cannot accidentally run a write without going through the approval path.
Define tools narrowly
A generic execute_odoo(model, method, args) tool is tempting because it is flexible. It is also the easiest way to let a model delete records or edit things you never intended. Define one tool per business action instead, with only the fields it needs.
{
"name": "create_draft_quotation",
"description": "Request a draft sales quotation for an existing customer. Does not confirm the order. A human must approve before it is created.",
"input_schema": {
"type": "object",
"properties": {
"partner_id": {"type": "integer", "description": "Customer ID from search_customers"},
"lines": {
"type": "array",
"items": {
"type": "object",
"properties": {
"product_id": {"type": "integer"},
"quantity": {"type": "number"}
},
"required": ["product_id", "quantity"]
}
},
"note": {"type": "string"}
},
"required": ["partner_id", "lines"]
}
}Good descriptions matter. Tell the model what the tool does, what it does not do, and where IDs should come from ("Customer ID from search_customers"). That reduces guessed IDs.
Validate arguments in code
The JSON Schema guides the model, but treat it as a hint, not a guarantee. Validate every input again in your own code before anything touches the ERP. We do this in two layers:
- Shape validation: types, required fields, ranges, string lengths, no unknown fields. Pydantic (Python) or Zod (TypeScript) handles this well.
- Business validation: does the customer exist, is the product sellable, is the quantity within a sensible limit for this agent. This needs ERP lookups.
When validation fails, do not raise an exception that kills the loop. Return a tool_result with is_error: true and a clear message. Claude can usually correct itself, for example by searching for the right product ID first.
Limit what the model may do
Validation stops bad arguments. Limits stop bad behaviour. Use several layers, because each one covers gaps in the others.
- A dedicated ERP user for the agent. Create a separate user with only the access rights the agent needs. If the agent should never touch accounting, that user should have no accounting rights. ERP access rules are your last line of defence.
- A tool allowlist per role. A support agent gets order lookup tools. A sales assistant also gets the quotation tool. Only send the tools for that role, and reject any call to a tool name not on the list.
- Approval for writes. Write tools put a request in a queue. A person reviews and approves, and only then does your code run the write.
- Hard limits in code. Maximum lines per quotation, maximum quantity, maximum records returned by a search. These are values you choose for your business; the example below uses placeholders.
- A turn limit and a spend cap. Stop the loop after a fixed number of tool rounds, and cap monthly model spend so a runaway loop cannot surprise you.
Log every call
Every tool call should produce one log record, whether it succeeded, failed validation or was queued. At minimum, record:
- run ID and timestamp
- role and ERP user the agent acted as
- tool name and raw input from the model
- validation result and error text, if any
- outcome: executed, queued for approval, rejected
- approval ID and approver, for writes
- duration
In production we write this to a database table, not a file. A simple shape:
CREATE TABLE agent_tool_log (
id bigserial PRIMARY KEY,
run_id uuid NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
role text NOT NULL,
tool_name text NOT NULL,
tool_input jsonb NOT NULL,
status text NOT NULL, -- executed | queued | rejected | error
error text,
approval_id text,
duration_ms integer
);Log the raw input before validation. When something goes wrong, you want to see exactly what the model asked for, not the cleaned-up version.
A working Python example
This example connects to Odoo over XML-RPC, exposes two read tools and one write tool, validates with Pydantic, queues writes for approval and logs to a JSON Lines file to keep it short.
import json, os, time, uuid, xmlrpc.client
from datetime import datetime, timezone
import anthropic
from pydantic import BaseModel, ConfigDict, Field, ValidationError
# --- ERP connection (dedicated agent user with limited rights) ---
ODOO_URL = os.environ["ODOO_URL"]
ODOO_DB = os.environ["ODOO_DB"]
ODOO_UID = int(os.environ["ODOO_UID"])
ODOO_KEY = os.environ["ODOO_API_KEY"]
_models = xmlrpc.client.ServerProxy(f"{ODOO_URL}/xmlrpc/2/object")
def odoo(model, method, args, kwargs=None):
return _models.execute_kw(ODOO_DB, ODOO_UID, ODOO_KEY, model, method, args, kwargs or {})
# --- Hard limits (set your own values) ---
MAX_LINES = 20
MAX_QTY = 500
MAX_TURNS = 8
# --- Argument models ---
class SearchCustomers(BaseModel):
model_config = ConfigDict(extra="forbid")
query: str = Field(min_length=2, max_length=100)
limit: int = Field(default=10, ge=1, le=25)
class GetOrder(BaseModel):
model_config = ConfigDict(extra="forbid")
order_name: str = Field(min_length=1, max_length=64)
class Line(BaseModel):
model_config = ConfigDict(extra="forbid")
product_id: int = Field(gt=0)
quantity: float = Field(gt=0, le=MAX_QTY)
class DraftQuotation(BaseModel):
model_config = ConfigDict(extra="forbid")
partner_id: int = Field(gt=0)
lines: list[Line] = Field(min_length=1, max_length=MAX_LINES)
note: str | None = Field(default=None, max_length=500)
# --- Handlers ---
def search_customers(a: SearchCustomers):
return odoo("res.partner", "search_read",
[[["name", "ilike", a.query], ["customer_rank", ">", 0]]],
{"fields": ["id", "name", "email"], "limit": a.limit})
def get_order(a: GetOrder):
return odoo("sale.order", "search_read",
[[["name", "=", a.order_name]]],
{"fields": ["name", "state", "amount_total", "partner_id"], "limit": 1})
PENDING = {} # use a database table in production
def queue_quotation(a: DraftQuotation):
# Business validation before queueing
if not odoo("res.partner", "search_count", [[["id", "=", a.partner_id]]]):
raise ValueError(f"Customer {a.partner_id} does not exist")
ids = [l.product_id for l in a.lines]
ok = odoo("product.product", "search", [[["id", "in", ids], ["sale_ok", "=", True]]])
missing = set(ids) - set(ok)
if missing:
raise ValueError(f"Products not found or not sellable: {sorted(missing)}")
approval_id = str(uuid.uuid4())
PENDING[approval_id] = a
return {"status": "queued_for_approval", "approval_id": approval_id}
def approve(approval_id: str, approver: str):
a = PENDING.pop(approval_id)
order_id = odoo("sale.order", "create", [{
"partner_id": a.partner_id,
"note": a.note or "",
"order_line": [(0, 0, {"product_id": l.product_id, "product_uom_qty": l.quantity})
for l in a.lines],
}])
log("approval", "system", "create_draft_quotation", {"approval_id": approval_id},
"executed", approval_id=approval_id, approver=approver)
return order_id
REGISTRY = {
"search_customers": (SearchCustomers, search_customers),
"get_order": (GetOrder, get_order),
"create_draft_quotation": (DraftQuotation, queue_quotation),
}
ROLE_TOOLS = {
"support": {"search_customers", "get_order"},
"sales_assistant": {"search_customers", "get_order", "create_draft_quotation"},
}
def tool_spec(name, description):
model_cls, _ = REGISTRY[name]
return {"name": name, "description": description,
"input_schema": model_cls.model_json_schema()}
TOOLS = [
tool_spec("search_customers", "Search customers by name. Returns id, name, email."),
tool_spec("get_order", "Get status and total of a sales order by its reference, e.g. S00042."),
tool_spec("create_draft_quotation",
"Request a draft quotation for an existing customer. "
"Use IDs from search tools. A human must approve before it is created."),
]
# --- Logging ---
def log(run_id, role, tool, tool_input, status, error=None, **extra):
rec = {"run_id": run_id, "ts": datetime.now(timezone.utc).isoformat(),
"role": role, "tool": tool, "input": tool_input,
"status": status, "error": error, **extra}
with open("agent_tool_log.jsonl", "a") as f:
f.write(json.dumps(rec, default=str) + "\n")
# --- Execute one tool call ---
def execute(block, role, run_id):
start = time.monotonic()
def result(content, is_error=False, status="executed"):
log(run_id, role, block.name, block.input, status,
error=content if is_error else None,
duration_ms=int((time.monotonic() - start) * 1000))
return {"type": "tool_result", "tool_use_id": block.id,
"content": content if is_error else json.dumps(content, default=str),
"is_error": is_error}
if block.name not in ROLE_TOOLS[role]:
return result(f"Tool {block.name} is not allowed for this agent.", True, "rejected")
model_cls, handler = REGISTRY[block.name]
try:
args = model_cls.model_validate(block.input)
except ValidationError as e:
return result(f"Invalid arguments: {e.errors()}", True, "rejected")
try:
out = handler(args)
except ValueError as e:
return result(str(e), True, "rejected")
except Exception as e:
return result(f"ERP error: {type(e).__name__}", True, "error")
status = "queued" if isinstance(out, dict) and out.get("status") == "queued_for_approval" else "executed"
return result(out, status=status)
# --- Agent loop ---
client = anthropic.Anthropic()
MODEL = os.environ["CLAUDE_MODEL"] # e.g. claude-opus-5-5
SYSTEM = ("You help the sales team with Odoo. Only use the tools provided. "
"Never guess IDs; search first. Write actions are queued for human approval; "
"tell the user the approval ID.")
def run(task, role="sales_assistant"):
run_id = str(uuid.uuid4())
tools = [t for t in TOOLS if t["name"] in ROLE_TOOLS[role]]
messages = [{"role": "user", "content": task}]
for _ in range(MAX_TURNS):
resp = client.messages.create(model=MODEL, max_tokens=1024, system=SYSTEM,
tools=tools, messages=messages)
messages.append({"role": "assistant", "content": resp.content})
if resp.stop_reason != "tool_use":
return "".join(b.text for b in resp.content if b.type == "text")
results = [execute(b, role, run_id) for b in resp.content if b.type == "tool_use"]
messages.append({"role": "user", "content": results})
log(run_id, role, "-", {}, "error", error="turn limit reached")
return "Stopped: turn limit reached."A few points worth noticing:
- The tool schemas are generated from the Pydantic models, so the schema Claude sees and the validation your code runs come from the same source.
extra="forbid"rejects fields the model invents.- The role check happens in
execute, not only in the tool list. Filtering the list is the first gate; the check is the second. - ERP exceptions are returned as a short message. Do not send stack traces or connection details back to the model.
create_draft_quotationnever callscreate. Onlyapprove()does, and it is called by your UI or a reviewer, never by the model.
Running it
- Create a dedicated Odoo user for the agent with sales rights only, and generate an API key for it. (Open the user's Preferences, go to Account Security and click New API Key.)
- Set
ODOO_URL,ODOO_DB,ODOO_UID,ODOO_API_KEY,ANTHROPIC_API_KEYandCLAUDE_MODEL. - Install the dependencies:
pip install anthropic pydantic- Try a read-only task with the
supportrole first, then a quotation request withsales_assistant:
print(run("What is the status of order S00042?", role="support"))
print(run("Draft a quotation for Acme with 10 units of product 57."))- Check
agent_tool_log.jsonl. Every call should be there, including rejected ones.
Common mistakes
- One generic "run any method" tool. It bypasses every limit you write. Use one tool per action.
- Trusting the schema. Always validate in code, and validate business rules against live ERP data.
- Running the agent as an admin user. If your validation has a bug, admin rights turn it into a real incident.
- Logging only successes. Rejected and failed calls are the most useful records when you review agent behaviour.
- No turn or spend limit. A model that keeps retrying a failing tool can run many rounds if nothing stops it.
Other ways to connect Claude to your ERP
If you would rather not write and host the tool layer yourself, Model Context Protocol (MCP) is another route. Our Claude Connector | Odoo Remote MCP Server connects Anthropic Claude to Odoo using remote MCP and OAuth 2.1. The same principles still apply: give the connection a limited user and review what it can reach.
For spend control, AI Base plugs an AI model into Odoo with a hard monthly cap, and AI Base for ERPNext does the same for ERPNext.
How Kalvyai can help
We build AI agents that work inside Odoo, ERPNext and Shopify, with narrow tools, human approvals for writes, budgets and an audit trail of every call. If you want an agent that can read and act on your ERP without broad access, or you want a review of a tool-use setup you already have, contact us. You can also browse our ready-made apps at store.kalvyai.com.
- Claude
- Tool Use
- Function Calling
- Odoo
- ERP
- AI Agents
- Python
- Audit Trail
Kalvyai Engineering · Engineering team
The engineers who build, connect and fix business systems at Kalvyai: Odoo, ERPNext, Shopify and AI agents that work inside them with approvals, budgets and an audit trail.



Comments
No comments yet. Questions and corrections are welcome.
Rate this post or leave a comment