What is the difference between function and tool calling?
| Mechanism | Purpose |
|---|---|
| Function Calling | Propose a function invocation |
| Tool Calling | Use different capabilities |
| Structured Outputs | Schema-conforming data |
| MCP | Tool integration |
In practice, function calling supplies a model with a function contract and receives a proposed invocation. Tool calling is often synonymous, but can include provider-hosted capabilities such as search and computation. Your application executes custom functions; some tools run in the provider's environment. Do not assume every model supports every tool type. [1][2][3][4]
Structured outputs produce data matching a format, such as a ticket classification. Valid JSON does not itself execute an API. RAG provides knowledge context, potentially retrieved through a tool. MCP defines how capabilities are exposed, not how a model reasons. If rules are deterministic, ordinary backend code may be a better fit than an LLM. [5][6]
How does a tool call work?
The application authenticates the user, selects available tools and sends their contracts with the request. The model may return a final response or one or more calls. An adapter extracts identifiers, names and arguments; the executor validates and authorizes them, invokes a service and returns bounded results. Each result must be correlated to its request and supplied in the API's required format. The model may then request another action. [1][2][3][4]
For example, asking about order X1 may produce get_order_status with orderId X1. The server reads only within the authenticated identity's scope. With shipped, the model can report shipment; with NOT_FOUND it must not invent a status or reveal whether another person's order exists. Never execute incomplete streamed arguments: wait for the appropriate completion event and validate the full object.
Follow a complete round trip: the model proposes get_order_status with arguments {"orderId":"X1"} and identifier c1. The application checks the session and arguments, then returns {"ok":true,"status":"shipped"} correlated with c1. Only after receiving the result does the model formulate its answer. If the order identifier is missing, ask for it rather than guessing. When the tool returns NOT_FOUND, do not reveal whether the order belongs to someone else. This is a provider-neutral example, not an API request envelope.
Designing function contracts
{
"name": "get_order_status",
"description": "Read the status of an order visible to the authenticated user.",
"parameters": {
"type": "object",
"properties": {
"orderId": {
"type": "string",
"description": "Order identifier, 1 to 32 uppercase ASCII letters or digits.",
"pattern": "^[A-Z0-9]{1,32}$"
}
},
"required": [
"orderId"
],
"additionalProperties": false
}
}
Name each tool after a single business operation. Describe its purpose, when it applies and its limits, and define types and required fields in its schema. Avoid general-purpose arbitrary SQL or HTTP execution. Use an allowlist, bounded outputs, clear error codes and versioned contracts. Never make secrets or tenant identity arguments generated by the model.
Automatic, required and named-tool modes and strict schema support vary by API and model. Forcing a tool does not guarantee a correct business decision. Providers support different JSON Schema subsets; check compatibility before sending declarations. Even with constrained generation, validate values, access and current state on the server. The following neutral contract is not a complete request envelope for any provider. [1][3][4]
The contract below also defines the identifier pattern to match the TypeScript validator. Not every API or model supports the pattern keyword. An adapter must handle incompatibility explicitly, for example by using a supported schema subset for the model while retaining full server-side validation. In OpenAI, strict: true requires, among other constraints, additionalProperties: false and all object properties listed in required; do not assume other providers impose identical rules. [1][3][4]
TypeScript example: reading an order safely
export interface Principal {
tenantId: string;
userId: string;
}
export type OrderStatus = "pending" | "shipped" | "delivered";
export interface OrderRepository {
findVisibleStatus(
principal: Principal,
orderId: string,
): Promise<OrderStatus | null>;
}
type ToolResult =
| { ok: true; status: OrderStatus }
| { ok: false; code: "INVALID_CALL" | "NOT_FOUND" | "UNAVAILABLE" };
interface OrderArguments {
orderId: string;
}
function isOrderArguments(value: unknown): value is OrderArguments {
if (typeof value !== "object" || value === null || Array.isArray(value)) {
return false;
}
const hasOnlyOrderId =
Object.keys(value).length === 1 && Object.hasOwn(value, "orderId");
if (!hasOnlyOrderId) {
return false;
}
if (!("orderId" in value)) {
return false;
}
const { orderId } = value;
if (typeof orderId !== "string") {
return false;
}
return /^[A-Z0-9]{1,32}$/.test(orderId);
}
export async function executeTool(
name: string,
args: unknown,
principal: Principal,
repository: OrderRepository,
): Promise<ToolResult> {
if (name !== "get_order_status") {
return { ok: false, code: "INVALID_CALL" };
}
if (!isOrderArguments(args)) {
return { ok: false, code: "INVALID_CALL" };
}
try {
const status = await repository.findVisibleStatus(principal, args.orderId);
if (status === null) {
return { ok: false, code: "NOT_FOUND" };
}
return { ok: true, status };
} catch {
return { ok: false, code: "UNAVAILABLE" };
}
}
The executor below accepts normalized arguments as unknown, not as a trusted interface. The adapter first decodes JSON and rejects parsing errors. The validator rejects extra fields, incorrect types and out-of-domain identifiers. User and tenant identity come from the authenticated session, never the model response.
The repository must enforce visibility in its database query, considering tenant, user and applicable roles. Missing and unauthorized records share the public NOT_FOUND code. The example does not implement a database, authentication, quotas or retries; these belong to application infrastructure. Record internal errors without secrets in a separate layer. Test the executor with the real repository as well.
The TypeScript example assumes ES2022 or newer (Object.hasOwn) and JSON-decoded arguments. The repository or its diagnostic wrapper should record failures before propagating exceptions to the executor; UNAVAILABLE must not be the only trace of a failure. Test valid identifiers of lengths 1 and 32, rejection of empty, oversized, lowercase or non-ASCII identifiers, extra fields and inherited properties, and denial of access to another user’s records. Tests with a simulated repository do not replace integration tests of actual database queries.
OpenAI, Anthropic and Google Gemini API differences
| API | Call | Result |
|---|---|---|
| OpenAI Responses | function_call | function_call_output |
| OpenAI Chat Completions | tool_calls | tool (tool_call_id) |
| Claude Messages | tool_use | tool_result (tool_use_id) |
| Gemini GenerateContent | functionCall | functionResponse |
| Gemini Interactions | function_call | function_result |
OpenAI Responses API declares custom functions in tools; function_call carries call_id and the result is function_call_output. Chat Completions instead uses tool_calls and a tool message with tool_call_id. Claude Messages API returns tool_use with an identifier and input object; tool_result in the subsequent user message references tool_use_id. These are distinct formats. [1][2][3][11]
Gemini exposes multiple API surfaces: GenerateContent uses functionCall and functionResponse parts, while Interactions API uses function_call and function_result steps. Preserve history, identifiers and required provider metadata, including reasoning signatures where documented. An adapter can normalize proposals to callId, name and args while retaining the original response for continuation. Check parallel and streaming support for the selected model. [1][2][4][10]
When manually managing Responses API history, retain returned reasoning items where required by the selected model. With Claude, return a tool_result for each pending call in the next user message; mark execution errors with is_error: true. In Gemini Interactions, correlate function_result with the function_call step id using call_id. Do not reconstruct or modify required metadata. Incomplete responses, refusals and transport errors are not valid function calls. [1][4][11]
Execution loops, concurrency and retries
The orchestrator should distinguish final responses, calls, refusals, errors and cancellation. Cap iterations, calls, elapsed time and total task cost. Independent reads may run concurrently; dependent operations and writes require explicit ordering. Return all required results with correct correlation. A list of proposed calls does not establish independence.
Retry only operations whose semantics allow it, with a bounded attempt count. For writes distinguish success, rejection and unknown outcome after timeout. A model call identifier is not necessarily a business idempotency key. Persist a key bound to identity, action and parameters; ensure atomicity or reconcile with the destination system. After a lost response check status before retrying. [8]
Distinguish message deduplication from business-operation idempotency. Two different model call identifiers may represent the same approved refund. Persist a key based on the approved operation identifier; reject reuse of that key with changed parameters. Reserve budgets atomically before expensive operations. After cancellation, do not treat a write with an unknown outcome as rolled back; reconcile its status before deciding what to do next. [8]
Security, approval and MCP
Valid arguments do not grant access. Authorize every call outside the model and scope tools and credentials to the user. For a refund, the server calculates the amount, verifies the order and limit, and an authorized person approves exact parameters. Recheck approval and current permissions immediately before execution. Tool results may include untrusted instructions; do not let them change policy. [8]
MCP supports discovery and invocation of server-exposed tools. It does not replace authorization, consent or the model loop. Verify server provenance, contract changes and token scopes. Reject tokens meant for other resources; restrict outbound connections and redirects. Treat results as data and read-only annotations as hints rather than security guarantees. [6][7][8]
For more on tool integration, see the POLPROG MCP guide. [12]
Cost, testing and production readiness
Task cost includes all model calls, schemas, tool results, retries and external services. Illustrative calculation: 10,000 tasks with two model calls each, each using 2,000 input and 250 output tokens, yield 40 million input and 5 million output tokens. At USD 1 and USD 4 per million respectively, model cost is USD 60. Another 10,000 service calls at USD 0.002 add USD 20, for USD 80 total. These are not provider prices. Measure cost per successful task, bound results and expose only relevant contracts.
Unit-test validation; integration-test authorization, correlation and idempotency. End-to-end tests should cover missing arguments, no-tool tasks, wrong tools, multiple calls, latency and untrusted results. Measure correct tool selection, argument accuracy, task success, unauthorized effects and cost per success. Require zero unauthorized effects in the test suite, not a claim of absolute security. Record model and contract versions, authorization decisions and operation outcomes without full customer data. [9]
Related POLPROG guides: Harness Engineering and LLM application security. [13][14]
