An AI agent that calculates with your Excel model
Your Excel workbook holds the prices, rates and rules of your business. This tutorial shows how an agent you build yourself gets a tool that calculates with that workbook, instead of estimating numbers.
First the shortcut, because you may not need any code:
- Claude or ChatGPT connect to a SpreadAPI service over MCP. You add an address and sign in. See Excel MCP server: a developer's guide.
- n8n has a verified SpreadAPI node that also works as a tool for n8n AI agents. See SpreadAPI is a verified n8n node.
The rest of this post is for the third case: your own agent, with function calling, against the REST API.
What was run, and what was not
Every JavaScript block below was run on 13 November 2026 with Node.js 22, without any package, against the public demo quote calculator of the SpreadAPI homepage. The outputs printed here are the ones we received. In the code, {serviceId} stands for the ID of the service.
One part was not run: the loop that talks to the language model. Model APIs differ from vendor to vendor, so that part is written as pseudocode and marked as such.
The service
The demo service prices a software quote. It has three inputs and five outputs:
licenses: a number from 1 to 10,000edition: one of Starter, Business, Enterprisediscount: a decimal from 0 to 0.5, so 0.05 for 5%- outputs:
unit_price,net_per_month,net_total,tax,total
Behind it is an Excel workbook with price lists and volume steps. A caller sees none of that, only inputs and outputs. How you turn your own workbook into such a service is described in Your first service.
Step 1: Build the tool definition from the OpenAPI document
A model needs a description of the function it may call: a name, a sentence about when to use it, and a JSON Schema of the arguments. You do not have to write that schema by hand. Every published service has an OpenAPI document, and the schema of its inputs is in there, with types, limits and allowed values.
// 1. Build the tool definition from the service's OpenAPI document
const BASE = 'https://spreadapi.io/api/v1/services/{serviceId}';
export async function loadTool() {
const response = await fetch(`${BASE}/openapi`);
if (!response.ok) throw new Error(`OpenAPI: HTTP ${response.status}`);
const doc = await response.json();
const post = Object.values(doc.paths)[0].post;
const body = post.requestBody.content['application/json'].schema;
return {
name: 'calculate_quote',
description: doc.info.description.split('\n')[0]
+ ' Call it for every number you report. Never estimate.',
parameters: body.properties.inputs // a JSON Schema object
};
}await loadTool() returned:
{
"name": "calculate_quote",
"description": "Prices a software quote: licenses, edition and discount give the unit price, net amounts, sales tax and the total for a 12-month term. Call it for every number you report. Never estimate.",
"parameters": {
"type": "object",
"description": "Input values by name. Names are not case-sensitive.",
"properties": {
"licenses": {
"type": "number",
"minimum": 1,
"maximum": 10000,
"description": "Number of licenses"
},
"edition": {
"type": "string",
"enum": ["Starter", "Business", "Enterprise"],
"description": "Edition"
},
"discount": {
"type": "number",
"minimum": 0,
"maximum": 0.5,
"description": "Send a decimal: 0.05 for 5%."
}
},
"required": ["licenses", "edition", "discount"]
}
}The limits and the allowed editions come from the parameter settings of the service. When the owner changes them and publishes again, your agent picks them up the next time it loads the document. The decimal hint on discount was added by SpreadAPI because the input is a percentage.
Pass this object to your model in the form its API expects. The three fields name, description and parameters are what the common function-calling interfaces ask for.
Step 2: Run a tool call
When the model decides to use the tool, it hands you arguments. Your code sends them to the service and gives the model an answer it can work with, also when the call fails.
// 2. Run one tool call and turn every outcome into an answer for the model
const BASE = 'https://spreadapi.io/api/v1/services/{serviceId}';
const TOKEN = process.env.SPREADAPI_TOKEN; // only for a protected service
export async function runTool(inputs) {
const headers = { 'Content-Type': 'application/json' };
if (TOKEN) headers.Authorization = `Bearer ${TOKEN}`;
let response;
try {
response = await fetch(`${BASE}/execute?flatten=true`, {
method: 'POST',
headers,
body: JSON.stringify({ inputs }),
signal: AbortSignal.timeout(30000)
});
} catch (error) {
return { ok: false, retry: true, error: `No answer: ${error.message}` };
}
const data = await response.json().catch(() => ({}));
if (response.status === 200) {
return { ok: true, result: data.result, usedInputs: data.inputs };
}
if (response.status === 429) {
// per-minute limit: Retry-After says how long to wait.
// "Monthly call limit reached": waiting does not help.
const wait = response.headers.get('Retry-After');
return { ok: false, retry: Boolean(wait), waitSeconds: Number(wait) || null,
error: data.error, message: data.message };
}
// 400: a refused input, or a token problem (also 400, by design).
// 404: wrong id or not published. 500: try again later.
return { ok: false, retry: response.status >= 500, status: response.status,
error: data.error, message: data.message, details: data.details };
}flatten=true adds result to the answer, one object with the output names as keys. inputs repeats the values as the workbook used them.
A valid call
await runTool({ licenses: 50, edition: 'Business', discount: 0.05 }) returned:
{
"ok": true,
"result": {
"unit_price": 41,
"net_per_month": 1998.14,
"net_total": 23977.68,
"tax": 1738.38,
"total": 25716.06
},
"usedInputs": [
{ "name": "licenses", "title": "Number of licenses", "value": 50 },
{ "name": "edition", "title": "Edition", "value": "Business" },
{ "name": "discount", "title": "Discount", "value": 0.05 }
]
}A value that is not allowed
await runTool({ licenses: 50, edition: 'Platinum', discount: 0.05 }) returned:
{
"ok": false,
"retry": false,
"status": 400,
"error": "Parameter validation failed",
"message": "1 parameter(s) failed validation",
"details": {
"errors": [
{
"parameter": "Edition",
"error": "Value \"Platinum\" is not allowed. Allowed values: Starter, Business, Enterprise",
"type": "invalid_enum_value",
"allowedValues": ["Starter", "Business", "Enterprise"],
"receivedValue": "Platinum",
"caseSensitive": false,
"name": "edition",
"title": "Edition"
}
]
}
}Give this to the model as the tool result. It says which input is wrong and what is allowed, so the model can ask the user or correct the call. It should not pick another edition on its own.
A missing input
await runTool({ licenses: 50, edition: 'Business' }) returned:
{
"ok": false,
"retry": false,
"status": 400,
"error": "Missing required parameters",
"message": "The following required parameters are missing: Discount",
"details": {
"required": [{ "name": "discount", "title": "Discount" }]
}
}The statuses the API returns
The three answers above are real. The demo service is public and we stayed far below its limits, so the following cases are taken from the help centre, not from a run:
- 200: the calculation worked. A formula error in an output cell, such as
#VALUE!, is also a 200; the error text is the value. - 400, input:
Missing required parametersorParameter validation failed, withdetails. - 400, token: a protected service answers token problems with 400 as well, by design, not with 401. The text in
errortells the cases apart:Authentication required. …,Invalid token,Token expired,Token does not belong to this service. Check the text, not only the status. - 404: the ID is wrong or the service is not published.
- 429, per minute: more than 1,000 calls per minute for the service. The answer has
error: "RATE_LIMIT_EXCEEDED"and aRetry-Afterheader in seconds. Wait, then send the same call again. - 429, per month:
Monthly call limit reached. Waiting does not help; tell the user. - 500: an error on the server. Try again later.
A call has up to 30 seconds to answer. The full list is in the error reference.
Step 3: Compare options in one request
"Business or Enterprise?" is one question, so make it one request. The discovery address of a service has a batch action for 2 to 20 scenarios, each with a label:
// 3. Compare several options in one request (2 to 20 scenarios)
const DISCOVERY = 'https://spreadapi.io/d/{serviceId}';
export async function runBatch(scenarios) {
const response = await fetch(DISCOVERY, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ action: 'batch', scenarios })
});
const data = await response.json();
if (!response.ok || !data.success) {
return { ok: false, status: response.status, error: data.error };
}
return {
ok: true,
scenarios: data.scenarios.map((s) => s.success
? { label: s.label,
...Object.fromEntries(s.outputs.map((o) => [o.name, o.value])) }
: { label: s.label, error: s.error })
};
}Called with two scenarios, the second with an edition that does not exist:
await runBatch([
{ label: 'Business',
inputs: { licenses: 50, edition: 'Business', discount: 0.05 } },
{ label: 'Platinum',
inputs: { licenses: 50, edition: 'Platinum', discount: 0.05 } }
]);it returned:
{
"ok": true,
"scenarios": [
{
"label": "Business",
"unit_price": 41,
"net_per_month": 1998.14,
"net_total": 23977.68,
"tax": 1738.38,
"total": 25716.06
},
{
"label": "Platinum",
"error": "Parameter validation failed: edition: Value \"Platinum\" is not allowed. Allowed values: Starter, Business, Enterprise"
}
]
}One failing scenario does not stop the others. Every calculated scenario counts as one call of the service. With two real editions, the same call returned a total of 25716.06 for Business and 47041.52 for Enterprise.
The same address, opened with GET, describes the service in JSON: inputs, outputs, a call that works as it stands, and a list of instructions for an AI. See The discovery address.
Step 4: The loop around the model
This part is pseudocode. It was not run, because it depends on the model API you use.
PSEUDOCODE, not run
tool = loadTool()
messages = [system prompt, user question]
repeat:
answer = model.respond(messages, tools = [tool])
if answer contains no tool call:
return answer.text
for each tool call in answer:
outcome = runTool(call.arguments)
if outcome.retry and outcome.waitSeconds:
wait outcome.waitSeconds, then runTool again, once
append to messages: tool result = outcome as JSON
stop after a fixed number of rounds, for example 5Three points decide whether this works well:
- Always return something. Also a failed call goes back to the model as a tool result. Then the model can tell the user what is allowed.
- Limit the rounds. A model that keeps calling with the same wrong value should run into your limit, not into your month's calls.
- Do not retry what cannot succeed. A refused input and the monthly limit do not get better by repeating.
What to tell the model
The discovery document of the demo service carries instructions written for an AI. These three are taken from it word for word and make a good start for your system prompt:
- "Every result is calculated by the owner's spreadsheet. Call the service for each number you report instead of working it out or estimating it yourself."
- "A call only calculates; it changes nothing and can be repeated."
- "If the user asks for a value an input does not allow, tell them what is allowed instead of picking another value for them."
Add what only you know: who the users are, which currency the numbers are in, and when the tool should not be used.
Things that go wrong in practice
- Percentages. The service expects 0.05 for 5%. A model that sends 5 is refused here because of the maximum of 0.5. On an input without a maximum it would calculate with 500%. Set limits on your inputs. See Input validation.
- Rounding in the answer. The API returns the raw number of the cell. Let your code format it, or tell the model how.
- The token. A token belongs on your server, in an environment variable. Do not put it into a prompt or into code that runs in a browser. See Tokens and access.
- Identical questions. SpreadAPI stores the result of identical inputs for up to 15 minutes. A stored result still counts as a call.
- Changes to the workbook. Callers get the published version until the owner publishes again. Load the OpenAPI document when your agent starts, not once at build time.
- What a service is not. VBA macros do not run, and an input is a single value, not a list.
Checklist before you go live
- The tool definition is built from the OpenAPI document of the published service
- Every input has sensible limits or allowed values
- Failed calls go back to the model as tool results
- 429 is handled: wait for
Retry-After, do not retry the monthly limit - The number of tool rounds per question is limited
- The token, if there is one, lives on the server
- You compared a few answers of the agent with the workbook