Core

Tools and middlewares

A stack-neutral Tool, middlewares that compose in any order, and tool call recording that is built in.

A Tool is what a model sees (name, description, input_schema, optional output_schema, attributes, provider_options) plus an async execute(args, context). Adapters translate it to and from each agent stack. A ToolMiddleware is a function from tool to tool. HITL gating and Context's per-skill binding are middlewares, so they compose in any order with yours.

Recording is built in. A tool made with @tool / defineTool, or wrapped with wrap_tool / wrapTool, emits one tool_call event per call whenever a sink is in scope. Middlewares run inside that recording, so a call a middleware refuses is still recorded, with its error, and events the middleware emits get the call as their parent. Wrapping again never records twice.

main.py
import asyncio
import contextlib

from viewportai.core import (
    ToolCall,
    ToolContext,
    ToolNext,
    ViewportError,
    stable_json,
    tool,
    tool_middleware,
    trace,
    wrap_tool,
)


@tool
async def issue_refund(order_id: str, amount: float, ctx: ToolContext) -> dict[str, str]:
    """Refund an order."""
    return {"refund_id": f"R-{order_id[2:]}", "call": ctx.call_id or ""}


@tool_middleware
async def max_amount(call: ToolCall, next: ToolNext) -> object:
    if call.args["amount"] > 100:
        raise ViewportError("example.too_large", "refunds over $100 need approval")
    return await next()


guarded = wrap_tool(issue_refund, max_amount)
print(stable_json(guarded.descriptor().input_schema["required"]))  # ["order_id","amount"]: ctx is not in the schema


async def main() -> None:
    async with trace() as t:
        await guarded.execute({"order_id": "A-1", "amount": 5}, ToolContext(call_id="toolu_1"))
        with contextlib.suppress(ViewportError):
            await guarded.execute({"order_id": "A-2", "amount": 500})
    calls = t.trajectory.tool_calls()
    print(calls[0].call_id)  # toolu_1
    print(stable_json([c.error.type if c.error else "ok" for c in calls]))  # ["ok","example.too_large"]


asyncio.run(main())
main.ts
import { compose, defineTool, stableJson, toolCalls, toolMiddleware, trace, ViewportError, wrapTool } from "@viewportai/core";

const issueRefund = defineTool({
  name: "issue_refund",
  input_schema: {
    type: "object",
    properties: { order_id: { type: "string" }, amount: { type: "number" } },
    required: ["order_id", "amount"],
  },
  execute: async ({ order_id }, context) => ({ refund_id: `R-${order_id.slice(2)}`, call: context.callId ?? "" }),
});

const maxAmount = toolMiddleware(async (call, next) => {
  if ((call.args as { amount: number }).amount > 100) throw new ViewportError("example.too_large", "refunds over $100 need approval");
  return next();
});
const audit = toolMiddleware(async (call, next) => next(call.args, { ...call.context, attributes: { audited: true } }));

const guarded = wrapTool(issueRefund, compose(audit, maxAmount)); // audit sees the call first

console.log(stableJson(guarded.input_schema.required)); // ["order_id","amount"]

const { trajectory } = await trace(async () => {
  await guarded.execute({ order_id: "A-1", amount: 5 }, { callId: "toolu_1" });
  await guarded.execute({ order_id: "A-2", amount: 500 }).catch(() => {});
});
console.log(toolCalls(trajectory)[0]?.call_id); // toolu_1
console.log(stableJson(toolCalls(trajectory).map((c) => c.error?.type ?? "ok"))); // ["ok","example.too_large"]

