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.
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())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,
@toolkeeps 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. ATool(...)can also be built directly, with a JSON Schema or a pydantic model asinput_schema. - In TypeScript,
input_schemamay 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@toolcalled directly with non-JSON values such as adatetimevalidates 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_unstableotherwise). Args a middleware substitutes throughnext(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 callingnext(view). - A JSON Schema
input_schema(either language) is checked by core's own interpreter, the one behind thejson_schemaoperator. Your own schema is compiled when the tool is defined, and one core cannot run (an unknown keyword, a bad$ref) raisescore.tool_schema_invalidright there. In TypeScript, a foreign tool's schema that core cannot run (an MCP tool usingunevaluatedProperties) still wraps throughwrapTool: 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(...)raisescore.tool_schema_invalidfor 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 beforenext(): the start event waits until the call reaches its body, andcall.maskafter that throwscore.mask_too_late. An invalid JSONPath throwscore.path_invalid.- A middleware that fails after the body returned cannot undo the body's effect: the recorded
tool_callholds the result and the failure asviewport.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_skillanswersnot_foundwith a hint) opts out withvalidate: false(TSdefineTool) /validate=False(PythonTool(...), JSON Schema only). Its arguments are still copied and recorded, and laterwrapToolcalls keep the opt-out. - A secret argument is declared with
writeOnly: truein the input schema (pydantic'sSecretStrandSecretBytesemit it). Middleware, gate digests and the tool get the real value; every recordedtool_callevent holds[redacted hmac:<first 12 hex of HMAC-SHA256(tenant key, value)>]instead, the same marker HITL shows approvers. Set the master key withVIEWPORT_REDACT_KEY, for example the output ofopenssl rand -hex 32as it is (64 hex digits are read as hex, canonical base64 of 32 bytes or more as base64,hex:andbase64: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, ornone)).decodeRedactKey,deriveRedactKeyandredactionMarker(decode_redact_key,derive_redact_key,redaction_markerin Python) are what HITL uses too. withToolServer(server, fn)(Pythonwith 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) orundefined/Noneto run the tool. A served call records as a normaltool_callwith the span attributeviewport.tool.served: true. Outside a test runner the first use warns once (warn: falseacknowledges it).compose(a, b)appliesaoutermost: it sees the call first.- Invalid arguments raise
SpecErrorwith codecore.tool_args_invalidand one issue per problem.