Araç paketleri ve depo
Araç paketi, bir Safran örneğine ajan araçları ekleyen bir eklentidir. MCP sunucusu bunları yerleşik araçların yanına kaydeder; böylece bir ekip, hiçbir şeyi fork'lamadan ajanlarına Safran'ın sunmadığı bir araç verebilir (inceleme notları, bir sürüm kontrol listesi, iç katalogda arama). Bu sayfa bir paketi baştan sona kurar, sonra bir paketin uyduğu kuralları ve her paketin aldığı küçük kayıt deposunu anlatır.
Bir paket, örneğin okuma yüzeyi ve kendi deposuyla çalışır. Bir iş takip sistemine yazamaz, bir bağlayıcıya ulaşamaz, repoları eşitleyemez ya da örneği durduramaz: bunlar, bir işleyicinin aldığı nesnede yoktur.
Eksiksiz bir paket
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.",
}),
});Dikkat edilecek üç şey:
- Bir araç,
defineAgentToolile tamamlanan bir tanımdır: snake_case bir ad, bir başlık, model için yazılmış bir açıklama, iki zod nesne şeması ve bir işleyici. Argümanlar işleyici çalışmadan önceinputSchemaile ayrıştırılır; işleyicininstructuredolarak döndürdüğü şey dışarı çıkmadan önceoutputSchemaile ayrıştırılır. - İşleyici
textvestructureddöndürür.text, modelin okuduğu kısa gösterimdir;structuredaynı verinin nesne hâlidir. HatalarSafranErrorolarak fırlatılır. - Eklentinin kendisi
defineToolPackçağrısıdır: birtype, profil girdisi için bir yapılandırma şeması ve paketi girdiden kurancreate.createhiçbir servis almaz; böylece bir paket çevrimdışı kurulabilir, listelenebilir ve denetlenebilir.
Yükleyin ve çağırın
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(), paketleri profil sırasıyla döndürür. safran.toolPacks.call(name, args) tek bir aracı yeni bir bağlamla çalıştırır; MCP sunucusu bir paket aracının her çağrısında tam olarak bunu yapar ve güvenilmeyen veri etiketi sonucun geri kalanıyla eşleşsin diye kendi sarmalayıcısını verir.
Bir profil dosyasında paket, plugins: altında bir modül ve tool_packs: altında bir girdidir:
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 değerini siz belirlersiniz ve paketin depo ad alanına adını o verir: değiştirirseniz paketin sakladıkları sahipsiz kalır. id ve type dışındaki her şey pakete aittir ve onun kendi şemasıyla doğrulanır. Profil bir modül listelediği için CLI onu yalnızca adını verdiğiniz bir profilden ya da --allow-plugins ile yükler (bkz. eklenti modülleri ve güven).
İşleyici ne alır
/**
* 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;
}tanımlandığı yer: packages/kit/src/tools.ts
| Üye | Nedir |
|---|---|
tickets | Profildeki her iş takip sisteminde get, comments, links, history, children, search. |
code | Kod indeksi üzerinde search, grep, readFile. |
pulls | Her kod barındırıcıda list, get, changes, diff, threads. |
company | teams, glossary, conventions, expand. Çevrimdışı. |
store | Paketin kendi ad alanı: tool-pack:<entry id>. Başka bir paketin kayıtlarına ulaşamaz. |
logger | Örneğin günlükleyicisi. |
signal | İstemci çağrıyı iptal ettiğinde ya da örnek kapandığında tetiklenir. Her servis çağrısına aktarın. |
untrusted(text, source) | Üçüncü taraflere ait metni model için sarar. |
Bağlam her çağrı için yenidir ve içindeki hiçbir şey çağrıdan sonra yaşamaz: bağlamı, sinyali ya da depo tutamacını sonrası için saklamayın.
Üçüncü taraflere ait metin sarılmalıdır
İş kaydı başlıkları ve gövdeleri, yorumlar, kaynak kod, diff metni ve birinin daha önce yazdığı her şey, bir modelin talimat sanabileceği serbest metindir. text ve structured içindeki böyle her string context.untrusted üzerinden geçer; adlar, anahtarlar, yollar, sayılar ve tarihler dışarıda kalır. Sonuç başına etiketi aracı çalıştıran sunucu sağlar; işleyici kendisi sarmalayıcı kurmaz.
Bir aracın nerede çalışacağını işaretler belirler
readOnly | openWorld | Anlamı | Kaydedilir mi |
|---|---|---|---|
true | fark etmez | Hiçbir yerde hiçbir şeyi değiştirmez. | Her zaman. |
false | false | Yalnızca paketin kendi deposunu değiştirir. | Her zaman; salt okunur olmadığı dürüstçe bildirilir. |
false | true | Safran'ın dışında bir şeyi değiştirir. | Yalnızca yazma açıkken (profilde writes.enabled ve allowWrites); Safran'ın kendi yazma araçları gibi. Aksi hâlde toolPacks.call onu FORBIDDEN ile reddeder. |
destructive varsayılan olarak false değerindedir ve salt okunur araçta her zaman false olur; idempotent varsayılan olarak readOnly değerini alır. Bir paketin Safran'ın korumalı yazma işlemlerine giden bir yolu yoktur: başka bir yere yazan araç bunu kendi istemcisi ve kendi kimlik bilgileriyle yapar; önizleme ve onay yükümlülüğünü de kendisi üstlenir.
Bir paketin uyması gereken kurallar
createSafran, paketleri bağlayıcılarla birlikte ve ağ G/Ç'si olmadan kurar; şu durumlarda PLUGIN_CONFIG_INVALID ile başarısız olur:
- paket hiç araç tanımlamıyorsa ya da
create,toolslistesi olan bir nesne döndürmediyse; - bir araç
defineAgentToolile kurulmadıysa; - bir araç adı, harfle başlayan 3 ile 64 karakter arası küçük harfli snake_case değilse (
AGENT_TOOL_NAME_PATTERN); - bir paket aynı araç adını iki kez tanımlıyorsa ya da iki paket aynı adı tanımlıyorsa;
instructions,MAX_TOOL_PACK_INSTRUCTIONS_CHARS(1.000 karakter) değerinden uzunsa.
MCP sunucusu ayrıca yerleşik bir aracın adını taşıyan paket aracını reddeder. instructions, sunucu talimatlarına paketin kimliği altında eklenen isteğe bağlı metindir; eklenti yazarı tarafından yazılır ve eklentinin kodu kadar güvenilir sayılır.
Çağrı anında: bilinmeyen bir araç adı NOT_FOUND olur; inputSchema ile uyuşmayan argümanlar, sorunlu yollarla birlikte INVALID_INPUT olur; kendi outputSchema şemasının reddettiği bir şey döndüren işleyici INTERNAL olur (paketteki bir hata; asla çağıranın hatası gibi gösterilmez); SafranError olmayan bir şey fırlatan işleyici de öyle.
Depo
safran.store, string anahtarlı JSON kayıtlarından oluşan ad alanları verir; kayıtlar <dataDir>/safran.db içinde tutulur. Bir araç paketi ad alanını context.store olarak alır; kendi kodunuz herhangi bir ad alanını adıyla isteyebilir.
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| Sınır | Değer |
|---|---|
| Ad alanı adı | 1 ile 64 karakter: küçük harfler, rakamlar, ., _, :, -; harf ya da rakamla başlar (STORE_NAMESPACE_PATTERN). |
| Anahtar | Harfler, rakamlar ve ._:/@- karakterlerinden 1 ile 256 karakter (STORE_KEY_PATTERN). Bayt bayt karşılaştırılır. |
| Değer | Düz JSON; JSON metni olarak en çok MAX_STORE_VALUE_BYTES (256 KiB). undefined, fonksiyonlar, sonlu olmayan sayılar, sınıf örnekleri ve döngüler sessizce değiştirilmez, reddedilir. |
| Ad alanı başına kayıt | MAX_STORE_RECORDS (10.000). Bunun ötesinde yeni bir anahtarın put çağrısı reddedilir. |
list sayfası | DEFAULT_STORE_LIST_LIMIT (100); MAX_STORE_LIST_LIMIT (1.000) ile sınırlanır. Artan anahtar sırası; prefix daraltır. |
Her metot argümanlarını doğrular ve INVALID_INPUT fırlatır; hiçbiri kısmi sonuç döndürmez. Okumalar dosyayı asla oluşturmaz; ilk put oluşturur. get çağrısının döndürdüğü bir kopyadır.
/** 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;
}tanımlandığı yer: packages/kit/src/store.ts
Bir paketi test etmek
Test yüzeyinin tamamı safran.toolPacks.call çağrısıdır: sahte bağlayıcılar üzerine bir örnek kurun ve aracı çağırın.
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" });
});@safran/kit/testing içindeki fakeToolPackPlugin(pack) ters yönde çalışır: hazır bir ToolPack nesnesini fake türünde bir eklenti olarak sarar; paketleri listeleyen ya da sunan kodu test etmek içindir. FakeStore, gerçeğinin sınırlarını taşıyan bellek içi bir StoreService uygulamasıdır. Sahtelerle test sayfasına bakın.
Sık yapılan hatalar
- Bir iş kaydı gövdesini sarmadan döndürmek. Bir servisin serbest metin olarak döndürdüğü her şey,
textiçinde destructurediçinde decontext.untrustedüzerinden geçer. - Bir aracı "yalnızca" depoya yazıyor diye
readOnly: trueişaretlemek.putbir değişikliktir:readOnly: false, openWorld: falsekullanın. - Bağlamı bir modül değişkeninde tutmak. Tek bir çağrı için geçerlidir.
context.signaldeğerini yok saymak. İptal edilen çağrı servis çağrılarını durdurmalıdır; sinyali aktarın.- Girdinin
iddeğerini değiştirmek. Depo ad alanı kimliği izler; eski kayıtlar eski adın altında kalır. - Bir araca yerleşik bir aracın adını vermek.
search_codeadı kullanımdadır; sunucu başlamayı reddeder.