Skip to main content

Chapter 22. Tool-Using, Coding, and Computer-Use Agents

Tool Use, Function Calling, and MCP

Harbor & Pine adds a shipping-status tool to Juniper. The model selects the right function and emits valid JSON, but passes a customer’s account number where the function expects an order ID. In this fictional example, the identifier happens to match a different order, so the call succeeds and retrieves the wrong record. Although the interface accepted the request, it did not establish that the agent had chosen the right entity.

Tool use is the observable interface between an agent and systems that can return information or change state. Evaluating it means following the whole transaction: was the tool appropriate, were its arguments grounded in the request or trusted observations, did the call respect its contract, and did the resulting state match the authorized intent? Chapter 5 introduced the trajectory and outcome checks behind these questions; here we apply them to tools, then extend the same reasoning to agents that edit code or operate graphical interfaces.

After this chapter you will be able to:

  • measure tool selection and argument grounding separately from schema validity;
  • define positive, negative, and ambiguity cases for tool-call evaluation;
  • test multi-tool sequences, error handling, and consequential side effects;
  • evaluate tool descriptions, server capabilities, and protocol integration as one system;
  • interpret tool benchmarks without confusing benchmark score with production readiness.

Illustrative case. Harbor & Pine and Juniper are fictional. All tool names, requests, and outputs below are synthetic. MCP examples refer to the public protocol specification, not to an endorsement of a specific server.

Evaluation contract

Step Tool-use example
Case A customer requests a refund; order identity, policy eligibility, and authorization vary by case.
Observable evidence Selected tool, grounded arguments, schema version, tool result, authorization decision, and final state diff.
Oracle Versioned refund policy plus authoritative order and identity state; schema checks alone are insufficient.
Metric Episode success, argument accuracy, unnecessary calls, unauthorized writes, and safe error recovery, reported separately.
Decision Hold on any unauthorized or wrong-record write; use predeclared task and operational thresholds for other outcomes.
Failure analysis Locate the first failure in selection, grounding, validation, server execution, or post-action verification.

22.1 Tool selection and argument grounding

Juniper’s mistaken lookup illustrates why selecting the right tool is only the first step. For each task, define the acceptable tools and the evidence needed to call them. One useful selection metric considers cases where a tool call is expected; report no-tool cases separately, including requests where the agent should answer directly, ask for clarification, or abstain. Without those cases, a model that calls tools constantly can look strong simply because it rarely misses an expected call.

Argument correctness is field-specific. For lookup_order(order_id=...), verify the entity identity against the user’s request and any trusted clarification, rather than counting a guessed identifier as grounded merely because it exists in the fixture. A useful test set includes paraphrases, multiple entities, missing arguments, conflicting history, plausible distractors, and requests that do not authorize a state-changing call.

The constraints can be explicit without requiring one particular explanation from the agent. For example:

expected = {
    "tool": "lookup_order",
    "required_arguments": {"order_id": "HP-1004"},
    "must_not_call": ["issue_refund"],
}

This fixture specifies one expected identifier, although a broader task may permit several valid arguments or safe paths. In production evaluation, score the selected tool, each argument, whether the call was appropriate, and the observed effect. Keeping these dimensions separate prevents perfect JSON formatting from hiding an incorrect tool or target.

22.2 Schema adherence and error handling

The identifier can be wrong even when it satisfies every syntactic rule. A tool schema defines names, types, required fields, enums, and sometimes constraints across fields, so structural validation catches malformed calls before execution. Semantic checks, by contrast, address calls that are structurally valid but violate task or policy conditions. Validate against the same schema version used at runtime, since a stale evaluator can misclassify valid calls or miss breaking changes.

Test valid boundaries as well as invalid inputs: empty strings, omitted optional fields, nulls, numeric limits, unknown enum values, and extra fields. Also record whether failure occurred during model generation, adapter validation, server validation, or tool execution, because these are different failure classes and should not be collapsed into one “tool error.”

