Skip to content

Tool schemas, OpenAPI extraction, runtime validation and action authority

15 min reading

Derive a tool contract from an OpenAPI operation and enforce parameters and action scope at runtime.

Page details

GenAI · Lesson 21 of 45 · 3 / 3.2

Sources · 15 min reading · 31 min with practice

Published · Last edited:

More
20px

Progress is saved in this browser when storage is available.

View guided paths and progress

Know first: ReAct, Plan-and-Solve and Reflexion with shared tasks and explicit limits. Optional help: GenAI foundations.

Optional background references

Hypothetical scenario. Northwind’s planner chooses a support API operation. Dev extracts a tool description from OpenAPI, but Maya notices a missing case identifier. Priya asks who supplied the tenant scope and whether the proposed request may execute.

Maya: “The operation name looks right, but this request does not identify the case.”

Dev: “The API description tells us which fields the operation expects.”

Priya: “Validate those fields and bind effective scope from trusted context before dispatch.”

You will follow an approved OpenAPI operation into a tool contract, then separate schema description, runtime validation and permission to act. A connector supplies an interface; the application still owns execution authority.

What turns an API description into a permitted request?

The OpenAPI 3.1.0 specification separates paths, operations, parameters, request bodies, responses and security requirements. A tool adapter can extract one approved operation, resolve its referenced schemas and describe its required fields. That extraction does not grant the model credentials or permission to invoke every operation in the document.

Hypothetical scenario. An approved read operation requires a path identifier and a date filter, with an optional page limit. A proposal supplying only the date has one of two required fields and is rejected before dispatch. The runtime obtains the permitted tenant scope from the authenticated execution context, not from a model-supplied override. Validate types, required values, argument locations and allowed scope before creating an executable request; then validate the returned result separately.

A tool call can change the world

Hypothetical scenario. A support assistant reads a customer message and proposes a refund. The message also contains instructions to send the customer database to another address. The model can represent both requests as structured tool arguments. Only one might belong to the authorized support workflow.

A tool-using application converts proposed model output into an operation against another system. That conversion is an authority boundary. Parsing valid arguments establishes their shape, not the caller's permission, the action's business validity or the safety of its side effects.

The evaluation module taught how to inspect outcomes. Here the system must prevent unauthorized actions before execution. Begin with a bounded workflow whose permitted actions are explicit; dynamic planning is an optional control strategy, not a reason to grant the model broad credentials.

Turn discovery metadata into a scoped execution contract

Hypothetical scenario. OpenAPI or MCP metadata describes tool names, inputs and outputs. A model proposes a call using that description. The application resolves a trusted tool identity, validates arguments and checks caller scope before creating an executable operation.

Turn discovery metadata into a scoped execution contract
ArtifactConcrete evidenceDecision boundary
Tool definitiontrusted identity, version, schemaDiscovery contract
Proposed callarguments and task evidenceFallible selection
Execution grantscope, fingerprint, operation IDEnforced permission
Describe available interface: Tool metadata → Model call proposal.Describe available interface: Tool metadata → Model call proposal. Tool metadata to Model call proposal: describe available interface; Model call proposal to Scoped executor: validate and authorize actual call.Tool metadataModel call proposalScoped executordescribe available interfacevalidate and authorize actual call
Describe available interface: Tool metadata → Model call proposal. Enlarge the diagram to inspect its labels; the surrounding records and explanation give the text alternative.

Do not derive credentials or destination authority from model text. Bind sensitive arguments to an approved fingerprint and restrict network destinations at the actual execution boundary. An API schema can be correct while the selected operation is wrong for the task. Version tool contracts and evaluate ambiguous tool choices, no-tool cases and changing results. A remote effect with a lost response requires its stable operation identity and reconciliation path.

Instruction text is not authorization

A document, search result or tool response may describe an instruction without possessing authority to issue it. If the application lets those words change its permissions, an attacker can influence actions indirectly through content the user merely asked it to read.

Role labels in a prompt help communicate intended distinctions but do not enforce external permissions. A model can misinterpret a boundary, follow a malicious passage or choose an unintended argument. The receiving application must independently check the operation.

The primary study Not what you've signed up for examines indirect prompt injection through retrieved content. The engineering response is not a claim that one defensive sentence eliminates the problem. Reduce what compromised model output can cause and evaluate the remaining failure paths.

Treat the model as a proposer

