@safran/mcp
@safran/mcp, bir Safran örneğini MCP sunucusuna dönüştürür. Çoğu kullanıcı bu paketi hiç içe aktarmaz: sunucuyu safran mcp komutu ve Claude Code eklentisi sizin yerinize başlatır (MCP sunucusunu çalıştırma). Bu sayfa diğer durum içindir: sunucuyu kendi sürecinizin içinde, kendi HTTP katmanınızın arkasında, bir testte ya da farklı çıktı bütçeleriyle çalıştırmak istiyorsunuz. Paketin dışa aktardığı her şey burada belgelenir.
Her aracın ne alıp ne döndürdüğü MCP başvurusunda yer alır; bu sayfa araçların çevresindeki sunucuyu anlatır.
Eksiksiz bir örnek
Tek süreçte bir sunucu ve bir istemci, bellek içi bir taşıyıcıyla birbirine bağlı. Bir ajanın ne gördüğünü görmenin en kısa yolu budur; sunucunun üzerine kurulan her şeyi test etmenin yolu da budur. Kurulum @safran/kit/testing içindeki sahte bağlayıcıları kullanır; hiçbir çağrı ağa çıkmaz.
import { mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { createSafran, type Safran } from "@safran/core";
import { FakeCodeIndex, FakeTracker, fakePlugins } from "@safran/kit/testing";
/** A small in-memory acme: one tracker with one ticket, one indexed file. */
export async function createAcme(): Promise<Safran> {
const jira = new FakeTracker({
id: "jira",
baseUrl: "https://jira.acme.example",
tickets: [
{
key: "PAY-1423",
title: "Kısmi iade işlemi İstanbul şubesinde başarısız oluyor",
type: "Bug",
status: "Done",
statusCategory: "done",
description: "Kısmi iade 500 hatası veriyor.",
},
],
});
const index = new FakeCodeIndex({
files: { "payments-api": { "src/refund/service.ts": "export function refundPartially() {}\n" } },
groups: { backend: ["payments-api"] },
});
return createSafran({
profile: {
version: 1,
company: "acme",
languages: { tickets: "tr", code: "en" },
trackers: [{ id: "jira", type: "fake", projects: ["PAY"] }],
code: { hosts: [], groups: { backend: ["payments-api"] } },
glossary: [{ term: "İade", code: ["refund", "chargeback"] }],
embeddings: { type: "fake" },
},
builtinPlugins: false,
plugins: fakePlugins({ trackers: [jira] }),
index,
dataDir: join(mkdtempSync(join(tmpdir(), "acme-")), "data"),
});
}import { Client } from "@modelcontextprotocol/client";
import { InMemoryTransport } from "@modelcontextprotocol/server";
import { createSafranMcpServer } from "@safran/mcp";
import { createAcme } from "./acme";
const safran = await createAcme();
const server = createSafranMcpServer(safran);
const [clientSide, serverSide] = InMemoryTransport.createLinkedPair();
await server.connect(serverSide);
const client = new Client({ name: "acme-agent", version: "1.0.0" });
await client.connect(clientSide);
const { tools } = await client.listTools();
console.log(tools.map((tool) => tool.name)); // get_company_profile, who_owns, get_ticket, …
const result = await client.callTool({ name: "get_ticket", arguments: { ref: "PAY-1423" } });
console.log(result.isError === true ? "failed" : "ok");
console.log(result.content); // compact text for the model, third-party text wrapped
console.log(result.structuredContent); // the same data as an object: { tracker: "jira", key: "PAY-1423", … }
await client.close();
await server.close();
await safran.close(); // the server does not own the instanceBu çıktının üzerine bir şey kurmadan önce iki noktayı bilmek gerekir. Başarısız olan bir araç hata fırlatmaz: callTool, isError: true ve tek satırlık bir iletiyle sonuçlanır; iletiyi çoğu zaman bir → ipucu izler (Ticket PAY-9999 not found in jira ve sırada ne deneneceği) ve metin her zaman [code: NOT_FOUND] makine etiketiyle biter. Üçüncü tarafların yazdığı metin ise hem content hem structuredContent içinde <untrusted-data-…> etiketleriyle sarmalanmış olarak gelir; sarmalayıcıyı güvenlik sayfası anlatır.
Paketin dışa aktardıkları
| Dışa aktarım | Tür | Ne olduğu |
|---|---|---|
createSafranMcpServer, SafranMcpServerOptions | fonksiyon, tür | Bir örnek üzerindeki sunucu. |
serveSafranStdio, SafranStdioOptions, SafranStdioHandle | fonksiyon, türler | stdin/stdout üzerinden sunum. |
createSafranHttpHandler, SafranHttpHandlerOptions, SafranHttpHandler | fonksiyon, türler | Streamable HTTP için bir fetch işleyicisi. |
SAFRAN_TOOLS, SAFRAN_WRITE_TOOLS, SafranTool, ToolAnnotationHints | sabitler, türler | Sunucunun okuma araçları ve iki yazma aracı, veri olarak. |
SERVER_NAME, DEFAULT_SERVER_VERSION | sabitler | Sunucunun istemcilere bildirdiği ad ve sürüm. |
SERVER_INSTRUCTIONS, MAX_INSTRUCTIONS_CHARS, READ_ONLY_INSTRUCTIONS, WRITE_INSTRUCTIONS, buildServerInstructions, ServerInstructionsOptions, BuiltInstructions | sabitler, fonksiyon, türler | Başlatma sırasında gönderilen yönergeler ve nasıl bir araya getirildikleri. |
errorTag | fonksiyon | Her hata metnini bitiren [code: NAME] satırı. |
OutputBudgets, DEFAULT_OUTPUT_BUDGETS, DEFAULT_*_MAX_CHARS ve benzerleri | tür, sabitler | Her aracın en çok ne kadar metin döndürebileceği. |
DEFAULT_*_LIMIT, DEFAULT_MAX_*_LIMIT | sabitler | Liste araçlarının varsayılan ve en büyük limit değerleri. |
DEFAULT_HTTP_PATH, HEALTH_PATH, DEFAULT_HTTP_MAX_BODY_BYTES, DEFAULT_HTTP_MIN_TOKEN_CHARS | sabitler | HTTP işleyicisinin varsayılanları. |
createStderrLogger | fonksiyon | stdout'a asla yazmayan bir günlükleyici. |
sniffAttachment, SniffedAttachment | fonksiyon, tür | Bir ekin baytlarının nasıl sınıflandırıldığı. |
Paket @modelcontextprotocol/server paketine bağımlıdır; createSafranMcpServer o SDK'nın McpServer nesnesini döndürür.
createSafranMcpServer
/**
* The MCP server over a Safran instance. It holds no logic of its own: every tool is one
* Safran call rendered for a model. The instance is not closed with the server; whoever
* created it owns it, and one instance can back many servers (one per HTTP request).
*
* What is registered is decided here, once, from the instance: the read tools always, the two
* write tools only while writes are enabled, then the tools of every tool pack. A profile change
* (enabling writes, adding a pack) therefore needs a new instance and a new server: a restart.
* Throws PLUGIN_CONFIG_INVALID when a tool pack's tool has the name of a built-in tool.
*/
export function createSafranMcpServer(safran: Safran, options: SafranMcpServerOptions = {}): McpServer;tanımlandığı yer: packages/mcp/src/server.ts
SERVER_NAME adında bir McpServer kurar ve araçları kaydeder: SAFRAN_TOOLS içindeki her aracı her zaman, SAFRAN_WRITE_TOOLS içindeki iki aracı yalnızca safran.writes.status().enabled doğruyken, ardından örneğin yüklediği her araç paketinin araçlarını. Gönderdiği yönergeler tam olarak bu küme için kurulur. Neyin kaydedileceğine burada, bir kez karar verilir: bir profil değişikliği (yazmayı açmak, bir paket eklemek) yeni bir örnek ve yeni bir sunucu gerektirir. Sunucunun kendine ait bir mantığı yoktur: her araç, model için biçimlendirilmiş tek bir Safran çağrısıdır. Hiçbir şeye bağlanmaz; MCP SDK'sının bir taşıyıcısıyla server.connect(transport) çağırın ya da aşağıdaki iki yardımcıyı kullanın.
Sunucu Safran örneğini asla kapatmaz. Örneği kim oluşturduysa sahibi odur ve tek bir örnek birçok sunucuya hizmet edebilir; HTTP işleyicisi her istek için bir sunucu oluşturur.
Dönüş değeri bir McpServer nesnesidir. Fırlattığı hata PLUGIN_CONFIG_INVALID olur: bir araç paketinin aracı yerleşik bir aracın (kayıtlı olsun olmasın iki yazma aracı dâhil) ya da başka bir paketin aracının adını taşıyorsa veya şemaları yayımlanamıyorsa.
| Seçenek | Tür | Varsayılan | Anlamı |
|---|---|---|---|
version | string | DEFAULT_SERVER_VERSION | İstemcilere bildirilen sürüm. |
budgets | Partial<OutputBudgets> | DEFAULT_OUTPUT_BUDGETS | Değiştirilecek çıktı bütçeleri; gerisi varsayılanını korur. |
logger | Logger | createStderrLogger(): uyarılar ve hatalar stderr'e | Başarısızlıkların günlüğe yazıldığı yer. Asla stdout değil. |
now | () => Date | () => new Date() | Metin çıktısındaki göreli süreler ("9 months ago") için kullanılan saat. Testlerde sabitleyin. |
export const SERVER_NAME = "safran";
export const DEFAULT_SERVER_VERSION: string = SAFRAN_VERSION;import { createSafranMcpServer } from "@safran/mcp";
import { createAcme } from "./acme";
const safran = await createAcme();
const server = createSafranMcpServer(safran, {
version: "2026.11.0",
// Show fewer comments inline and shorter snippets; everything else keeps its default.
budgets: { ticketInlineComments: 3, snippetChars: 2_000 },
now: () => new Date("2026-11-23T12:00:00Z"),
});
console.log(server.isConnected()); // false: nothing is served until a transport is connected
await safran.close();serveSafranStdio
/**
* Serves a Safran instance over stdio. stdout carries JSON-RPC frames and nothing else:
* the default logger writes to stderr and the console is redirected for the duration.
*/
export function serveSafranStdio(safran: Safran, options: SafranStdioOptions = {}): SafranStdioHandle;tanımlandığı yer: packages/mcp/src/stdio.ts
Örneği stdin/stdout üzerinden sunar ve hemen bir tutamaçla döner. stdout yalnızca JSON-RPC çerçevelerini taşır: varsayılan günlükleyici stderr'e yazar ve sunucu çalıştığı sürece console.log, console.info ve console.debug stderr'e yönlendirilir; çünkü stdout'a düşen tek bir başıboş satır istemci için protokol akışını bozar.
SafranStdioOptions, SafranMcpServerOptions türünü şununla genişletir:
| Seçenek | Tür | Varsayılan | Anlamı |
|---|---|---|---|
guardConsole | boolean | true | Sunum sırasında console.log / info / debug çağrılarını stderr'e yönlendirir. |
| Üye | Tür | Anlamı |
|---|---|---|
close | () => Promise<void> | Sunumu durdurur ve konsolu geri verir. Safran örneğini kapatmaz. |
Taşıyıcı hataları error düzeyinde günlüğe yazılır; hata olarak fırlatılmaz.
import { createSafran } from "@safran/core";
import { serveSafranStdio } from "@safran/mcp";
const safran = await createSafran({ profile: "/work/acme/safran.yaml" });
const handle = serveSafranStdio(safran, { version: "1.0.0" });
const stop = async (): Promise<void> => {
await handle.close();
await safran.close();
process.exit(0);
};
process.once("SIGINT", stop);
process.once("SIGTERM", stop);
// A client ends the session by closing stdin.
process.stdin.once("close", stop);Claude Code'a herhangi bir stdio sunucusu gibi, betiğinizin mutlak yoluyla kaydedin: claude mcp add --transport stdio acme -- bun /work/acme/serve-stdio.ts.
createSafranHttpHandler
createSafranHttpHandler(safran: Safran, options?: SafranHttpHandlerOptions): SafranHttpHandler
export interface SafranHttpHandlerOptions extends SafranMcpServerOptions {
/**
* Static bearer token. When set, every request except the health check must carry
* `Authorization: Bearer <token>`. An empty string is refused rather than read as "no auth",
* so an unset environment variable cannot open the server by accident; so is one shorter than
* `minTokenChars` or containing whitespace (it could never be presented in the header).
*/
token?: string;
/** Shortest `token` accepted. Default: `DEFAULT_HTTP_MIN_TOKEN_CHARS`. */
minTokenChars?: number;
/** Hostnames accepted in the `Host` header, without port. Default: localhost, 127.0.0.1, [::1]. */
allowedHosts?: string[];
/** Hostnames accepted in a browser's `Origin` header. Default: localhost, 127.0.0.1, [::1]. */
allowedOrigins?: string[];
/** Path the endpoint is served at, with or without a trailing slash. Default: `/mcp`. */
path?: string;
/** Largest request body accepted, in bytes. Default: `DEFAULT_HTTP_MAX_BODY_BYTES`. */
maxBodyBytes?: number;
}
export interface SafranHttpHandler {
/** For `Bun.serve({ fetch })`. Never rejects. */
fetch(request: Request): Promise<Response>;
/** Aborts in-flight requests. Does not close the Safran instance. */
close(): Promise<void>;
}tanımlandığı yer: packages/mcp/src/http.ts
Streamable HTTP taşıyıcısı için fetch biçiminde bir işleyici döndürür. Durumsuzdur: her istek, paylaşılan örnek üzerinde taze bir MCP sunucusu alır; süresi dolacak oturum yoktur. Bir portu dinlemez; handler.fetch fonksiyonunu Bun.serve çağrısına verin ya da kendi yönlendiricinize bağlayın.
| Seçenek | Tür | Varsayılan | Anlamı |
|---|---|---|---|
token | string | yok (kimlik doğrulama yok) | Sabit bearer token'ı. Verildiğinde, sağlık denetimi dışındaki her istek Authorization: Bearer <token> göndermelidir. Boş string reddedilir; minTokenChars değerinden kısa olan, boşluk içeren ya da görünür ASCII dışında karakter taşıyan bir string de reddedilir. |
minTokenChars | number | DEFAULT_HTTP_MIN_TOKEN_CHARS (16) | Kabul edilen en kısa token. |
allowedHosts | string[] | localhost, 127.0.0.1, [::1] | Host başlığında kabul edilen ana makine adları, portsuz. |
allowedOrigins | string[] | localhost, 127.0.0.1, [::1] | Bir tarayıcının Origin başlığında kabul edilen ana makine adları. |
path | string | DEFAULT_HTTP_PATH (/mcp) | Uç noktanın sunulduğu yol. Hem path hem path/ yönlendirme olmadan doğrudan yanıt verir. |
maxBodyBytes | number | DEFAULT_HTTP_MAX_BODY_BYTES (1 MiB) | Kabul edilen en büyük istek gövdesi. |
Ayrıca SafranMcpServerOptions türünün bütün seçeneklerini alır (version, budgets, logger, now).
| Üye | Tür | Anlamı |
|---|---|---|
fetch | (request: Request) => Promise<Response> | Tek bir isteği yanıtlar. Asla reddetmez: beklenmeyen bir hata günlüğe yazılır ve 500 ile yanıtlanır. |
close | () => Promise<void> | Süren istekleri iptal eder. Safran örneğini kapatmaz. |
export const DEFAULT_HTTP_PATH = "/mcp";
export const HEALTH_PATH = "/healthz";
/** Tool calls are a few hundred bytes of JSON; 1 MiB leaves room for batches and long cursors. */
export const DEFAULT_HTTP_MAX_BODY_BYTES = 1_048_576;
/** Shortest bearer token accepted: the kit's `MIN_BEARER_TOKEN_CHARS`, which the dashboard server requires too. */
export const DEFAULT_HTTP_MIN_TOKEN_CHARS = MIN_BEARER_TOKEN_CHARS;Fırlattığı hata seçenekler anlamsızsa INVALID_INPUT olur: boş bir token (tanımsız bir ortam değişkeni sunucuyu yanlışlıkla açamasın diye), fazla kısa ya da bir başlıkta taşınamayacak bir token, en az 1 olan bir tam sayı olmayan minTokenChars, mutlak olmayan ya da ? veya # içeren bir path, /healthz değerine eşit bir path, pozitif bir sayı olmayan maxBodyBytes.
Bir isteğin geçtiği denetimler
Denetimler bu sırayla çalışır; başarısız olan ilk denetim yanıtı verir.
| # | Denetim | Başarısız olursa yanıt |
|---|---|---|
| 1 | Host başlığı izin verilen bir ana makine adını taşıyor | 403, JSON-RPC hatası The Host header is missing or not an allowed host name. Başlık yankılanmaz. |
| 2 | Origin başlığı varsa, izin verilen bir ana makine adını taşıyor | 403, JSON-RPC hatası Requests from this Origin are not allowed. |
| 3 | /healthz üzerinde GET ya da HEAD | burada yanıtlanır: gövdesi ok olan 200, kimlik doğrulama yok |
| 4 | token verilmişse: Authorization: Bearer <token> eşleşiyor (sabit zamanlı karşılaştırma) | 401 {"error":"unauthorized",…} ve WWW-Authenticate: Bearer realm="safran" başlığı |
| 5 | Yol path ya da path/ | 404 {"error":"not_found"} |
| 6 | Bildirilen Content-Length düz bir bayt sayısı ve en çok maxBodyBytes | 400 {"error":"bad_request",…} ya da 413 {"error":"payload_too_large",…} |
| 7 | İsteği MCP taşıyıcısı işler | örneğin uç noktaya GET için 405 |
- ve 2. denetim birlikte, localhost'a bağlı bir sunucu için DNS rebinding savunmasıdır. CORS başlığı hiç gönderilmez; bu yüzden bir tarayıcı başka bir kökenden yanıtları okuyamaz. İşleyicinin kendi ürettiği her yanıt
Cache-Control: no-storeveX-Content-Type-Options: nosnifftaşır.
import { createSafran } from "@safran/core";
import { createSafranHttpHandler, DEFAULT_HTTP_PATH, HEALTH_PATH } from "@safran/mcp";
const safran = await createSafran({ profile: "/work/acme/safran.yaml" });
const token = process.env.SAFRAN_MCP_TOKEN;
const handler = createSafranHttpHandler(safran, {
// `exactOptionalPropertyTypes`: leave the key out instead of passing undefined.
...(token === undefined ? {} : { token }),
});
const server = Bun.serve({ hostname: "127.0.0.1", port: 3939, fetch: (request) => handler.fetch(request) });
console.error(`MCP endpoint: http://127.0.0.1:${server.port}${DEFAULT_HTTP_PATH} health: ${HEALTH_PATH}`);
process.once("SIGINT", async () => {
await handler.close();
await server.stop();
await safran.close();
});İşleyici Request alıp Response döndüren bir fonksiyon olduğu için port açmadan test edilebilir. Kodda oluşturulan bir Request nesnesinin Host başlığı yoktur; siz ekleyin:
import { expect, test } from "bun:test";
import { createSafranHttpHandler } from "@safran/mcp";
import { createAcme } from "./acme";
test("the endpoint needs the bearer token, the health check does not", async () => {
const safran = await createAcme();
const handler = createSafranHttpHandler(safran, { token: "s3cret-token" });
const host = { host: "localhost:3939" };
const health = await handler.fetch(new Request("http://localhost:3939/healthz", { headers: host }));
expect(health.status).toBe(200);
const anonymous = await handler.fetch(new Request("http://localhost:3939/mcp", { method: "POST", headers: host, body: "{}" }));
expect(anonymous.status).toBe(401);
const listed = await handler.fetch(
new Request("http://localhost:3939/mcp", {
method: "POST",
headers: { ...host, authorization: "Bearer s3cret-token", "content-type": "application/json", accept: "application/json, text/event-stream" },
body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list" }),
}),
);
expect(listed.status).toBe(200);
expect(await listed.text()).toContain("get_company_profile");
await handler.close();
await safran.close();
});Araç listesi
/** Every read tool of the server, in the order of docs/MCP-TOOLS.md. Registered on every server. */
export const SAFRAN_TOOLS: readonly SafranTool[] = [...companyTools, ...ticketTools, ...codeTools, ...historyTools, ...pullTools, ...workTools];
/** A tool ready to be put on a server. The generics of its spec are closed over. */
export interface SafranTool {
readonly name: string;
readonly title: string;
readonly description: string;
readonly inputSchema: z.ZodType;
readonly outputSchema: z.ZodType;
readonly annotations: ToolAnnotationHints;
readonly meta?: Record<string, unknown>;
register(server: McpServer, env: ToolEnv): void;
}tanımlandığı yer: packages/mcp/src/server.ts, packages/mcp/src/tools/shared.ts
Sunucunun bütün okuma araçları, veri olarak ve sunucunun kaydettiği sırayla; SAFRAN_WRITE_TOOLS ise yazma açıkken sunucunun onların ardından kaydettiği preview_write ve commit_write araçlarını tutar. Dokümantasyon üretmek, bir testte bir aracın var olduğunu doğrulamak ya da araçları kendi yapılandırdığınız bir McpServer üzerine kaydetmek için kullanın.
| Üye | Tür | Anlamı |
|---|---|---|
name | string | Araç adı; iş takip sisteminden bağımsız (get_ticket). |
title | string | İnsanın okuyacağı başlık. |
description | string | Modelin okuduğu açıklama. |
inputSchema | z.ZodType | Argümanların zod şeması. |
outputSchema | z.ZodType | structuredContent için zod şeması. |
annotations | ToolAnnotationHints | Dört ipucunun dördü de her zaman gönderilir. SAFRAN_TOOLS içindeki araçlar salt okunur ve idempotenttir; iki yazma aracı ikisi de değildir. openWorldHint, araç bir iş takip sistemine, kod barındırıcıya ya da wiki'ye ulaşıyorsa true, yerel indeksi, bağlantı deposunu ya da profili okuyorsa false olur. |
meta | Record<string, unknown> (isteğe bağlı) | tools/list içinde yayımlanan _meta. |
register | (server: McpServer, env: ToolEnv) => void | Aracı bir sunucuya yerleştirir. createSafranMcpServer bunu sizin yerinize çağırır. |
Araçlar ve her birini belgeleyen MCP başvurusu bölümü:
| Araç | Ağa çıkar mı | Başvuru |
|---|---|---|
get_company_profile, who_owns, get_server_info | hayır | Şirket ve sunucu |
get_ticket, get_ticket_comments, get_ticket_attachment, get_ticket_history, search_tickets, fetch_linked_doc | evet | İş kayıtları |
get_ticket_family, get_linked_work, get_ticket_changes, get_ticket_time | evet | İş kaydı derinliği |
search_code, grep_code, read_file | hayır | Kod |
list_repos | yalnızca check_remote ile (ve bir sürecin ilk repo listelemesinde) | Kod |
find_past_work | hayır | Geçmiş |
find_pull_request, list_pull_requests, get_pull_request, get_pull_request_threads, get_pull_request_diff | evet | Pull request'ler |
preview_write, commit_write (SAFRAN_WRITE_TOOLS içinde) | evet; commit_write uzak sistemi değiştirir | Yazma |
import { SAFRAN_TOOLS, SAFRAN_WRITE_TOOLS } from "@safran/mcp";
for (const tool of [...SAFRAN_TOOLS, ...SAFRAN_WRITE_TOOLS]) {
const kind = tool.annotations.readOnlyHint ? "read " : "WRITE";
console.log(tool.name.padEnd(26), kind, tool.annotations.openWorldHint ? "network" : "local ", tool.title);
}Sunucu yönergeleri
/** The instructions of a default install: read-only, no tool packs. */
export const SERVER_INSTRUCTIONS = buildServerInstructions().text;
/** Clients cap server instructions; Claude Code cuts them at 4,096 characters. */
export const MAX_INSTRUCTIONS_CHARS = 4096;
/**
* Sent once at initialisation. With tool search on, a client loads only tool names plus this
* text at session start, so the sentence that matters most comes first and the rest is short.
* Nothing here names a company: everything company-specific comes from `get_company_profile`.
* The write paragraph depends on whether the write tools exist on this server: an agent told
* about tools it does not have looks for them, and one not told the rule would not follow it.
*
* Tool packs get what is left under the cap, in registration order: each pack's paragraph is
* added whole when it fits and left out whole when it does not (never cut mid-sentence), and a
* later, shorter one may still fit. What was left out is returned, so the server can say it
* (`get_server_info`, the log) instead of an agent silently missing a pack's rules.
*/
export function buildServerInstructions(options: ServerInstructionsOptions = {}): BuiltInstructions;
export interface ServerInstructionsOptions {
/** True when `preview_write` and `commit_write` are registered. Default false. */
writes?: boolean;
/** Guidance of the loaded tool packs, in registration (profile) order. */
toolPacks?: readonly { id: string; instructions?: string | undefined }[];
}
export interface BuiltInstructions {
text: string;
/** Ids of tool packs whose instructions did not fit under `MAX_INSTRUCTIONS_CHARS`. */
omitted: string[];
/** The same packs, with what each needed and what was left. */
omittedPacks: OmittedPackInstructions[];
}tanımlandığı yer: packages/mcp/src/instructions.ts
İstemciye bir kez, başlatma sırasında gönderilen metin. Ajana önce get_company_profile aracını çağırmasını, güvenilmeyen veriye nasıl davranacağını, kod hakkındaki iddialar için kanıt kuralını, hangi aracın ne için kullanılacağını ve Safran'ın burada salt okunur olduğunu (READ_ONLY_INSTRUCTIONS) ya da yazma kuralını (WRITE_INSTRUCTIONS) söyler. Hiçbir şirketin adını anmaz: şirkete özgü her şey get_company_profile aracından gelir.
MAX_INSTRUCTIONS_CHARS, metnin altında kalması gereken uzunluktur; çünkü istemciler sunucu yönergelerini keser. SERVER_INSTRUCTIONS, varsayılan bir kurulumun metnidir: salt okunur, araç paketi yok. createSafranMcpServer, buildServerInstructions fonksiyonunu örneğin gerçekten sahip olduklarıyla çağırır; böylece yazmanın açık olduğu bir sunucu yazma kuralını gönderir ve her araç paketinin instructions metni, sığdığı sürece TOOL PACK <id>: altında eklenir. Metni sığmayan bir paket bütün hâlinde dışarıda bırakılır ve omitted içinde adı verilir. Temel metin seçeneklerle değiştirilemez; farklı yönergelere ihtiyaç duyan bir sunucu araçları kendi McpServer nesnesine kaydeder.
import { buildServerInstructions, MAX_INSTRUCTIONS_CHARS, SERVER_INSTRUCTIONS } from "@safran/mcp";
console.log(SERVER_INSTRUCTIONS.length <= MAX_INSTRUCTIONS_CHARS); // true
console.log(SERVER_INSTRUCTIONS.split("\n")[0]);
// The text a server with writes enabled and one tool pack would send.
const built = buildServerInstructions({
writes: true,
toolPacks: [{ id: "acme-release", instructions: "Call release_notes before proposing a release." }],
});
console.log(built.text.endsWith("TOOL PACK acme-release: Call release_notes before proposing a release."));
console.log(built.omitted); // ids of packs whose text did not fit under the capÇıktı bütçeleri
export interface OutputBudgets {
profileChars: number;
titleChars: number;
ticketDescriptionChars: number;
ticketFieldsChars: number;
ticketFieldChars: number;
ticketInlineComments: number;
ticketInlineCommentsChars: number;
ticketLinks: number;
ticketLinksChars: number;
ticketAttachments: number;
ticketAttachmentsChars: number;
commentChars: number;
commentsChars: number;
historyValueChars: number;
historyChars: number;
attachmentTextChars: number;
attachmentImageBytes: number;
docChars: number;
snippetChars: number;
searchCodeChars: number;
alsoIn: number;
grepLineChars: number;
grepChars: number;
readFileChars: number;
listRepos: number;
pastWorkFilesPerRecord: number;
prDescriptionChars: number;
prChanges: number;
prThreadFiles: number;
reviewCommentChars: number;
threadsChars: number;
threadLatestComments: number;
threadFullComments: number;
diffFileChars: number;
diffChars: number;
linkedBodyChars: number;
ticketListChars: number;
worklogNoteChars: number;
worklogsChars: number;
changesCommentsChars: number;
changesRows: number;
tableColumns: number;
tableCellChars: number;
workRowsChars: number;
}tanımlandığı yer: packages/mcp/src/tools/shared.ts
Her araç döndürdüğünü sınırlar. Bütçeler, adı aksini söylemedikçe üçüncü taraf metninin karakter sayısıyla ölçülür. Bütçeyi aşan metin satır sınırında kesilir ve gerisinin nasıl alınacağını söyleyen açık bir işaret konur; hiçbir şey sessizce kesilmez. Herhangi birini SafranMcpServerOptions.budgets ile değiştirebilirsiniz.
export const DEFAULT_OUTPUT_BUDGETS: OutputBudgets; // defined in packages/mcp/src/tools/shared.ts| Bütçe | Varsayılan sabit | Değer | Neyi sınırlar |
|---|---|---|---|
profileChars | DEFAULT_PROFILE_MAX_CHARS | 24.000 | Profilin tamamının metin gösterimi (get_company_profile). |
titleChars | DEFAULT_TITLE_MAX_CHARS | 300 | Tek bir başlık: iş kaydı, sayfa, pull request. |
ticketDescriptionChars | DEFAULT_TICKET_DESCRIPTION_MAX_CHARS | 16.000 | Tek bir iş kaydının açıklaması. |
ticketFieldsChars | DEFAULT_TICKET_FIELDS_MAX_CHARS | 6.000 | Tek bir iş kaydının iş takip sistemine özgü bütün alanları birlikte. |
ticketFieldChars | DEFAULT_TICKET_FIELD_MAX_CHARS | 3.000 | İş takip sistemine özgü tek bir alan. |
ticketInlineComments | DEFAULT_TICKET_INLINE_COMMENTS | 10 | get_ticket aracının gösterdiği yorum sayısı; gerisi bir get_ticket_comments çağrısı uzaklıktadır. |
ticketInlineCommentsChars | DEFAULT_TICKET_INLINE_COMMENTS_MAX_CHARS | 8.000 | Bu satır içi yorumların toplamı. |
ticketLinks | DEFAULT_TICKET_LINKS_MAX | 50 | Tek bir iş kaydı için listelenen bağlantı sayısı. |
ticketLinksChars | DEFAULT_TICKET_LINKS_MAX_CHARS | 6.000 | O bağlantı listesinin gösterim boyutu. |
ticketAttachments | DEFAULT_TICKET_ATTACHMENTS_MAX | 50 | Tek bir iş kaydı için listelenen ek sayısı. |
ticketAttachmentsChars | DEFAULT_TICKET_ATTACHMENTS_MAX_CHARS | 4.000 | O ek listesinin gösterim boyutu. |
commentChars | DEFAULT_COMMENT_MAX_CHARS | 6.000 | Tek bir yorum. |
commentsChars | DEFAULT_COMMENTS_MAX_CHARS | 16.000 | get_ticket_comments aracının bir sayfası. Sığmayan yorumlar bütün olarak sonraki imlece geçer. |
historyValueChars | DEFAULT_HISTORY_VALUE_MAX_CHARS | 300 | get_ticket_history içindeki tek bir eski ya da yeni değer. |
historyChars | DEFAULT_HISTORY_MAX_CHARS | 12.000 | get_ticket_history aracının bir sayfası. |
attachmentTextChars | DEFAULT_ATTACHMENT_TEXT_MAX_CHARS | 40.000 | Bir metin eki (get_ticket_attachment). |
attachmentImageBytes | DEFAULT_ATTACHMENT_IMAGE_MAX_BYTES | 3.500.000 | Görsel bloğu olarak döndürülen en büyük görsel, bayt cinsinden. |
docChars | DEFAULT_DOC_MAX_CHARS | 40.000 | fetch_linked_doc aracından gelen bir sayfa. |
snippetChars | DEFAULT_SNIPPET_MAX_CHARS | 4.000 | Tek bir search_code sonucunun kod parçası. |
searchCodeChars | DEFAULT_SEARCH_CODE_MAX_CHARS | 16.000 | Tek bir search_code çağrısındaki bütün kod parçaları. Bunu aşan sonuçlar konumlarını korur, kod parçalarını yitirir. |
alsoIn | DEFAULT_ALSO_IN_MAX | 5 | Tek bir sonucun altında adı verilen yinelenen konumlar. |
grepLineChars | DEFAULT_GREP_LINE_MAX_CHARS | 300 | grep_code aracının eşleşen tek bir satırı. |
grepChars | DEFAULT_GREP_MAX_CHARS | 12.000 | Tek bir grep_code çağrısının bütün satırları. |
readFileChars | DEFAULT_READ_FILE_MAX_CHARS | 60.000 | Tek bir read_file çağrısının içeriği. |
listRepos | DEFAULT_LIST_REPOS_MAX | 500 | list_repos aracının döndürdüğü repo sayısı. |
pastWorkFilesPerRecord | DEFAULT_PAST_WORK_FILES_PER_RECORD | 30 | find_past_work içinde pull request başına listelenen değişen dosya sayısı. |
prDescriptionChars | DEFAULT_PR_DESCRIPTION_MAX_CHARS | 8.000 | Bir pull request'in açıklaması. |
prChanges | DEFAULT_PR_CHANGES_MAX | 60 | get_pull_request aracının listelediği değişen dosya sayısı. |
prThreadFiles | DEFAULT_PR_THREAD_FILES_MAX | 30 | get_pull_request aracının yorum dizisi sayılarıyla listelediği dosya sayısı. |
reviewCommentChars | DEFAULT_REVIEW_COMMENT_MAX_CHARS | 3.000 | Tek bir inceleme yorumu. |
threadsChars | DEFAULT_THREADS_MAX_CHARS | 16.000 | get_pull_request_threads sonucunun bir sayfası. Sığmayan yorum dizileri bütün hâlinde sonraki imlece geçer. |
threadLatestComments | DEFAULT_THREAD_LATEST_COMMENTS | 9 | Yorum dizisi başına, ilk yorumdan sonra gösterilen son yorum sayısı. |
threadFullComments | DEFAULT_THREAD_FULL_COMMENTS | 60 | Tek bir yorum dizisi thread_id ile istendiğinde gösterilen son yorum sayısı. |
diffFileChars | DEFAULT_DIFF_FILE_MAX_CHARS | 24.000 | get_pull_request_diff içinde tek bir dosyanın yaması. |
diffChars | DEFAULT_DIFF_MAX_CHARS | 60.000 | get_pull_request_diff sonucunun bir sayfasındaki bütün yamalar. |
linkedBodyChars | DEFAULT_LINKED_BODY_MAX_CHARS | 2.000 | get_linked_work içinde tek bir engelleyici iş kaydının ya da karşı taraftaki kaydın açıklaması. |
ticketListChars | DEFAULT_TICKET_LIST_MAX_CHARS | 10.000 | get_ticket_family ve get_linked_work içinde tek bir iş kaydı listesinin başlıkları. |
worklogNoteChars | DEFAULT_WORKLOG_NOTE_MAX_CHARS | 500 | Tek bir çalışma günlüğünün notu. |
worklogsChars | DEFAULT_WORKLOGS_MAX_CHARS | 10.000 | Bir get_ticket_time çağrısının bütün çalışma günlüğü notları. |
changesCommentsChars | DEFAULT_CHANGES_COMMENTS_MAX_CHARS | 8.000 | Bir get_ticket_changes çağrısının yorumları. |
changesRows | DEFAULT_CHANGES_ROWS_MAX | 40 | get_ticket_changes içinde liste başına satır sayısı; en sonuncular korunur. |
tableColumns | DEFAULT_TABLE_MAX_COLUMNS | 50 | get_ticket_attachment aracının gösterdiği hesap tablosu sütun sayısı. |
tableCellChars | DEFAULT_TABLE_CELL_MAX_CHARS | 500 | Tek bir hesap tablosu hücresi. |
workRowsChars | DEFAULT_WORK_ROWS_MAX_CHARS | 36.000 | Tek bir iş aracı sonucundaki iş kaydı satırları; bütün sütunlar ve bölümler birlikte. |
Boyutların gerekçesi kaynak kodda yazılıdır: araç sonucu başına kabaca 10.000 token üzerinde uyarı veren Claude Code'a göre ayarlanmıştır ve üçüncü taraf metni iki kez taşınır (metinde ve yapılandırılmış kopyada); bu yüzden liste araçları bunun yarısının epey altında kalır.
Dışa aktarılan beş sabit daha çıktıyı sınırlar ama OutputBudgets içinde yer almaz; yani sunucu başına değiştirilemez:
/** One piece of metadata (a name, a label, a status). */
export const DEFAULT_INLINE_MAX_CHARS = 200;
/** Symbols named in a hit's header line; a chunk can define ten. The data keeps all of them. */
export const DEFAULT_HIT_SYMBOLS_SHOWN = 3;
/**
* `_meta["anthropic/maxResultSizeChars"]` of `read_file`: numbered text plus the structured
* copy of a full budget, so an asked-for range is never spilled to a file by the client.
*/
export const DEFAULT_READ_FILE_RESULT_SIZE_CHARS = 160_000;
/**
* `_meta["anthropic/maxResultSizeChars"]` of `get_pull_request_diff`, for the reason `read_file`
* has one: a diff the agent asked for is reviewed line by line, and a client that spills it to a
* file breaks that. Patch text is carried twice (text and structured), so this is a full budget
* twice plus headers.
*/
export const DEFAULT_DIFF_RESULT_SIZE_CHARS = 160_000;
/** Longest message or hint line shown to the agent. Real ones are a sentence or two. */
export const DEFAULT_ERROR_LINE_MAX_CHARS = 1_000;Liste araçlarının sınırları
Her liste aracının kabul ettiği varsayılan ve en büyük limit değeri. Bunlar sabittir; en büyük değerden fazlasını isteyen bir araç çağrısını aracın girdi şeması reddeder.
export const DEFAULT_SEARCH_CODE_LIMIT = 8;
/**
* This tool's own cap, for the agent's context: 30 hits with snippets are already more than a
* model reads well. It can never promise more than the index serves (`DEFAULT_MAX_SEARCH_LIMIT`).
*/
export const DEFAULT_MAX_SEARCH_CODE_LIMIT = Math.min(30, DEFAULT_MAX_SEARCH_LIMIT);
export const DEFAULT_GREP_CODE_LIMIT = 50;
/** The index's own maxima (`@safran/codeindex`), under the tool's names: what the schema advertises is what the index returns. */
export const DEFAULT_MAX_GREP_CODE_LIMIT = DEFAULT_MAX_GREP_LIMIT;
export const DEFAULT_MAX_GREP_CODE_CONTEXT = DEFAULT_MAX_GREP_CONTEXT;export const DEFAULT_SEARCH_TICKETS_LIMIT = 20;
/** This tool's own cap, far below core's `DEFAULT_MAX_TICKET_SEARCH_LIMIT`: a page is read by a model, not exported. */
export const DEFAULT_MAX_SEARCH_TICKETS_LIMIT = 50;
export const DEFAULT_COMMENTS_LIMIT = 30;
export const DEFAULT_MAX_COMMENTS_LIMIT = 100;
export const DEFAULT_HISTORY_LIMIT = 50;
export const DEFAULT_MAX_HISTORY_LIMIT = 200;export const DEFAULT_PAST_WORK_LIMIT = 20;
export const DEFAULT_MAX_PAST_WORK_LIMIT = 100;export const DEFAULT_TICKET_FAMILY_LIMIT = 40;
export const DEFAULT_MAX_TICKET_FAMILY_LIMIT = 100;
export const DEFAULT_TICKET_TIME_LIMIT = 50;
export const DEFAULT_MAX_TICKET_TIME_LIMIT = 200;
export const DEFAULT_TABLE_ROWS = 100;
export const DEFAULT_MAX_TABLE_ROWS = 500;export const DEFAULT_FIND_PULL_REQUEST_LIMIT = 10;
export const DEFAULT_MAX_FIND_PULL_REQUEST_LIMIT = 25;
export const DEFAULT_LIST_PULL_REQUESTS_LIMIT = 20;
export const DEFAULT_MAX_LIST_PULL_REQUESTS_LIMIT = 50;
export const DEFAULT_THREADS_LIMIT = 20;
export const DEFAULT_MAX_THREADS_LIMIT = 50;
export const DEFAULT_DIFF_LIMIT = 10;
export const DEFAULT_MAX_DIFF_LIMIT = 30;| Araç | Varsayılan limit | En büyük limit |
|---|---|---|
search_code | DEFAULT_SEARCH_CODE_LIMIT (8) | DEFAULT_MAX_SEARCH_CODE_LIMIT (30) |
grep_code | DEFAULT_GREP_CODE_LIMIT (50) | DEFAULT_MAX_GREP_CODE_LIMIT (200); bağlam satırı en çok DEFAULT_MAX_GREP_CODE_CONTEXT (5) |
search_tickets | DEFAULT_SEARCH_TICKETS_LIMIT (20) | DEFAULT_MAX_SEARCH_TICKETS_LIMIT (50) |
get_ticket_comments | DEFAULT_COMMENTS_LIMIT (30) | DEFAULT_MAX_COMMENTS_LIMIT (100) |
get_ticket_history | DEFAULT_HISTORY_LIMIT (50) | DEFAULT_MAX_HISTORY_LIMIT (200) |
find_past_work | DEFAULT_PAST_WORK_LIMIT (20) | DEFAULT_MAX_PAST_WORK_LIMIT (100) |
get_ticket_family | DEFAULT_TICKET_FAMILY_LIMIT (40) | DEFAULT_MAX_TICKET_FAMILY_LIMIT (100); alt kayıtlar ve kardeş kayıtlar için ayrı ayrı |
get_ticket_time | DEFAULT_TICKET_TIME_LIMIT (50) | DEFAULT_MAX_TICKET_TIME_LIMIT (200) çalışma günlüğü |
get_ticket_attachment | DEFAULT_TABLE_ROWS (100) hesap tablosu satırı | DEFAULT_MAX_TABLE_ROWS (500) |
find_pull_request | DEFAULT_FIND_PULL_REQUEST_LIMIT (10) | DEFAULT_MAX_FIND_PULL_REQUEST_LIMIT (25) |
list_pull_requests | DEFAULT_LIST_PULL_REQUESTS_LIMIT (20) | DEFAULT_MAX_LIST_PULL_REQUESTS_LIMIT (50) |
get_pull_request_threads | DEFAULT_THREADS_LIMIT (20) | DEFAULT_MAX_THREADS_LIMIT (50) |
get_pull_request_diff | DEFAULT_DIFF_LIMIT (10) dosya | DEFAULT_MAX_DIFF_LIMIT (30); en çok DEFAULT_MAX_DIFF_PATHS (20) yol ve DEFAULT_MAX_DIFF_CONTEXT_LINES (10) bağlam satırı |
Bunlar sunucunun kendi sınırlarıdır ve SDK'nınkilerden küçüktür: safran.tickets.search varsayılanı 50'dir ve 500'e izin verir (@safran/core varsayılanları). Burada kıt olan kaynak ajanın bağlamıdır.
createStderrLogger
/** A logger that writes to stderr only. stdout belongs to the protocol when serving over stdio. */
export function createStderrLogger(minLevel: "debug" | "info" | "warn" | "error" = "warn"): Logger;tanımlandığı yer: packages/mcp/src/tools/shared.ts
Her girdi için stderr'e [safran-mcp] <level> <message> <fields as JSON> biçiminde tek satır yazan ve minLevel altındaki girdileri atan (varsayılan "warn") bir Logger. stdio üzerinden sunumda stdout protokole aittir; bu yüzden üç giriş noktasının da varsayılan günlükleyicisi budur. Günlüğe yazılan değerler üçüncü taraf metni içerdiğinden, satırdan denetim ve biçim karakterleri çıkarılır.
debug düzeyinde her araç çağrısı adı, sonucu ve süresiyle günlüğe yazılır.
import { createSafranMcpServer, createStderrLogger } from "@safran/mcp";
import { createAcme } from "./acme";
const safran = await createAcme();
const server = createSafranMcpServer(safran, { logger: createStderrLogger("debug") });
// [safran-mcp] debug tool call {"tool":"get_ticket","ok":true,"ms":3}
console.log(server.isConnected());
await safran.close();sniffAttachment
/**
* Decides how an attachment can be delivered from its bytes. The declared mime type and the
* file name are not consulted: an attacker (or a careless uploader) controls both. SVG is
* XML, so it comes out as text and never as an image block.
*/
export function sniffAttachment(data: Uint8Array, maxTextChars: number = Number.MAX_SAFE_INTEGER): SniffedAttachment;
export type SniffedAttachment =
| { kind: "empty" }
| { kind: "image"; mimeType: "image/png" | "image/jpeg" | "image/gif" | "image/webp" }
| { kind: "text"; text: string; /** True when only a prefix of the file was decoded. */ partial: boolean }
| { kind: "spreadsheet" }
| { kind: "binary"; /** Set when the magic bytes name the format. */ mimeType?: string };tanımlandığı yer: packages/mcp/src/tools/tickets.ts
get_ticket_attachment aracının bir eki nasıl teslim edebileceğine yalnızca baytlarına bakarak karar verir. Bildirilen MIME türüne ve dosya adına bakılmaz: ikisini de dosyayı yükleyen kişi belirler. safran.tickets.attachment ile okuduğunuz eklere aynı kuralı uygulayabilmeniz için dışa aktarılır.
kind | Ne zaman | Ek alanlar |
|---|---|---|
"empty" | Hiç bayt yok. | — |
"image" | PNG, JPEG, GIF ya da WebP sihirli baytları. | mimeType |
"spreadsheet" | Baytlarından tanınan bir .xlsx çalışma kitabı. | — |
"binary" | Diğer ikili içerik. | sihirli baytlar biçimi belirtiyorsa mimeType (PDF, ZIP, gzip) |
"text" | Çözülebilir metin. SVG bir XML'dir; bu yüzden metindir, asla görsel değildir. | text; yalnızca bir önek çözüldüyse (maxTextChars) partial değeri true olur |
import { sniffAttachment } from "@safran/mcp";
const log = new TextEncoder().encode("refund failed at 10:02\n");
const sniffed = sniffAttachment(log, 40_000);
if (sniffed.kind === "text") console.log(sniffed.text, sniffed.partial); // "refund failed at 10:02\n" false
const png = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
console.log(sniffAttachment(png)); // { kind: "image", mimeType: "image/png" }Sık yapılan hatalar
-
stdio sunucusunda stdout'a yazmak. Kendi kodunuzdan gelen tek bir
process.stdout.writeistemcinin akışını bozar.serveSafranStdio,console.logçağrılarını yönlendirir ama doğrudan yazma işlemlerini yönlendirmez. Günlüğü stderr'e yazın. -
Örneği çok erken kapatmak ya da hiç kapatmamak. Sunucu ve işleyiciler
Safranörneğinin sahibi değildir. Önce tutamacı, sonra örneği kapatın. -
token: process.env.Xdeğerini denetlemeden vermek. Tanımsız değişkenundefinedverir; bu,exactOptionalPropertyTypesaltında tür hatasıdır, çalışma zamanında ise "kimlik doğrulama yok" anlamına gelir. Boş string hata fırlatır.serve-http.tsörneğindeki gibi açıkça karar verin. -
allowedHostsvermeden ters vekil sunucunun arkasında sunmak. Vekil kendi genelHostdeğerini iletir; o ana makine adını ekleyin, yoksa her istek403ile yanıtlanır. -
callToolçağrısının reddetmesini beklemek. Araç hatalarıisError: truetaşıyan sonuçlardır. Metni okuyun; ipucu oradadır ve son satırı, dallanmanız gereken[code: NAME]etiketidir. -
"Her şeyi almak" için bütçeleri yükseltmek. Büyük sonuçları istemci dosyaya taşır ya da kendisi keser. İşaretler ajana gerisini nasıl alacağını söyler; bütçeleri koruyun ve işaretleri izleyin.
-
Yazma araçlarını
SAFRAN_TOOLSiçinde beklemek. OnlarSAFRAN_WRITE_TOOLSiçindedir ve sunucu onları yalnızcasafran.writes.status().enableddeğeritrueolan bir örnek için kaydeder. Onlara ihtiyaç duyan bir test, örneğiniwritesbölümünü açan bir profille kurar.