Error handling should be measured by the response to the actual error, not simply by whether the model retries. A retry requires an operation with appropriately defined idempotent behavior or a server-enforced idempotency key, as well as a bounded retry policy. For consequential writes, evaluate duplicate calls, partial failures, timeouts with uncertain completion, and whether the agent checks authoritative state before claiming success. A key alone is not protection unless the service honors it for the relevant operation and time window.

22.3 Multi-tool orchestration

Juniper may need more than one call to complete a request: retrieve an order, check eligibility, and only then issue a refund. The evaluator must therefore consider prerequisites, ordering constraints, data passed between calls, and final state. A dependency graph is often a clearer oracle than a single “correct sequence,” because safe plans may contain optional reads or valid parallel calls.

For each episode, record tool-call count, successful-call count, unnecessary or duplicate calls, critical ordering violations, latency, cost, and final state. Per-call accuracy is not an episode pass rate: a workflow with many correct reads but one unauthorized write must fail its safety gate even if its average call score is high.

Worked example: sales research-to-outreach workflow

The same dependency problem appears outside customer support. Consider a fictional workflow agent that researches a prospect, retrieves product facts, drafts an email, and can create or send a CRM message. Each stage needs its own evidence: source records and retrieval versions for research; supported claims and required content for the draft; consent, suppression, and authorization state for CRM actions. Even a polished message does not make the workflow successful if it invents a prospect fact or sends after an opt-out.

For a synthetic prospect, the authoritative record supports the industry and pain-point claims, but the draft also asserts a 14-day implementation promise that is absent from approved sources. Two of three claims are supported, so claim-support rate is \(2/3=0.667\). The required sender identity and opt-out language are present, the prospect has not opted out, and no send action occurred. Nevertheless, the draft fails its evidence gate and must not be sent.

from bookkit.domain_eval import evaluate_sales_outreach

report = evaluate_sales_outreach(
    source_facts={
        "industry": "manufacturing",
        "pain_point": "manual quoting",
        "product_integration": "CRM connector",
    },
    draft_claims={
        "industry": "manufacturing",
        "pain_point": "manual quoting",
        "implementation_days": 14,
    },
    required_disclosures={"sender_identity", "opt_out_language"},
    included_disclosures={"sender_identity", "opt_out_language"},
    prospect_opted_out=False,
    message_sent=False,
    crm_action_authorized=True,
)
print(
    f"evidence-supported claims: {report['supported_claims']}/"
    f"{report['claim_count']} = {report['claim_support_rate']:.3f}"
)
print(f"unsupported claims: {report['unsupported_claims']}")
print(
    f"disclosures_complete={report['disclosures_complete']}; "
    f"opt_out_respected={report['opt_out_respected']}; "
    f"send_allowed={report['send_allowed']}"
)
evidence-supported claims: 2/3 = 0.667
unsupported claims: ['implementation_days']
disclosures_complete=True; opt_out_respected=True; send_allowed=False

The unit is one outreach draft; the claim-support denominator is its three checkable factual claims. The helper compares supplied key-value pairs rather than extracting or verifying natural-language claims. Its send_allowed field is not a reliable pre-send authorization decision: when message_sent is false, its opt-out and authorization checks describe the absence of a past violation rather than whether a future send is permitted. An empty claim set also receives a support rate of 1.0. In this fixture, the unsupported claim happens to make send_allowed false, but that result must not be used as a production send gate.

In a real system, qualified reviewers should define which statements count as claims and validate the source-to-claim grader. A separate pre-send control must check current suppression, consent, authorization, disclosures, and the supported draft before any action; post-action auditing asks whether a violation actually occurred. Track draft factuality, relevance/personalization, disclosure completeness, opt-out violations, and unauthorized CRM actions separately. Any unsupported material claim, send to a suppressed prospect, or unauthorized send is a hard stop. Offline draft quality does not prove that outreach improves sales; assess business outcomes separately under an approved experimental design with contact-frequency limits and compliance guardrails.

Run python code\ch11\lab_sales_outreach.py to reproduce this synthetic draft check; it does not connect to a CRM or send messages, and it is not an adequate pre-send authorization control.

22.4 Evaluating MCP servers and tool descriptions