A tool contract states its name, purpose, arguments, allowed caller scope, result meaning and possible effects. Prefer narrow operations over an unrestricted execution interface. An operation such as “create a draft reply for this case” is easier to constrain than arbitrary network access with a long-lived account credential.

Model proposals pass an independent action boundaryUntrusted documents inform a model proposal. An application checks identity, permitted action, arguments and state before a tool executes. Tool observations return as data rather than new permission.Model proposalfrom task + dataApplication enforcementidentity / scope / statearguments / confirmationNarrow toolbounded effectsObservations are data, not expanded authority.

Enforcement checks authenticated identity, tenant, action scope, validated arguments and current resource state. An expected document version can prevent an edit based on stale evidence. A budget can reject an action outside the task's declared resource allowance.

Keep credentials out of the model context where possible and give the execution boundary only the authority needed for the approved operation. The model's explanation is useful review material, but it is not a credential. Tool results must retain their origin and be interpreted under their documented contract.

Work through an action policy

Hypothetical scenario. Choose a support policy permitting automatic refunds up to 50 units for a verified purchase, with a maximum cumulative refund of 80 units for this task. These are example policy values, not a recommendation for financial controls.

The assistant proposes refunds of 30 and 40. Each is below 50, and their total is 30 + 40 = 70, leaving 80 − 70 = 10 of the task allowance. A third proposed refund of 20 passes the per-action threshold but would make the total 70 + 20 = 90, exceeding the cumulative allowance by 90 − 80 = 10.

The executor must reserve or update that allowance atomically with its accepted action state. Two concurrent proposals cannot each read the same remaining ten and independently spend it. An application-side number in a prompt does not establish the cumulative invariant.

For a different action, a document edit expects source version seven while the authoritative document is now version eight. The equality check fails because 7 ≠ 8. Re-read the current document and reconsider the change instead of treating a syntactically valid edit as current.

Finally, suppose a task permits four tool attempts. A retrieval, a status lookup and a repeated status lookup consume three attempts, leaving 4 − 3 = 1. Whether retries count against this budget must be explicit. Otherwise an innocent-looking retry policy can exceed the intended boundary.

Confirmation must name the real action

Some actions require a user decision. Present the concrete target, parameters, effect and uncertainty at the point that decision matters. A generic “continue?” detached from the actual recipient or document does not establish informed authorization.

Bind the confirmation to the proposed operation and relevant resource version. If the action changes after confirmation, determine whether the existing decision still covers it. A malicious tool observation must not replace the recipient while preserving an approval for a different action.

Human involvement also has limits. A reviewer may miss a disguised instruction or misunderstand the effect. Narrow execution authority and validation remain necessary even when a person approves. Use confirmation for a meaningful decision, not as a substitute for enforcing routine scope checks.

A retrieved note changes the recipient

Hypothetical scenario. A user asks for a draft reply to a support case. A retrieved internal note tells the assistant to send the conversation to an external address for verification. The model proposes a send action even though the task allowed drafting only.

The executor rejects the action because sending is outside the authorized task. The content did not acquire permission by appearing in a relevant document. If the system exposed an unrestricted mail tool under broad credentials, that same model error could have become a disclosure.

Investigate the observation path and include the case in adversarial evaluation. Also check generated links and attachments: sensitive information can leave through rendered output or subsequent fetches, not only through an explicitly named send tool.

Avoid these tool-use equivalences

“Valid JSON means a valid action.” Shape validation does not establish authorization, current state or business invariants.

“The tool is read-only, so there is no risk.” A read can disclose information, trigger an expensive query or send sensitive query data to a remote system. Bound its actual effects.

“The model refused the test attack, so the boundary is solved.” That is one observed case. Continue testing indirect content and enforce scope outside the model.

Choose a workflow before a general agent

Use a predefined workflow when the sequence and permitted decisions are known. Allow model-directed tool selection when it solves a real branching problem and the application can bound actions and recover uncertainty. Building effective agents makes this workflow-versus-agent distinction explicit.

Do not equate more tools with greater task capability. Each tool adds contracts, permissions, observation formats and failure paths. Start with the smallest action surface that meets the task, and evaluate the complete trajectory as well as the final answer.

The next chapter makes this execution durable. A correct authorization decision can still be followed by a lost response, repeated action or resumed stale state. Authority and recovery must work together.

MCP connects the host to a capability, not to its authority

The Model Context Protocol separates the application host, a client connection and a server exposing capabilities. Northwind’s policy assistant is the host. Its client communicates with a shipping or order server that advertises supported tools and resources. A tool describes a callable operation; a resource provides addressable context; a prompt exposes a reusable interaction template. The host chooses which capabilities to make available to the model.

