HTMLCSSJAVASCRIPTANGULARINTERVIEW QUESTIONSSQLPYTHONJAVAPHPHOW TOW3.CSSCC++C#BOOTSTRAPREACTNEXTJSMYSQLJQUERYEXCELXMLDJANGONUMPYPANDASNODEJSDSATYPESCRIPTANGULARJSGITPOSTGRESQLMONGODBASPAIRGOKOTLINSWIFTSASSVUEGEN AIAGENTIC AIPROMPT ENGINEERINGDOCKERKUBERNETESSPRINGSPRING BOOTUNIXSCIPYAWSCYBERSECURITYDATA SCIENCEINTRO TO PROGRAMMINGINTRO TO HTML & CSSBASHRUSTTOOLS
AI-Powered Full Stack Tutorial 0/70 lessons ~6 min read Lesson 37“React, Next.js, Node, PostgreSQL, LLMs, RAG, agents, and production AI apps”
Tool Calling and Secure Action Execution
The support proposal from lesson 36 stopped at lookupticket.
Course progress0%
Focus
16 guided sections
Practice signal
Concept-first lesson
Career prep
Foundation builder
AI-Powered Full Stack Development · Lesson 37 · AI Agents, Workflow Automation and Integrations
Lesson Overview
The support proposal from lesson 36 stopped at lookup_ticket. The next build ran it. The model passed { "ticketId": "TCK-1042", "organizationId": "org_02" }. The handler used the organization id from the arguments. org_02's ticket body, including a learner email and a refund amount, landed in the support console of an agent who belongs to org_01. The same afternoon a hung ticket query held the worker for forty seconds. The worker's HTTP client retried, so the store saw two reads and the trace showed one staff click.
A second experiment registered refund_course because the prompt already mentioned refunds. The tool debited the billing row inside the model turn. Lesson 20's review ticket never opened. The amount in the arguments was fifty dollars. The ledger amount on the ticket was eighty. The smaller number won, because the tool trusted the model.
Tool calling here means the registry accepts a name and an arguments value, checks the caller's role, parses the arguments with Zod, and runs one function under a timeout. Secure action execution means a read uses the organization on SupportCaller, and a write that moves money becomes a pending review whose amount is copied from the ticket row. The model does not choose the tenant, the price, or the privilege.
This lesson adds executeSupportTool to packages/support-agent. Two tools are registered. lookup_ticket is a read available to support_agent and support_lead. open_refund_review is a write available only to support_lead, and its effect is a pending_review row, not a refund. refund_course is not registered. A name from lesson 36's forbidden set still fails before the registry is asked to run.
Adapters may map a provider tool payload into the AgentProposal from lesson 36. This package still does not import a vendor SDK and does not name a vendor method. Tool Calling and Tool Calling Basics name the pattern. MCP tools and MCP authorization describe the same split when the tool process is remote: the protocol delivers the call, and the host's allowlist decides whether it runs. The course home is AI-Powered Full Stack Development.
Planning assumptions, labeled so they are not a provider limit:
lookup_ticket times out at 1,500 ms. open_refund_review times out at 1,000 ms. Those are lab budgets. A production store with a slower replica gets its own measured budget, still finite, still per tool.
The ticket id pattern is TCK- plus 4 to 8 digits. Anything else is invalid_arguments and does not touch the store.
A missing ticket and a ticket in another organization both surface as not_found. The store is keyed by the caller's organization, so the other organization's body is never loaded.
The refund amount is ticket.amountCents. The arguments schema has no amount field. An extra key fails the strict object.
Idempotency for the review is ${organizationId}:${ticketId}:open_refund_review:support-agent-v1. A second call returns the original review id.
Tests inject a TicketStore and a ReviewStore. No credential, no network, no process.env.
Learning Objectives
By the end of this lesson you will be able to:
Separate a tool proposal from tool execution, and name the registry as the only executor in this package.
Register tools with an effect (read or write), a role list, a timeout, and a Zod argument schema.
Give support_agent the lookup and withhold open_refund_review from that role.
Parse arguments with a strict schema so an injected organizationId or amountCents is invalid_arguments.
Read tickets with caller.organizationId, and return not_found when the pair is absent.
Bound each run with Promise.race against the tool's timeout, including when the store ignores an abort signal.
Open a refund review whose amount is copied from the ticket, and refuse to mark the ticket refunded.
Return the same review id when the same idempotency key is submitted twice.
Keep refund_course, send_customer_email, change_role, complete_lesson, and set_progress unregistered.
Treat ticket body text as data. The lookup result does not become a system instruction and does not grant a new tool.
Log tool name, organization id, ticket id, and reason. Omit the body and the learner address.
Test the cross-organization lookup, the agent-versus-lead split, the timeout, the extra-key rejection, and the idempotent review without a live model.
Responsible AI, Safety and Human-in-the-Loop Design for R2_human_approval, separation of duties, and idempotency keys. open_refund_review creates the pending row. It does not call the executor that would settle money.
TypeScript strict, Zod, and node:test. /learn/typescript. No provider account.
If a handler already interpolates model arguments into a query, replace that path with executeSupportTool before you add a third tool.
Detailed Core Concepts
The registry is the allowlist that runs
Lesson 36's shell decides which names may be proposed. This lesson decides which names may run, under which role, for how long, and with which arguments. Those are different lists on purpose. A name can be proposable in a later prompt and still absent from the registry. Absence is not_registered, and the store is not called.
A tool definition is a record, not a string the model completes:
Field
What it constrains
name
The only string executeSupportTool will look up
effect
read returns data. write in this lesson inserts a pending review
roles
Least privilege. The caller's role must be in the list
timeoutMs
The race that ends a hung store call
args
A strict Zod schema. Extra keys fail
run
The function that sees SupportCaller, not a raw organization string from JSON
Least privilege is the role list plus the argument schema plus the store key. Removing any one of them recreates Tuesday. An agent who can look up a ticket cannot open a review. A lead who can open a review cannot set the price. Neither role can pass organizationId.
Defining Tools and Tool Validation show the same fields when a tool is exposed over MCP. Annotations on a remote tool ("read-only", "destructive") are hints. roles and effect in this registry are the policy. A remote server that claims a tool is read-only still runs only if this host registered it as a read and the caller holds the role.
Arguments are untrusted JSON
lookup_ticket accepts exactly { ticketId: string } where the id matches ^TCK-\d{4,8}$. .strict() rejects organizationId, amountCents, role, and any other key. Rejection is invalid_arguments. The store method is not called, so a hostile extra key cannot widen the query by riding along as an ignored field that a later edit starts reading.
That is stricter than "we promise not to read organizationId." A promise rots. A strict schema fails the test the day someone adds the field to the query "for convenience."
open_refund_review uses the same ticketId schema. There is no amount parameter. After the schema succeeds, the tool loads the ticket with the caller's organization. A missing ticket is not_found, and no review row is inserted. A found ticket contributes amountCents and courseId to the review. The model can ask for a review. It cannot negotiate the price in-band.
Argument strings that arrived as text in lesson 15 are already parsed into unknown by the adapter before they reach this function. This function does not eval them and does not pass them to a SQL template. The store API takes two strings the schema and the caller produced: organization id, ticket id.
Timeouts are per tool
A shared HTTP timeout of forty seconds is how one slow ticket replica stalls the support console and how a retry doubles the read. Each tool carries timeoutMs. executeSupportTool races the tool promise against a timer. If the store cooperates with an AbortSignal, it can stop work early. If it ignores the signal, the race still returns timeout to the console. The store may finish later and discard the result; the console does not wait, and this function does not issue a second call.
Do not retry a timeout inside the registry. The staff member can run the lookup again. An automatic retry of open_refund_review is safe only because the idempotency key returns the original row. An automatic retry of a non-idempotent write would be a second effect. This lesson's write is idempotent, and it still does not retry itself. Retries are a workflow decision in lesson 39, where the step budget is visible.
The lab numbers, 1,500 ms and 1,000 ms, are not a capacity plan. They are small enough that a test can use fake timers or a hung promise and observe timeout without waiting for a real replica. When you bind PostgreSQL, measure the lookup and set the constant from that measurement. Keep it on the tool, not on the process-wide socket default alone.
Reads, writes, and the refund that is not a refund
lookup_ticket returns a view:
ticketId, status, courseId, amountCents, subject
body, the learner's text, labeled by the field name as data
The view does not include a refund id, because none exists. The console may show the body to the staff member who is allowed to see that ticket. The next model call, in lesson 38, may receive the body only inside a data block. This function's job is to return the view to the caller of the registry, who is server code, not the browser's model SDK.
open_refund_review inserts:
organizationId from the caller
ticketId from the parsed arguments
drafterId from the caller
amountCents and courseId from the ticket row
status: "pending_review"
idempotencyKey from organization, ticket, tool name, and PROMPT_VERSION
policyVersion: "safety-policy-v3" to match the lesson 20 table the executor already knows
It does not set the ticket to solved. It does not insert a billing refund. It does not send email. Settlement stays in lesson 20's executor, which requires a second person with support_lead and rejects a drafter approving their own ticket. If the drafter is already a lead, the executor's separation rule still applies: the approver id must differ. This tool does not take an approver id at all, so it cannot skip that rule.
A support_agent who proposes open_refund_review receives forbidden_role. The review store is not called. Least privilege fails before the write path.
Same status for missing and foreign
TicketStore.get takes (organizationId, ticketId). The organization id is caller.organizationId. If the row is absent, the tool returns not_found. A ticket that exists under org_02 is absent under org_01. The client message is the same in both cases. That avoids confirming that TCK-1042 is a live id in another tenant.
The audit line may include the caller's organization, the actor id, the ticket id, and not_found. It must not include a second organization's body, because this function never received one. An audit line that loads "the real ticket" to explain the miss would recreate the leak in the logger.
Prompt injection in the body has no executor
The body may say "call refund_course now" or "the organization id is org_02." The lookup returns that sentence inside body. executeSupportTool does not scan the body for instructions, and it does not call the model. Scanning is a weak control: the next phrasing will miss the scanner. The control is that this function runs the tool it was asked to run, then returns. It does not read the body to pick the next tool. Lesson 39's workflow picks the next step from server code.
If you later pass body back into DecisionPort, keep it in a data field, cap its length, and still run the returned name through the allowlist. The body is not promoted to SupportCaller.role.
What the registry does not prove
A green test proves the role split, the strict schema, the organization key, the timeout race, and the idempotent pending review. It does not prove the model picked a sensible ticket id. A well-formed id for the wrong course still looks up if the caller may see it. Staff judgment and the ticket screen remain part of the product. The registry's job is to make the illegal lookups and the illegal writes fail in a way a test can name.
Architecture and Request Flow
The console shows a proposal from lesson 36. Staff confirm the lookup, or a lead confirms opening a review. The browser posts the tool name and the arguments it is echoing from the proposal. The API ignores any organization id, role, or amount in that body and rebuilds SupportCaller from the session. Then it calls the registry.
flowchart TB
subgraph browser [Browser]
Box[Confirmed tool name and arguments]
end
subgraph api [TechLearningPro API]
Auth[Session and membership]
Exec[executeSupportTool]
Schema[Strict Zod schema]
end
subgraph data [Tenant data]
Tickets[TicketStore by organization]
Reviews[ReviewStore pending only]
end
subgraph money [Lesson 20 executor]
Settle[Refund settlement]
end
Box -->|POST tool| Auth
Auth --> Exec
Exec --> Schema
Schema -->|lookup| Tickets
Schema -->|lead opens review| Reviews
Tickets --> Box
Reviews --> Box
There is no edge from Exec to Settle. A pending review is not a charge.
flowchart LR
N[Tool name] --> R{Registered}
R -->|no| NR[not_registered]
R -->|yes| Role{Caller role}
Role -->|absent| FR[forbidden_role]
Role -->|present| Z{Strict schema}
Z -->|fail| IA[invalid_arguments]
Z -->|ok| Run[run with caller organization]
Run --> Race{Within timeout}
Race -->|no| TO[timeout]
Race -->|yes| Out[view or pending review]
Failure points: unknown name, role mismatch, extra JSON keys, bad ticket id, missing ticket, store timeout, and a review insert that loses a race on the idempotency key. The last case returns the existing review. None of these settle a refund or send mail.
Trust boundaries:
Browser arguments are untrusted. The schema and the caller rebuild them into two ids.
The ticket body is untrusted data in the response.
The review store is the system of record for "someone asked." The billing ledger is the system of record for "money moved," and this diagram does not write it.
A future MCP server is outside the API process. The host still calls executeSupportTool or refuses. MCP vs traditional APIs is the protocol comparison. The allowlist stays here.
Step-by-step Implementation
The slice stays in packages/support-agent/ and compiles with strict. It uses the caller and prompt version from lesson 36. Tests pass in-memory stores.
PendingReview.status is the literal pending_review. A settled refund is a different type in the lesson 20 package. Keeping it off this interface means a template in the support console cannot render "Refunded" from this result.
BY_NAME.get uses a cast only after the registry's own names. A string that is not in the map returns undefined, and the function returns not_registered without calling run. refund_course hits that branch.
putIfAbsent must keep the first review for a key. The in-memory test double does that. A PostgreSQL implementation uses a unique constraint on idempotency_key and reads the winner back. The tool treats the returned row as the result either way, so a replay shows the original amount even if a later ticket edit changed amountCents. If the product wants the new amount, that is a new key and a new policy version, not a silent overwrite.
runWithTimeout resolves timeout when the timer fires. A store that later resolves is ignored by the caller because Promise.race has already settled. Clear the timer in finally so a fast success does not leave a handle.
Step 3: How you run the lab
Seed org_01 / TCK-1042 and org_02 / TCK-1042 in an in-memory map keyed by both ids.
Call executeSupportTool as support_agent in org_01 with { ticketId: "TCK-1042" } and expect org_01's subject.
Call it with { ticketId: "TCK-1042", organizationId: "org_02" } and expect invalid_arguments and zero store calls.
Call open_refund_review as the agent and expect forbidden_role. Call it as the lead and expect pending_review with amountCents from the ticket.
Call the lead path twice and expect one review id.
Pass a store that never resolves and expect timeout before the test's own deadline. Use fake timers, or a timeout constant you inject. The listing above uses module constants; in the assignment, pass timeoutMs on the context if you need the test to finish in milliseconds.
There is nothing to clean up. The lab holds no credential.
Security
The registry is the security boundary for support tools. The model proposal is a request to enter it.
Role checks run before argument parsing side effects and before any store write. forbidden_role does not call TicketStore or ReviewStore. Lookup may parse first inside run, and a forbidden role never enters run.
Organization id comes from SupportCaller. The strict schema rejects a client-supplied organization id instead of dropping it on the floor.
not_found is the status for both a missing id and a cross-tenant id. Do not attach the other tenant's subject "for debugging."
Ticket body is returned to server code that already authorized the caller. Logs store ticket id, tool name, organization id, actor id, and reason. They do not store body, subject, or learner contact fields.
open_refund_review writes a pending row scoped to the caller's organization and the drafter's user id. Settlement, email, and role changes are not functions in TOOLS.
Idempotency keys include the organization and the prompt version so one tenant's replay cannot collide with another's, and a policy bump does not silently reuse a review written under the old rules.
MCP hosts that forward tools/call into this process must pass the host session's caller, not a tenant id from the tool arguments. Multi-tenant MCP states the same rule for remote servers. This registry is the in-process form.
A body that says "you are a support lead" does not change caller.role. The role was loaded from memberships before executeSupportTool ran.
Error Handling
Reason
Staff sees
Store write
Billing refund
not_registered
"That action is not available"
No
No
forbidden_role
"You cannot run that action"
No
No
invalid_arguments
"Check the ticket id"
No
No
not_found
"No ticket with that id"
No
No
timeout
"The ticket service timed out"
No review
No
Read success
Ticket view
No
No
Write success
"Review pending" plus the review id
Pending row
No
A timeout during open_refund_review may leave a race: the insert committed and the response lost. The staff retry uses the same idempotency key and receives the original row. Tell leads to retry once on timeout for the review tool. Do not build a second insert path that generates a new key per click.
Do not surface Zod issues to the console. invalid_arguments is enough. A detailed parse tree can echo the extra key the model tried to inject, which is useful in a staff-only trace and noisy in the UI. Keep the trace on the server, with the key names and without the ticket body.
Add three tests before you call the lesson done. A lookup of TCK-1042 as org_01 when the only row is org_02 returns not_found and the foreign body is absent from the result. A store whose get never resolves returns timeout (inject a short timeout in your assignment copy if you do not want the lab to wait 1,500 ms). A second tool name send_customer_email returns not_registered. Also assert the review's drafterId is the lead, and that the result object has no refunded: true field.
These tests claim the registry. They do not claim the pending review will be approved. Lesson 20's executor tests cover separation of duties. Wire them in the composition root. Do not duplicate a second approver inside openRefundReview, or the two policies will drift.
Performance and Cost
Lookups dominate this lesson's latency. Model tokens are zero inside executeSupportTool. The cost risk is a hung store, a retry storm, and a review path that accidentally calls the model "to explain the refund."
Keep timeouts on the tool. A process-wide timeout of tens of seconds hides a slow query inside a support click and ties up a worker.
Do not retry lookups automatically. Two staff clicks are two reads the staff member can see. A hidden retry doubles load during the incident you are already timing out on.
The review path reads the ticket once and inserts once. Replays hit putIfAbsent and skip a second logical insert. They may still read the ticket; that is acceptable for a rare lead action. If the read becomes hot, cache the ticket inside the request, not across requests, so a fresh amount is visible for a new idempotency key.
Do not send the ticket body to a model as part of execution. A summary call would bill tokens on every lookup and would put learner text in a provider log. Drafting belongs to an explicit step with a cap, which lesson 39 budgets.
Index the ticket table by (organization_id, ticket_id) when you leave the in-memory map. The registry's key is that pair. A lookup by ticket id alone is both a performance plan and a tenancy bug.
Illustrative, not a quote: a confirmed lookup costs one indexed read. A forbidden role costs zero reads. A lead review costs one read plus one insert on the first call, and one read plus one key lookup on the replay. None of these call DecisionPort.
Model selection and cost still applies to the proposal step. This lesson's job is to keep execution from adding a second, hidden model bill.
Knowledge Check
1. What problem does this capability solve?
It runs lookup_ticket and open_refund_review under a role list, a strict argument schema, a timeout, and the caller's organization. The earlier bug used organizationId from the model and refunded a model-supplied amount. The registry reads with the session's organization and copies amountCents from the ticket into a pending review.
2. What alternatives exist, and when would you choose each?
Stop at lesson 36's proposal when staff only need to see what the model asked. Use lesson 15's single read when the tool quotes a lesson section and never touches billing. Use a button that calls lesson 20 when a lead is already looking at the ticket and no model is required to choose it. Use this registry when a confirmed proposal must become one scoped read or one pending review. Use MCP when the tool runs in another process, and still pass the caller through this allowlist. Use the executor when the review is approved and money should move.
3. Which data, identity, and trust boundaries matter?
The session supplies SupportCaller. Arguments supply a ticket id or they fail. The ticket store is keyed by organization and ticket id. The review store records the drafter and the ledger amount. The billing executor is outside this package. Logs omit the body. Remote MCP tools do not bring their own tenant.
4. What can fail, and how should the system respond?
Unknown names return not_registered. Agents opening a review return forbidden_role with no store call. Extra keys and bad ids return invalid_arguments. A missing pair returns not_found. A slow store returns timeout. A repeated review key returns the original pending row. None of these settle a refund.
5. How would you test quality, security, performance, and cost?
Tests cover an in-org lookup, a smuggled organization id with zero store calls, an agent blocked from reviews, a lead's idempotent pending review at the ticket's amount, and an unregistered refund_course. Security review checks the foreign-tenant not_found path and the log shape. Performance review checks the per-tool timeout and the unique key that makes replay cheap. Cost review checks that execution does not call DecisionPort. Whether staff picked the right ticket is a product metric, not a schema test.
Hands-on Assignment
Lab note. Use in-memory stores. Do not create a provider account, a database password, or a live billing client.
Problem. Ship the support tool registry: scoped lookup, lead-only pending review, timeouts, and a hard miss for every other name.
Tasks.
Draw the diagram. Mark settlement as a box this package does not call.
Implement executeSupportTool, both tools, the strict schema, and putIfAbsent.
Add the tests in this lesson plus the foreign-tenant lookup, the timeout, and send_customer_email.
Write six rows: control, owner, evidence. Include role list, strict schema, organization key, timeout, idempotency key, and the absence of a billing write.
State the staff-visible copy for not_found, forbidden_role, timeout, and a successful review.
Show a log line for the foreign-tenant lookup. It includes organization id, actor id, ticket id, and not_found. It omits body.
Deliverable. Diagram, source with no secrets, test output, the six-row control table, and a short note on why the amount is read from the ticket.
Challenge. Two organizations, one process, identical ticket ids. An agent in org_01 looks up TCK-1042 while org_02's body contains a card number. Show that the result view's body is the org_01 text, that the card number appears in no object the function returns, and that a lead in org_01 who opens a review stores amountCents from the org_01 ticket only.
Rubric. Conceptual accuracy and architecture 20%. Working implementation and code quality 25%. Security, privacy, and responsible AI 20%. Testing, reliability, and observability 20%. Documentation and decision rationale 15%.
Common Mistakes
Reading organizationId from tool arguments. Symptom: an agent in one tenant receives another tenant's ticket body. Cause: the JSON field was copied into the query. Fix: strict schema, and tickets.get(caller.organizationId, ticketId).
Letting the model set amountCents. Symptom: the pending review is for a smaller amount than the ledger, and the executor later settles the smaller one. Cause: the schema accepted an amount. Fix: copy ticket.amountCents and reject extra keys.
Registering refund_course because the prompt mentions refunds. Symptom: billing changes inside a tool turn, with no second approver. Cause: the write tool performed the effect. Fix: register open_refund_review only, and leave settlement to lesson 20.
One shared timeout of half a minute. Symptom: the support console freezes during a replica stall and a retry doubles the read. Cause: the tool had no own deadline. Fix: runWithTimeout with the tool's timeoutMs, and no automatic retry.
Returning a different error for cross-tenant ids. Symptom: a caller confirms that TCK-9999 exists by comparing "forbidden" with "missing." Cause: the store was queried by ticket id, then filtered. Fix: query by the pair and return not_found for both misses.
Logging the body on failure. Symptom: learner text and a pasted secret show up in the shared log platform. Cause: the error logger dumped the ticket or the raw arguments. Fix: log ids and the reason. Keep the body in the store.
Treating MCP annotations as permission. Symptom: a remote tool marked "read-only" updates a row, or runs for every tenant the server hosts. Cause: the host skipped the registry and forwarded tools/call. Fix: the host builds SupportCaller from its session and calls executeSupportTool.
Summary
executeSupportTool runs two tools. Agents may look up a ticket in their own organization. Leads may also open a pending refund review whose amount comes from that ticket. Every other name is unregistered. Arguments that carry an organization or an amount fail the schema. A slow store times out. A repeated review key returns the original pending row. Money, mail, roles, and lesson progress stay outside the registry. The next lesson stores the lookup on a run the model cannot reassign to another agent.
Next Lesson Preview
Agent State, Memory and Conversation Orchestration persists the support run: owner, revision, a ticket slot filled only from a lookup you actually returned, and a short transcript that treats tool output as data. Two tabs cannot silently overwrite the slot.