In an MCP-based system, an apparently simple tool call crosses several boundaries. The Model Context Protocol standardizes how clients discover and invoke tools and exchange context with servers [1], so an evaluation has at least three layers: model behavior, client/adapter behavior, and server behavior. Test discovery and schema exposure, invocation and result handling, error propagation, cancellation/timeouts, and changes across server versions. Otherwise, a protocol or server defect may be mistaken for a model failure.

Tool descriptions are part of the interface, so vary one description feature at a time—name, purpose, argument explanation, examples, or warnings—and evaluate tool selection on a held-out task set. Record descriptions and schemas with the run; a description that improves benchmark scores but encourages over-calling or unsafe inference is not an improvement.

Operational checks include least-privilege credentials, explicit tool allowlists, bounded outputs, version pinning, and audit records. A successful protocol handshake does not prove that the server’s data scope or side effects are safe.

22.5 Tool-use benchmarks and what they miss

With a local contract in place, public benchmarks can provide useful comparisons and ideas for additional cases. BFCL evaluates function calling across tool and agent settings, and \(\tau\)-bench emphasizes interaction with tools, users, and domain rules [2], [3]. AgentBench covers varied interactive environments [4]. Each answers questions about its own tasks and scoring rules; none establishes that an agent is safe under your permissions, data, failure modes, or traffic distribution.

Before adopting a benchmark, inspect its task population, environment determinism, tool schema realism, state oracle, contamination controls, scoring rules, and repeated-run protocol, and reproduce the baseline where possible. Then add local cases for your own tools and policies, reporting benchmark and product-specific results separately.

Coding, Computer-Use, and Web Agents

The same distinction between an action and its consequences applies when the interface is a repository or a screen rather than a named function. Imagine a coding agent that fixes the reported test and passes the visible suite, but silently removes a security check, or a browser agent that reaches the requested page by clicking a hidden destructive control. In neither case does a green task-completion flag mean the work is correct, safe, or maintainable.

Coding and computer-use agents act in environments where the result can be checked partly by machines: tests, state diffs, browser observations, and task completion. Evaluation must also detect regressions, unintended side effects, environmental flakiness, and shortcuts that satisfy a narrow oracle but violate intent.

After this chapter you will be able to:

  • build outcome checks for code patches and repository tasks;
  • evaluate web and GUI actions against observed state, not click counts;
  • identify flaky tests and separate agent variance from environment variance;
  • detect side effects and make irreversible actions explicit gates;
  • report partial progress and efficiency without rewarding unsafe shortcuts.

Illustrative case. All repository tasks and browser states in the lab are synthetic. Run code-agent evaluations in isolated, disposable workspaces with controlled credentials.

Evaluation contract

Step Coding and computer-use example
Case Fix a specified defect or complete a browser task from a reproducible initial repository or application state.
Observable evidence Patch or state diff, relevant test output, action trace, environment version, and external side effects.
Oracle Task-specific tests and authoritative state/invariant checks, supplemented by scoped human review.
Metric Verified completion, regression and scope-violation rates, side effects, repeatability, and cost.
Decision Reject unsafe side effects or broken invariants even if visible tests pass; compare other outcomes to predeclared gates.
Failure analysis Separate agent behavior, test-oracle gaps, environment flakiness, and task-spec ambiguity.

22.6 Test-based grading for code agents

For a code agent, the task outcome is often a patch, which should be graded against the task contract rather than similarity to a reference diff. Existing tests, tests for the requested behavior, static checks, and relevant regression suites provide complementary evidence. A pass establishes only that the tested checks passed in the tested environment; it does not establish correctness for untested behavior.

Protect against test gaming: include hidden tests where feasible, verify that tests remain present and meaningful, inspect changed files, and check security or API invariants. Report task success, regression rate, test coverage relevant to the change, build status, patch scope, and human review separately. SWE-bench illustrates repository-level issue resolution evaluated through task-specific tests [5].

22.7 GUI and browser environments

In a GUI, there may be no patch to inspect, and a click, keystroke, or DOM event is an action rather than proof that the requested change took effect. A useful benchmark therefore needs a reproducible initial state, accessible observations, action logs, and a trusted state oracle. Check the resulting application state and record viewport, browser, locale, permissions, network conditions, and app version.

