Tool packs and the store
A tool pack is a plugin that adds agent tools to a Safran instance. The MCP server registers them next to the built-in tools, so a team can give its agents a tool Safran does not ship (review notes, a release checklist, a lookup in an internal catalogue) without forking anything. This page builds one pack end to end, then covers the rules a pack lives under and the small record store every pack gets.
A pack runs with the read surface of the instance and its own store. It cannot post to a tracker, reach a connector, sync repositories or stop the instance: those are not on the object a handler receives.
A complete pack
import { defineAgentTool, defineToolPack, SafranError } from "@safran/kit";
import { z } from "zod";
const ticketKey = z.string().trim().min(1).max(64).describe("Ticket key, e.g. PAY-10.");
interface NotesConfig {
/** Most notes kept per ticket. */
maxNotes: number;
}
function tools(config: NotesConfig) {
const addReviewNote = defineAgentTool({
name: "add_review_note",
title: "Add a review note",
description: "Keeps a short note about a ticket for later review sessions. Stored on this machine only.",
inputSchema: z.object({ ticket: ticketKey, note: z.string().trim().min(1).max(2000) }),
outputSchema: z.object({ ticket: z.string(), count: z.number().int() }),
// Changes the pack's own store and nothing outside Safran: registered always, announced as not read-only.
annotations: { readOnly: false, openWorld: false },
async handler({ ticket, note }, context) {
// Proves the ticket exists and gives its canonical key. Pass the signal on to every service call.
const found = await context.tickets.get(ticket, { signal: context.signal });
const existing = await context.store.list({ prefix: `note/${found.key}/`, signal: context.signal });
if (existing.items.length >= config.maxNotes) {
throw new SafranError("INVALID_INPUT", `${found.key} already has ${config.maxNotes} notes`, { hint: "Delete one before adding another." });
}
await context.store.put(`note/${found.key}/${String(existing.items.length + 1).padStart(3, "0")}`, { note }, { signal: context.signal });
return { text: `Note ${existing.items.length + 1} kept for ${found.key}.`, structured: { ticket: found.key, count: existing.items.length + 1 } };
},
});
const listReviewNotes = defineAgentTool({
name: "list_review_notes",
title: "List review notes",
description: "Lists the notes kept for a ticket with add_review_note, oldest first.",
inputSchema: z.object({ ticket: ticketKey }),
outputSchema: z.object({ ticket: z.string(), title: z.string(), notes: z.array(z.object({ at: z.string(), note: z.string() })) }),
annotations: { readOnly: true, openWorld: false },
async handler({ ticket }, context) {
const found = await context.tickets.get(ticket, { signal: context.signal });
const page = await context.store.list({ prefix: `note/${found.key}/`, signal: context.signal });
const notes = page.items.map((record) => {
const value = record.value as { note: string };
// A note was typed by a person or a model earlier: it is free text, so it is wrapped.
return { at: record.updatedAt, note: context.untrusted(value.note, "review-note") };
});
// So is the ticket title. Keys, counts and dates stay outside the wrapper.
const title = context.untrusted(found.title, "ticket-title");
const text = [`${found.key} ${title}`, ...(notes.length === 0 ? ["No notes."] : notes.map((entry, index) => `${index + 1}. ${entry.note}`))].join("\n");
return { text, structured: { ticket: found.key, title, notes } };
},
});
return [addReviewNote, listReviewNotes];
}
export const reviewNotes = defineToolPack({
type: "review-notes",
description: "Notes kept per ticket between review sessions",
configSchema: z.strictObject({
id: z.string().min(1),
type: z.literal("review-notes"),
max_notes: z.number().int().min(1).max(100).default(20),
}),
create: (config) => ({
tools: tools({ maxNotes: config.max_notes }),
instructions: "Review notes are kept per ticket on this machine. Read them with list_review_notes before reviewing a ticket again.",
}),
});Three things to notice:
- A tool is a spec closed by
defineAgentTool: a snake_case name, a title, a description written for a model, two zod object schemas and a handler. Arguments are parsed withinputSchemabefore the handler runs; what the handler returns asstructuredis parsed withoutputSchemabefore it leaves. - A handler returns
textandstructured.textis the compact rendering a model reads;structuredis the same data as an object. Failures are thrown asSafranError. defineToolPackis the plugin: atype, a config schema for the profile entry, andcreate, which builds the pack from the entry.creategets no services, so a pack can be built, listed and checked offline.
Load it and call it
import { createSafran, defineProfile } from "@safran/core";
import { FakeTracker, fakeTrackerPlugin } from "@safran/kit/testing";
import { reviewNotes } from "./plugins/review-notes";
const profile = defineProfile({
version: 1,
company: "acme",
trackers: [{ id: "jira", type: "fake", projects: ["PAY"] }],
tool_packs: [{ id: "review-notes", type: "review-notes", max_notes: 5 }],
});
await using safran = await createSafran({
profile,
dataDir: "/work/acme/data",
// A fake tracker stands in for Jira here, so the example runs without a network.
plugins: [reviewNotes, fakeTrackerPlugin(new FakeTracker({ id: "jira", tickets: [{ key: "PAY-10", title: "[BE] Kısmi iade tutarı yuvarlanıyor" }] }))],
index: false,
});
for (const pack of safran.toolPacks.list()) {
console.log(`${pack.id} (${pack.type}): ${pack.tools.map((tool) => `${tool.name}${tool.annotations.readOnly ? "" : " [changes local state]"}`).join(", ")}`);
}
const added = await safran.toolPacks.call("add_review_note", { ticket: "pay-10", note: "Yuvarlama testi eksikti; ikinci turda bak." });
console.log(added.text);
const listed = await safran.toolPacks.call("list_review_notes", { ticket: "PAY-10" });
console.log(listed.text);
// The same records, read directly: the pack's namespace is `tool-pack:<entry id>`.
const records = await safran.store.namespace("tool-pack:review-notes").list({ prefix: "note/PAY-10/" });
console.log(records.items.map((record) => record.key));$ bun use-review-notes.ts
review-notes (review-notes): add_review_note [changes local state], list_review_notes
Note 1 kept for PAY-10.
PAY-10 <untrusted-data-5939ee70a13b0ca7 source="ticket-title">
[BE] Kısmi iade tutarı yuvarlanıyor
</untrusted-data-5939ee70a13b0ca7>
1. <untrusted-data-5939ee70a13b0ca7 source="review-note">
Yuvarlama testi eksikti; ikinci turda bak.
</untrusted-data-5939ee70a13b0ca7>
[ "note/PAY-10/001" ]safran.toolPacks.list() returns the packs in profile order. safran.toolPacks.call(name, args) runs one tool with a fresh context; an MCP server does exactly this for every call of a pack tool, passing its own wrapper so the untrusted-data tag matches the rest of the result.
From a profile file, the pack is a module under plugins: and an entry under tool_packs::
plugins:
- ./plugins/review-notes.ts
tool_packs:
- id: review-notes
type: review-notes
max_notes: 5$ safran plugins --profile /work/acme/safran.yaml
…
Tool packs tool_packs[].type
review-notes Notes kept per ticket between review sessions [from the profile's plugins, in use]
Tools of the configured packs tool_packs[]
review-notes (review-notes)
add_review_note Add a review note [changes local state]
list_review_notes List review notesid is yours and names the pack's store namespace: renaming it orphans what the pack stored. Everything besides id and type belongs to the pack and is validated by its own schema. Because the profile lists a module, the CLI loads it only from a profile you named or with --allow-plugins; see plugin modules and trust.
What a handler receives
/**
* What a tool handler receives, new for every call. Nothing in it outlives the call: a handler
* must not keep the context, the signal or the store handle for later.
*/
export interface ToolPackContext extends ToolPackServices {
/** The pack's own namespace (`toolPackNamespace(id)`). It cannot reach another pack's records. */
readonly store: StoreNamespace;
readonly logger: Logger;
/** Fires when the client cancels the call or the instance closes. Pass it on to every service call. */
readonly signal: AbortSignal;
/**
* Wraps third-party text (ticket bodies, comments, source code, anything a service above
* returned as free text) for a model. EVERY such string in `text` and in `structured` must go
* through it; names, keys, paths, numbers and dates stay outside. The server that runs the
* tool supplies the per-result tag, so a handler never builds a wrapper itself.
*/
untrusted(text: string, source: string): string;
}
/** The part of a running instance a tool pack may use. All of it is read-only. */
export interface ToolPackServices {
readonly tickets: ToolPackTickets;
readonly code: ToolPackCode;
readonly pulls: ToolPackPulls;
readonly company: ToolPackCompany;
}defined in packages/kit/src/tools.ts
| Member | What it is |
|---|---|
tickets | get, comments, links, history, children, search across every tracker of the profile. |
code | search, grep, readFile over the code index. |
pulls | list, get, changes, diff, threads across every code host. |
company | teams, glossary, conventions, expand. Offline. |
store | The pack's own namespace, tool-pack:<entry id>. It cannot reach another pack's records. |
logger | The instance's logger. |
signal | Fires when the client cancels the call or the instance closes. Pass it on to every service call. |
untrusted(text, source) | Wraps third-party text for a model. |
The context is new for every call and nothing in it outlives the call: do not keep the context, the signal or the store handle for later.
Third-party text must be wrapped
Ticket titles and bodies, comments, source code, diff text, and anything a person typed earlier are free text a model could mistake for instructions. Every such string in text and in structured goes through context.untrusted; names, keys, paths, numbers and dates stay outside. The server that runs the tool supplies the per-result tag, so a handler never builds a wrapper itself.
Annotations decide where a tool runs
readOnly | openWorld | Meaning | Registered |
|---|---|---|---|
true | either | Changes nothing anywhere. | Always. |
false | false | Changes only the pack's own store. | Always, announced honestly as not read-only. |
false | true | Changes something outside Safran. | Only while writes are enabled (profile writes.enabled and allowWrites), like Safran's own write tools. toolPacks.call refuses it with FORBIDDEN otherwise. |
destructive defaults to false and is always false for a read-only tool; idempotent defaults to the value of readOnly. A pack has no path to Safran's guarded writes: a tool that posts somewhere does it with its own client and its own credentials, and takes on the preview-and-confirm duty itself.
Rules a pack must meet
createSafran builds the packs with the connectors, without network I/O, and fails with PLUGIN_CONFIG_INVALID when:
- a pack defines no tools, or
createdid not return an object with atoolslist; - a tool was not built with
defineAgentTool; - a tool name is not lowercase snake_case of 3 to 64 characters starting with a letter (
AGENT_TOOL_NAME_PATTERN); - one pack defines a tool name twice, or two packs define the same name;
instructionsis longer thanMAX_TOOL_PACK_INSTRUCTIONS_CHARS(1,000 characters).
The MCP server additionally refuses a pack tool that has the name of a built-in tool. instructions is optional text appended to the server instructions under the pack's id; it is written by the plugin author and trusted like the plugin's code.
At call time: an unknown tool name is NOT_FOUND; arguments that do not match inputSchema are INVALID_INPUT with the offending paths; a handler that returns something its own outputSchema rejects is INTERNAL (a bug in the pack, never shown as the caller's mistake), as is a handler that throws something that is not a SafranError.
The store
safran.store hands out namespaces of JSON records with string keys, kept in <dataDir>/safran.db. A tool pack gets its namespace as context.store; your own code can ask for any namespace by name.
import { createSafran } from "@safran/core";
await using safran = await createSafran();
const drafts = safran.store.namespace("acme.drafts");
await drafts.put("draft/PAY-10/1", { title: "Yuvarlama testi", done: false });
const record = await drafts.get("draft/PAY-10/1");
console.log(record?.value, record?.updatedAt);
const page = await drafts.list({ prefix: "draft/PAY-10/", limit: 50 });
for (const item of page.items) console.log(item.key);
console.log(await drafts.delete("draft/PAY-10/1")); // true: a record was removed| Limit | Value |
|---|---|
| Namespace name | 1 to 64 characters: lowercase letters, digits, ., _, :, -, starting with a letter or digit (STORE_NAMESPACE_PATTERN). |
| Key | 1 to 256 characters from letters, digits and ._:/@- (STORE_KEY_PATTERN). Compared byte for byte. |
| Value | Plain JSON, at most MAX_STORE_VALUE_BYTES (256 KiB) as JSON text. undefined, functions, non-finite numbers, class instances and cycles are refused, not silently altered. |
| Records per namespace | MAX_STORE_RECORDS (10,000). A put of a new key beyond it is refused. |
list page | DEFAULT_STORE_LIST_LIMIT (100), clamped to MAX_STORE_LIST_LIMIT (1,000). Ascending key order; prefix narrows it. |
Every method validates its arguments and throws INVALID_INPUT; none returns a partial result. Reads never create the file; the first put does. What get returns is a copy.
/** Hands out namespaces. Two calls with the same name see the same records. */
export interface StoreService {
/** Throws INVALID_INPUT for a name that does not match `STORE_NAMESPACE_PATTERN`. Opens nothing until first use. */
namespace(name: string): StoreNamespace;
}
/**
* The records of one namespace. Keys are compared byte for byte (case-sensitive). Every method
* validates its arguments with the limits above and throws INVALID_INPUT; none returns a
* partial result.
*/
export interface StoreNamespace {
readonly namespace: string;
/** The record, or undefined when the key was never written or was deleted. */
get(key: string, options?: CallOptions): Promise<StoreRecord | undefined>;
/**
* Creates or replaces. The value is stored as its JSON text, so what `get` returns is a copy.
* With `ifUnchanged` it replaces only what the caller read (`CONFLICT` otherwise). A store that
* is busy with another process's write fails with `UPSTREAM` (`details.busy`); nothing was
* written and the call can simply be repeated.
*/
put(key: string, value: JsonValue, options?: StorePutOptions): Promise<StoreRecord>;
/** True when a record was removed, false when there was none. */
delete(key: string, options?: CallOptions): Promise<boolean>;
/** Records in ascending key order. Default limit `DEFAULT_STORE_LIST_LIMIT`, clamped to `MAX_STORE_LIST_LIMIT`. */
list(options?: StoreListOptions): Promise<Page<StoreRecord>>;
}
export interface StoreRecord {
key: string;
value: JsonValue;
/** ISO time of the `put` that wrote this value. */
updatedAt: string;
}defined in packages/kit/src/store.ts
Testing a pack
safran.toolPacks.call is the whole test surface: build an instance over fakes and call the tool.
import { expect, test } from "bun:test";
import { createSafran, defineProfile } from "@safran/core";
import { FakeTracker, fakeTrackerPlugin } from "@safran/kit/testing";
import { reviewNotes } from "./plugins/review-notes";
test("a note is kept under the ticket's canonical key", async () => {
const tracker = new FakeTracker({ id: "jira", tickets: [{ key: "PAY-10", title: "[BE] Kısmi iade tutarı yuvarlanıyor" }] });
await using safran = await createSafran({
profile: defineProfile({
version: 1,
company: "acme",
trackers: [{ id: "jira", type: "fake", projects: ["PAY"] }],
tool_packs: [{ id: "review-notes", type: "review-notes", max_notes: 1 }],
}),
dataDir: "/work/acme/test-data",
plugins: [reviewNotes, fakeTrackerPlugin(tracker)],
index: false,
});
const added = await safran.toolPacks.call("add_review_note", { ticket: "pay-10", note: "ikinci turda bak" });
expect(added.structured).toEqual({ ticket: "PAY-10", count: 1 });
// The pack's own limit, raised as a SafranError the server turns into an error result.
await expect(safran.toolPacks.call("add_review_note", { ticket: "PAY-10", note: "bir tane daha" })).rejects.toMatchObject({ code: "INVALID_INPUT" });
// Arguments are parsed with the input schema before the handler runs.
await expect(safran.toolPacks.call("add_review_note", { ticket: "PAY-10" })).rejects.toMatchObject({ code: "INVALID_INPUT" });
});fakeToolPackPlugin(pack) from @safran/kit/testing goes the other way: it wraps a ready ToolPack as a plugin of type fake, for testing code that lists or serves packs. FakeStore is an in-memory StoreService with the limits of the real one. See testing.
Common mistakes
- Returning a ticket body unwrapped. Everything a service returned as free text goes through
context.untrusted, intextand instructured. - Marking a tool
readOnly: truebecause it "only" writes to the store. Aputis a change: usereadOnly: false, openWorld: false. - Keeping the context in a module variable. It is valid for one call.
- Ignoring
context.signal. A cancelled call should stop its service calls; pass the signal on. - Renaming the entry
id. The store namespace follows the id; the old records stay under the old name. - Naming a tool like a built-in one.
search_codeis taken; the server refuses to start.