Testing Tools, with a Trading-System Example

Business rules are the code you least want to break, and they are often the code that is hardest to test, because the rule is tangled up with a database call, a payment client and a clock. LVD tools avoid the tangle by construction. Everything that touches the outside world arrives as an argument, so a test can swap it for a fake in a few lines.

Inject the world, then fake it

Tools depend on the Resources layer for all their input and output. That single fact makes isolated testing straightforward: to test a tool, replace each resource with a mock or stub. The book's recommended approach is dependency injection. The handler receives its resources as parameters, or through a context object, instead of importing them.

The handler is the business logic, so with its resources faked, a unit test exercises nothing else. There is no network, no database and no web framework to start.

Four behaviours worth pinning down

The book lists four things a handler's tests should cover:

  • The happy path: the resource calls happen in the right order and the return value is correct.
  • Validation failure: schema errors surface before any resource is touched.
  • Business rules: an operation that breaks a rule is rejected.
  • Error handling: when a resource fails, the caller gets a sensible message or a partial result.

Here is the third kind, written for a veterinary clinic's booking tool:

it("refuses to move a visit into a full slot", async () => {
  const visits = { get: vi.fn().mockResolvedValue(visit), save: vi.fn() };
  const calendar = { slotsLeft: vi.fn().mockResolvedValue(0) };

  await expect(
    rescheduleVisitHandler({ visitId: "v1", newSlot }, { visits, calendar }),
  ).rejects.toThrow("fully booked");

  expect(visits.save).not.toHaveBeenCalled();
});

Notice the last line. A good tool test checks what the handler declined to do as well as what it returned.

Where unit tests stop

Fakes cannot tell you whether the real repository speaks to a real database correctly, so the book pairs unit tests with integration tests that run the same handler against real or realistic resources. For database access that usually means an in-memory database or a test container, and the assertions go beyond the return value: did the record actually get persisted, with the right status?

The coverage target reflects this split. The Tools layer aims for at least 90 percent line and branch coverage, a little below the 95 to 100 percent set for Schema and Utils. The reason is honest rather than lax. Tools orchestrate asynchronous resource calls, and some of their failure modes, such as network timeouts and partial writes, are better exercised at the integration level than in a unit test.

A trading example: two tools, two personalities

The book's TradeX platform makes the point with a pair of tools. placeOrder has a 500 microsecond end-to-end budget and follows a five-step pattern: validate, check compliance, compute margin, persist, route. Each step gets its own sub-budget. It is annotated as neither read-only nor idempotent, which tells agents and protocol layers that it changes state, should not be retried without explicit user confirmation, and will create a duplicate order if invoked twice.

calculateVar sits at the opposite end. It fetches positions and price history through resources, then hands the numerical work to pure Utils functions. It is read-only and idempotent, so an agent can call it repeatedly with different parameters, and a protocol layer may cache its answers briefly.

TradeX also extends the standard annotations with its own flags, such as a compliance requirement and a market-hours restriction, and these flow through the registry into MCP tool definitions and REST OpenAPI documents. For testing, the lesson is that these hints are part of a tool's contract. A cheap test that asserts a tool's annotations will catch the day somebody quietly changes a read-only tool into a writing one.

The takeaway

Tools are easy to test because they are forbidden from reaching sideways and expected to receive their dependencies. Fake the resources for speed, use real ones for confidence, and treat annotations as part of what you verify. For the structure that makes this possible, see the anatomy of a tool. For the same ideas applied to the layer beneath, read testing the resources layer, and for the whole picture, the LVD testing pyramid.

What the book covers

  • Mocking resource dependencies through a context object, with full test listings
  • Integration tests against in-memory databases and test containers
  • The coverage targets for the Tools layer compared with Schema and Utils
  • The TradeX placeOrder tool and its per-step latency budget
  • The domain-specific annotations TradeX adds to the MCP standard set