WebArena provides realistic websites and tasks for browser agents [6], while OSWorld evaluates open-ended tasks in real computer environments across desktop and web applications [7]. Benchmark environments are still not identical to production, so keep test accounts and data synthetic, isolate sessions, and capture screenshots or state snapshots that allow failures to be replayed.

22.8 Flakiness and environmental noise

Even with an appropriate oracle, a failed run may not identify the failing component: the agent, a nondeterministic application, network timing, or the test itself could be responsible. Run controls with a known-good script or baseline agent, repeat selected cases, and record failures observed in those controls. Their rate is informative about that control and environment, not necessarily a complete estimate of every environmental failure. Fix retry policies in advance and preserve all attempts rather than silently dropping failed runs.

For comparison, use paired tasks and the same environment version. Report both first-attempt and eventual success if retries are part of the product. If a browser state is nondeterministic, capture enough context to separate environment instability from agent choice.

22.9 Side effects and irreversible actions

The final state also has a blind spot: an agent may perform an unauthorized action and later reverse it. Inspect the available state diff and action history—files changed, permissions altered, messages sent, records created, and external actions triggered—while recognizing that no snapshot alone proves that all side effects were captured. Set allowlists and expected-change boundaries. Use a disposable sandbox, mock external services, and explicit approval gates for irreversible operations. Never evaluate against live accounts or customer data without a reviewed safety plan.

For code tasks, inspect generated tests, dependency changes, secrets exposure, and unrelated modifications. For web tasks, verify that the agent did not submit, purchase, delete, or publish anything beyond the task scope, because a correct final page does not erase an unauthorized intermediate action.

22.10 Partial credit and efficiency

Even a failed task can yield useful diagnostic information: the agent may have found the right files or produced a promising draft patch. Milestones can show that progress, but must not obscure final correctness, so report them alongside hard safety gates and end-state success. A weighted composite may be useful for dashboards, but retain its dimensions and make an unsafe side effect non-compensable.

Measure tool calls, elapsed time, token use, tests run, and recovery attempts, but compare efficiency only among runs that satisfy critical quality constraints. Faster code that removes validation is not more efficient in a product-relevant sense.

Chapter summary

Tool use and function calling

The tool-use contract connects the agent’s selection and arguments to the effects of the call:

  • Score tool choice, argument grounding, schema validity, execution, and outcome as separate dimensions.
  • Include tool-not-needed, clarification, and abstention cases to measure overuse as well as missed calls.
  • Validate schemas at runtime versions and distinguish generation, adapter, server, and execution failures.
  • Evaluate sequences through prerequisites, ordering constraints, state effects, and episode-level safety gates.
  • Treat MCP client, model, and server as separate but interacting evaluation surfaces.
  • Use benchmarks as evidence about tested tasks—not as proof of production readiness.

For product managers. Which tools can change state, and which actions require approval? What authoritative record proves the right entity was affected? Which calls may be retried safely? Ask for a scorecard that separates correct use, overuse, failures, latency, cost, and harmful side effects.

Coding and computer use

Repository and browser tasks require the same attention to outcomes, process, and side effects, but their evidence comes from different environments:

  • Grade patches and GUI tasks against task outcomes and invariants, not reference-path similarity.
  • Treat passing tests as evidence for tested behavior, not a proof of general correctness.
  • Record environment state and use controls to estimate flakiness.
  • Inspect all side effects and gate irreversible actions.
  • Report milestones and efficiency separately from final success and safety.
  • Use sandboxed, synthetic, replayable environments for agent evaluation.

For product managers. What counts as a correct patch or completed browser task? Which changes are unacceptable even if tests pass? Ask how the team controls credentials, replays failures, detects flaky infrastructure, and measures regressions outside the requested feature.

Hands-on labs (Python)

Lab 1: Tool use and function calling

Run python code\ch11\lab_tools.py with code on Python’s module search path. The synthetic fixture evaluates expected tool selection, required arguments, basic argument-name checks, and prohibited calls, then prints the shared evaluation record from Appendix D. It uses no provider SDK or live tool. The ch11 directory is a retained legacy lab identifier.