Notes:

  • In Python, @tool keeps the function callable with its own signature (await issue_refund("A-1001", 42.5)) and validates arguments with pydantic. .execute(args, context) is the form adapters use. A Tool(...) can also be built directly, with a JSON Schema or a pydantic model as input_schema.
  • In TypeScript, input_schema may be a JSON Schema written inline (arguments are typed from it) or a Standard Schema such as zod (arguments are validated, and transformed, by it).
  • Arguments are validated once, before any middleware runs, on a copy the caller can no longer change (frozen in TypeScript, Standard Schema output included; read-only dicts and lists in Python, and a pydantic model instance is validated again from a copy of its fields), so a gate that awaits a human approval approves exactly what the tool then runs with and what the trajectory records. The copy accepts JSON only: NaN, Infinity, class instances, Maps and Dates are core.tool_args_invalid (a Python @tool called directly with non-JSON values such as a datetime validates a deep copy instead). What you approve is what runs: the validated arguments are one frozen JSON view that gates approve and the trajectory records, and the tool body runs on a fresh parse of it on every attempt, so validation must be idempotent on the view (core.tool_args_unstable otherwise). Args a middleware substitutes through next(args) are validated into a view, passed inward, and recorded as what ran; call.revalidate(args) gives a view to compare with an approved grant before calling next(view).
  • A JSON Schema input_schema (either language) is checked by core's own interpreter, the one behind the json_schema operator. Your own schema is compiled when the tool is defined, and one core cannot run (an unknown keyword, a bad $ref) raises core.tool_schema_invalid right there. In TypeScript, a foreign tool's schema that core cannot run (an MCP tool using unevaluatedProperties) still wraps through wrapTool: its args get the JSON check and the copy, are masked as unvalidated, and its own server validates the rest. Python has no such fallback yet: Tool(...) raises core.tool_schema_invalid for that schema.
  • call.mask(jsonpaths) marks parts of a call's arguments secret at call time (a policy's secrets), as JSONPaths over the arguments: $.headers.Authorization, $.cards[*].number, or $ for all of them (one marker). The paths are unioned with the schema's secret positions (writeOnly, x-viewport-secret: true, format: "password") and masked in the recorded start and final events, in any substituted arguments, and in validation errors that touch them, both the recorded error and the one thrown to the caller. Call it before next(): the start event waits until the call reaches its body, and call.mask after that throws core.mask_too_late. An invalid JSONPath throws core.path_invalid.
  • A middleware that fails after the body returned cannot undo the body's effect: the recorded tool_call holds the result and the failure as viewport.tool.middleware_error. TypeScript and async Python still raise the failure to the caller; a Python sync tool run in place returns the result.
  • A tool that turns bad arguments into a readable result itself (Context's load_skill answers not_found with a hint) opts out with validate: false (TS defineTool) / validate=False (Python Tool(...), JSON Schema only). Its arguments are still copied and recorded, and later wrapTool calls keep the opt-out.
  • A secret argument is declared with writeOnly: true in the input schema (pydantic's SecretStr and SecretBytes emit it). Middleware, gate digests and the tool get the real value; every recorded tool_call event holds [redacted hmac:<first 12 hex of HMAC-SHA256(tenant key, value)>] instead, the same marker HITL shows approvers. Set the master key with VIEWPORT_REDACT_KEY, for example the output of openssl rand -hex 32 as it is (64 hex digits are read as hex, canonical base64 of 32 bytes or more as base64, hex: and base64: prefixes are explicit, anything else is text of at least 32 bytes; default a random key per process): each tenant's key is HMAC-SHA256(master, viewport.redact: + (t: + tenant, or none)). decodeRedactKey, deriveRedactKey and redactionMarker (decode_redact_key, derive_redact_key, redaction_marker in Python) are what HITL uses too.
  • withToolServer(server, fn) (Python with tool_server(server):) answers tool calls instead of running the tools, for replaying production runs in evals. It is asked where the tool body would run, after validation and inside every middleware, so gates still decide first; the answer is { result }, { error } (recorded verbatim) or undefined / None to run the tool. A served call records as a normal tool_call with the span attribute viewport.tool.served: true. Outside a test runner the first use warns once (warn: false acknowledges it).
  • compose(a, b) applies a outermost: it sees the call first.
  • Invalid arguments raise SpecError with code core.tool_args_invalid and one issue per problem.