Give Tools Per-Request Dependencies

easy5 mintool-deps.ts

One agent serves many users, and its tools need each request's database client or signed-in user. Putting them in the prompt leaks them to the model, closures do not work for a shared agent.

What it shows

  • Pass deps to run(), read them as context.deps in the tool
  • ToolContext<Deps> and new Agent<Deps> check both sides at compile time
  • deps never reach the model, memory, spans or paused checkpoints

The code

tool-deps.ts
import { Agent, Cogitator, tool, type ToolContext } from '@cogitator-ai/core';
import { z } from 'zod';

interface ShopDeps {
  orders: Map<string, string[]>;
  userId: string;
}

const listOrders = tool({
  name: 'list_orders',
  description: "List the signed-in customer's orders",
  parameters: z.object({}),
  execute: async (_params, { deps }: ToolContext<ShopDeps>) => deps.orders.get(deps.userId) ?? [],
});

const agent = new Agent<ShopDeps>({
  name: 'shop',
  model: 'ollama/qwen2.5:0.5b',
  instructions: 'You do not know any order until you call list_orders. Call it before every answer.',
  tools: [listOrders],
});

const cog = new Cogitator();
const orders = new Map([['alice', ['A-1 shipped']], ['bob', ['B-7 packing']]]);

for (const userId of ['alice', 'bob']) {
  const result = await cog.run(agent, {
    input: 'Check my orders with list_orders and tell me their status.',
    deps: { orders, userId },
  });
  console.log(userId, result.output);
}

await cog.close();

Run it

install · bash
pnpm add @cogitator-ai/core zod
ollama pull qwen2.5:0.5b
run · bash
npx tsx tool-deps.ts

Or run the full example from a clone of the repository (keys in .env):

repository · bash
npx tsx examples/core/20-tool-deps.ts

Learn more