The helper compares arguments with values supplied in the fixture; it does not establish their provenance, validate a full runtime schema, execute the tool, or inspect a resulting state. The “grounded” claim below is therefore a fixture assertion, not independent evidence that a real agent used an authoritative source.

from bookkit.tool_eval import evaluate_call
from bookkit.system_eval import evaluation_record

case = {
    "expected_tool": "lookup_order",
    "required_arguments": {"order_id": "HP-1004"},
    "allowed_arguments": {"order_id"},
    "allowed_tools": {"lookup_order", "issue_refund"},
    "forbidden_tools": {"issue_refund"},
}
result = evaluate_call(
    {"tool": "lookup_order", "arguments": {"order_id": "HP-1004"}},
    case,
)
print(result)
print(evaluation_record(
    claim="The requested order lookup is selected and grounded",
    case_id="tool-lookup-01@v1",
    evidence_ref="fixture://ch11/call-01",
    oracle={"id": "tool-case-v1", "result": "pass" if result["passed"] else "fail"},
    metric={"name": "tool_call_pass", "value": int(result["passed"]), "denominator": 1},
    decision={"result": "pass" if result["passed"] else "hold", "reason": "synthetic fixture gate"},
    failure_category=None if result["passed"] else "tool_call_contract",
))
{'tool_correct': True, 'arguments_correct': True, 'schema_valid': True, 'forbidden_call': False, 'passed': True}
{'claim': 'The requested order lookup is selected and grounded', 'case_id': 'tool-lookup-01@v1', 'evidence_ref': 'fixture://ch11/call-01', 'oracle': {'id': 'tool-case-v1', 'result': 'pass'}, 'metric': {'name': 'tool_call_pass', 'value': 1, 'denominator': 1}, 'decision': {'result': 'pass', 'reason': 'synthetic fixture gate'}, 'failure_category': None}

Lab 2: Coding and computer use

Run python code\ch15\lab_computer_agents.py with code on Python’s module search path. The synthetic fixture represents a code patch whose visible and regression tests pass while a hidden authorization invariant fails. No repository files are modified and no candidate patch or tests are run; the script prints the shared evaluation record from Appendix D. The ch15 directory is a retained legacy lab identifier.

The grader checks supplied sets of passed checks and changed paths, together with a supplied side-effect list; it does not discover those facts itself. In a real evaluation, collect them from controlled test execution, an independently inspected workspace, and the relevant external systems.

from bookkit.computer_eval import grade_workspace
from bookkit.system_eval import evaluation_record

passed_checks = {"visible", "regression"}
result = grade_workspace(
    required_checks={"visible", "regression", "authorization_invariant"},
    passed_checks=passed_checks,
    allowed_paths={"src/refunds.py", "tests/test_refunds.py"},
    changed_paths={"src/refunds.py", "tests/test_refunds.py"},
    side_effects=[],
)
print("visible checks pass:", {"visible", "regression"}.issubset(passed_checks))
print("authorization invariant pass:", "authorization_invariant" in passed_checks)
print(result)
print(evaluation_record(
    claim="The patch preserves the authorization invariant as well as visible behavior",
    case_id="workspace-authorization-fix-02@v1",
    evidence_ref="fixture://ch15/hidden-invariant-report",
    oracle={"id": "workspace-invariants-v1", "result": "pass" if result["passed"] else "fail"},
    metric={
        "name": "workspace_task_pass",
        "value": int(result["passed"]),
        "denominator": 1,
    },
    decision={
        "result": "pass" if result["passed"] else "hold",
        "reason": "hidden authorization invariant failed",
    },
    failure_category=None if result["passed"] else "security_invariant_regression",
))
visible checks pass: True
authorization invariant pass: False
{'checks_pass': False, 'scope_valid': True, 'side_effects_clear': True, 'passed': False}
{'claim': 'The patch preserves the authorization invariant as well as visible behavior', 'case_id': 'workspace-authorization-fix-02@v1', 'evidence_ref': 'fixture://ch15/hidden-invariant-report', 'oracle': {'id': 'workspace-invariants-v1', 'result': 'fail'}, 'metric': {'name': 'workspace_task_pass', 'value': 0, 'denominator': 1}, 'decision': {'result': 'hold', 'reason': 'hidden authorization invariant failed'}, 'failure_category': 'security_invariant_regression'}