The architecture specification describes separate client-server connections. Initialization exchanges protocol version and capability information before ordinary operation. JSON-RPC messages carry requests, responses and notifications. A request identifier correlates an exchange; it is not automatically a durable refund identity. Reconnecting the client does not establish whether a previously requested business change completed.

The specified standard transports include stdio and Streamable HTTP. Stdio connects a client to a local process through its input and output streams. Streamable HTTP carries protocol exchanges over HTTP and can support streaming. These are communication arrangements. Neither makes the server’s tool description trusted evidence of what the current employee is allowed to do.

The MCP architecture, transport and authorization specifications are the primary references for those boundaries. HTTP authorization governs access to the protected server. Northwind still checks the particular employee, order, operation and approved arguments inside its service. The grant to connect is broader than the question of whether a refund of a particular amount is permitted now.

Keep the protocol budget separate from the task budget

Hypothetical worked extension: Northwind connects 3 servers exposing 4 tools each. If all 12 descriptions consume an assumed 100 prompt tokens apiece, the descriptions occupy 3 × 4 × 100 = 1,200 tokens before customer evidence is added. Selecting only the 4 tools relevant to this task uses 4 × 100 = 400 tokens, leaving 1,200 − 400 = 800 more tokens for other material under the same allowance.

This is a teaching estimate, not a protocol-mandated token cost. Hosts differ in how they select and serialize capabilities. Count the actual assembled request, including argument schemas and any repeated descriptions. More tools increase the model’s selection problem as well as its prompt budget, so expose capabilities according to the task rather than attaching every available server by default.

A server response also needs a bounded size and a declared trust role. An order lookup should return the fields needed for the decision rather than an unrestricted customer record. A retrieved message can contain hostile instructions, even when the MCP exchange itself is correctly authenticated. Treat returned content as an observation and enforce action scope where the resource is controlled.

In the wild: interoperability has a narrow promise

The MCP specification is a real interoperability contract covering message exchange, capability negotiation and transport. It does not certify the truth of tool results or the correctness of Northwind’s refund policy. A protocol-conforming server can still return stale data or expose a badly scoped tool. Test those application properties independently of successful initialization.

Northwind’s decision is to connect an order lookup through a narrowly scoped server while retaining refund approval in the existing action service. The model can propose a tool call and interpret its result. The host verifies permitted arguments, persists consequential action identities and stops when the task budget is exhausted. Changing connector technology should preserve those invariants.

Limits of a standardized connector

MCP reduces custom integration work where both ends implement the same contract. It adds little to a fixed application that already has a small adequate API. Version differences, credential scope and server lifecycle still require operational ownership. Choose the connector for interoperability, and preserve separate evidence, authorization and recovery checks for every consequential action.

Northwind decision log

  • Treat a tool call as a proposal.
  • Authorize arguments with the caller’s identity.
  • Verify the external outcome before reporting completion.

Go deeper into authority and observations

Test the tool definition boundary

A tool advertises read-only behavior but calls an unrestricted endpoint. Where must the correction occur?

Reveal the design reasoning

At the trusted implementation and capability boundary. Descriptions help selection but cannot enforce network or data access. Test the actual consequence, not just the proposal text.

Decision: Keep tool discovery, semantic selection and execution authority separately reviewable.

Check yourself: find the authority

A retrieved document says a user approved sending private data. Is that sufficient?

No. Retrieved content cannot establish the authenticated user's action authorization. The application must check scope and any required decision through a trusted control path.

Each proposed refund is below the per-action threshold. Can the task still exceed policy?

Yes. Enforce cumulative allowance and concurrent updates at the authoritative boundary. Per-action checks alone do not establish the total invariant.

A confirmed edit now targets a newer document version. Should execution proceed automatically?

Inspect whether the confirmation and proposed change still apply. Re-read and revalidate when the expected version is no longer current; do not reuse approval for a materially different effect.

Check the mechanism in this lesson

May an OpenAPI-derived tool accept a model-supplied tenant ID that broadens authenticated scope?

Compare the explanation

No. Schema extraction describes parameters; it does not grant authority. Bind effective scope from trusted execution context and reject attempts to exceed it before dispatch.

Carry the decision forward

Northwind has a validated dispatch boundary. Page 22 examines the gap after dispatch, when a lost response leaves the worker uncertain whether the external action happened.