Exercises

The exercises ask you to design checks for both the chosen action and the consequences it can have.

Tool use and function calling

  1. Conceptual. Why can schema-valid tool use still be incorrect? Give one example for a read and one for a write.
  2. Design. Create positive and negative cases for a tool that searches orders by email. Include a case where the agent should ask a clarifying question.
  3. Hands-on. Change the order ID in the lab call and observe which dimensions fail. Add an extra argument and test how your schema policy treats it.
  4. Operations. Design retry rules for an idempotent read and a non-idempotent write after a timeout.
  5. Discussion. Which benchmark tasks would you trust to compare models, and which product risks need a local evaluation?

Coding and computer use

  1. Design. Write hidden regression tests for a bug fix without overfitting to a reference patch.
  2. Hands-on. Add an unrelated changed path to the lab and define the expected scope failure.
  3. Operations. Design a known-good control to estimate browser-environment flakiness.
  4. Safety. Define which actions in a web workflow require approval and how the harness prevents real submission.
  5. Discussion. When is partial credit useful, and when might it mislead a release decision?

Further reading

These sources offer benchmark and protocol examples to compare with the local contracts developed in this chapter:

Tool use and function calling

  • Patil et al., The Berkeley Function Calling Leaderboard, for tool-call and agentic function-calling evaluation [2].
  • Yao et al., \(\tau\)-bench, for policy-aware tool-agent-user interaction and repeated-run reliability [3].
  • Model Context Protocol specification, for the protocol surface that clients and servers must expose [1].
  • Liu et al., AgentBench, for interactive agent evaluation across multiple environments [4].

Coding and computer use

  • Jimenez et al., SWE-bench, for issue resolution in real software repositories [5].
  • Zhou et al., WebArena, for reproducible browser-agent tasks in realistic web environments [6].
  • Xie et al., OSWorld, for open-ended computer-use tasks evaluated in real computer environments [7].
  • Efron, for bootstrap methods useful when estimating uncertainty across task samples [8].
[1]
Model Context Protocol contributors, “Model context protocol specification, version 2025-06-18.” Accessed: Nov. 10, 2026. [Online]. Available: https://modelcontextprotocol.io/specification/2025-06-18
[2]
S. G. Patil et al., “The berkeley function calling leaderboard (BFCL): From tool use to agentic evaluation of large language models,” in Proceedings of the 42nd international conference on machine learning, Proceedings of Machine Learning Research, 2025, pp. 48371–48392. Available: https://proceedings.mlr.press/v267/patil25a.html
[3]
S. Yao, N. Shinn, P. Razavi, and K. Narasimhan, “\(\tau\)-bench: A benchmark for tool-agent-user interaction in real-world domains.” 2024. Available: https://arxiv.org/abs/2406.12045
[4]
X. Liu, H. Yu, H. Zhang, et al., “AgentBench: Evaluating LLMs as agents,” in International conference on learning representations (ICLR), 2024. Available: https://arxiv.org/abs/2308.03688
[5]
C. E. Jimenez, J. Yang, A. Wettig, et al., “SWE-bench: Can language models resolve real-world GitHub issues?” in International conference on learning representations (ICLR), 2024. Available: https://openreview.net/forum?id=VTF8yNQM66
[6]
S. Zhou, F. F. Xu, H. Zhu, et al., “WebArena: A realistic web environment for building autonomous agents,” in International conference on learning representations (ICLR), 2024. Available: https://arxiv.org/abs/2307.13854
[7]
T. Xie et al., “OSWorld: Benchmarking multimodal agents for open-ended tasks in real computer environments.” 2024. Available: https://arxiv.org/abs/2404.07972
[8]
B. Efron, “Bootstrap methods: Another look at the jackknife,” The Annals of Statistics, vol. 7, no. 1, pp. 1–26, 1979, doi: 10.1214/aos/1176344552.