@safran/mcp
@safran/mcp turns a Safran instance into an MCP server. Most people never import it: safran mcp and the Claude Code plugin start the server for you (running the MCP server). This page is for the other case: you want the server inside your own process, behind your own HTTP stack, in a test, or with different output budgets. It documents every export of the package.
What each tool takes and returns is in the MCP reference; this page is about the server around the tools.
A complete example
A server and a client in one process, connected by an in-memory transport. This is the shortest way to see what an agent sees, and it is how to test anything built on the server. The setup uses the fakes of @safran/kit/testing, so nothing reaches a network.
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://acme.atlassian.net",
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 instanceTwo things in that output are worth knowing before you build on it. A failing tool does not throw: callTool resolves with isError: true and a one-line message, often followed by a → hint (Ticket PAY-9999 not found in jira and what to try next). And text written by third parties arrives wrapped in <untrusted-data-…> tags in both content and structuredContent; security explains the wrapper.
What the package exports
| Export | Kind | What it is |
|---|---|---|
createSafranMcpServer, SafranMcpServerOptions | function, type | The server over an instance. |
serveSafranStdio, SafranStdioOptions, SafranStdioHandle | function, types | Serve over stdin/stdout. |
createSafranHttpHandler, SafranHttpHandlerOptions, SafranHttpHandler | function, types | A Streamable HTTP fetch handler. |
SAFRAN_TOOLS, SafranTool | constant, type | Every tool of the server, as data. |
SERVER_NAME, DEFAULT_SERVER_VERSION | constants | What the server reports to clients. |
SERVER_INSTRUCTIONS, MAX_INSTRUCTIONS_CHARS | constants | The instructions sent at initialisation. |
OutputBudgets, DEFAULT_OUTPUT_BUDGETS, DEFAULT_*_MAX_CHARS and friends | type, constants | How much text each tool may return. |
DEFAULT_*_LIMIT, DEFAULT_MAX_*_LIMIT | constants | Default and largest limit of the list tools. |
DEFAULT_HTTP_PATH, HEALTH_PATH, DEFAULT_HTTP_MAX_BODY_BYTES | constants | Defaults of the HTTP handler. |
createStderrLogger | function | A logger that never writes to stdout. |
sniffAttachment, SniffedAttachment | function, type | How an attachment's bytes are classified. |
The package depends on @modelcontextprotocol/server; createSafranMcpServer returns that SDK's McpServer.
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).
*/
export function createSafranMcpServer(safran: Safran, options: SafranMcpServerOptions = {}): McpServer;defined in packages/mcp/src/server.ts
Builds an McpServer named SERVER_NAME with SERVER_INSTRUCTIONS and registers every tool of SAFRAN_TOOLS. The server holds no logic of its own: each tool is one Safran call rendered for a model. It does not connect to anything; call server.connect(transport) with a transport of the MCP SDK, or use the two helpers below.
The server never closes the Safran instance. Whoever created the instance owns it, and one instance can back many servers; the HTTP handler creates one server per request.
Returns an McpServer. Throws nothing of its own.
| Option | Type | Default | Meaning |
|---|---|---|---|
version | string | DEFAULT_SERVER_VERSION | Version reported to clients. |
budgets | Partial<OutputBudgets> | DEFAULT_OUTPUT_BUDGETS | Output budgets to change; the rest keep their default. |
logger | Logger | createStderrLogger(): warnings and errors to stderr | Where failures are logged. Never stdout. |
now | () => Date | () => new Date() | Clock used for relative ages in the text output ("9 months ago"). Fix it in tests. |
export const SERVER_NAME = "safran";
export const DEFAULT_SERVER_VERSION = "0.1.0";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;defined in packages/mcp/src/stdio.ts
Serves the instance over stdin/stdout and returns at once with a handle. stdout carries JSON-RPC frames and nothing else: the default logger writes to stderr, and for as long as the server runs console.log, console.info and console.debug are redirected to stderr, because one stray line on stdout corrupts the protocol stream for the client.
SafranStdioOptions extends SafranMcpServerOptions with:
| Option | Type | Default | Meaning |
|---|---|---|---|
guardConsole | boolean | true | Redirect console.log / info / debug to stderr while serving. |
| Member | Type | Meaning |
|---|---|---|
close | () => Promise<void> | Stops serving and gives the console back. Does not close the Safran instance. |
Transport errors are logged at error level; they do not throw.
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);Register it with Claude Code as any stdio server, with the absolute path of your script: 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.
*/
token?: string;
/** 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>;
}defined in packages/mcp/src/http.ts
Returns a fetch-style handler for the Streamable HTTP transport. It is stateless: each request gets a fresh MCP server over the shared instance, so there are no sessions to expire. It does not listen on a port; pass handler.fetch to Bun.serve or mount it in your own router.
| Option | Type | Default | Meaning |
|---|---|---|---|
token | string | none (no authentication) | Static bearer token. When set, every request except the health check must send Authorization: Bearer <token>. An empty string is refused. |
allowedHosts | string[] | localhost, 127.0.0.1, [::1] | Hostnames accepted in the Host header, without port. |
allowedOrigins | string[] | localhost, 127.0.0.1, [::1] | Hostnames accepted in a browser's Origin header. |
path | string | DEFAULT_HTTP_PATH (/mcp) | Path the endpoint is served at. Both path and path/ answer directly, without a redirect. |
maxBodyBytes | number | DEFAULT_HTTP_MAX_BODY_BYTES (1 MiB) | Largest request body accepted. |
It also takes every option of SafranMcpServerOptions (version, budgets, logger, now).
| Member | Type | Meaning |
|---|---|---|
fetch | (request: Request) => Promise<Response> | Answers one request. Never rejects: an unexpected failure is logged and answered with 500. |
close | () => Promise<void> | Aborts in-flight requests. Does not close the Safran instance. |
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;Throws INVALID_INPUT when the options make no sense: an empty token (so an unset environment variable cannot open the server by accident), a path that is not absolute or contains ? or #, a path equal to /healthz, a maxBodyBytes that is not a positive number.
What a request goes through
Checks run in this order; the first one that fails answers.
| # | Check | Answer when it fails |
|---|---|---|
| 1 | The Host header names an allowed hostname | 403, JSON-RPC error Invalid Host: … (or Missing Host header) |
| 2 | An Origin header, when present, names an allowed hostname | 403, JSON-RPC error Invalid Origin: … |
| 3 | GET or HEAD on /healthz | answered here: 200 with the body ok, no authentication |
| 4 | With token set: Authorization: Bearer <token> matches (compared in constant time) | 401 {"error":"unauthorized",…} with a WWW-Authenticate: Bearer realm="safran" header |
| 5 | The path is path or path/ | 404 {"error":"not_found"} |
| 6 | A declared Content-Length is at most maxBodyBytes | 413 {"error":"payload_too_large",…} |
| 7 | The MCP transport handles the request | e.g. 405 for a GET on the endpoint |
Checks 1 and 2 together are the defence against DNS rebinding for a server bound to localhost. No CORS headers are ever sent, so a browser cannot read responses from another origin. Every response of the handler itself carries Cache-Control: no-store and X-Content-Type-Options: nosniff.
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();
});Because the handler is a function from Request to Response, it can be tested without a port. A Request built in code has no Host header, so set one:
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();
});The tool list
/** Every tool of the server, in the order of docs/MCP-TOOLS.md. */
export const SAFRAN_TOOLS: readonly SafranTool[] = [...companyTools, ...ticketTools, ...codeTools, ...historyTools];
/** 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: { readOnlyHint: true; destructiveHint: false; idempotentHint: true; openWorldHint: boolean };
readonly meta?: Record<string, unknown>;
register(server: McpServer, env: ToolEnv): void;
}defined in packages/mcp/src/server.ts, packages/mcp/src/tools/shared.ts
Every tool of the server as data, in the order the server registers them. Use it to generate documentation, to assert in a test that a tool exists, or to register the tools on an McpServer you configure yourself.
| Member | Type | Meaning |
|---|---|---|
name | string | Tool name, tracker-neutral (get_ticket). |
title | string | Human-readable title. |
description | string | The description the model reads. |
inputSchema | z.ZodType | zod schema of the arguments. |
outputSchema | z.ZodType | zod schema of structuredContent. |
annotations | { readOnlyHint: true; destructiveHint: false; idempotentHint: true; openWorldHint: boolean } | Every tool is read-only and idempotent. openWorldHint is true when the tool reaches a tracker or a wiki, false when it reads the local index or the profile. |
meta | Record<string, unknown> (optional) | _meta published in tools/list. |
register | (server: McpServer, env: ToolEnv) => void | Puts the tool on a server. createSafranMcpServer calls it for you. |
The tools, with the section of the MCP reference that documents each:
| Tool | Reaches the network | Reference |
|---|---|---|
get_company_profile, who_owns | no | Company |
get_ticket, get_ticket_comments, get_ticket_attachment, get_ticket_history, search_tickets, fetch_linked_doc | yes | Tickets |
search_code, grep_code, read_file, list_repos | no | Code |
find_past_work | no | History |
import { SAFRAN_TOOLS } from "@safran/mcp";
for (const tool of SAFRAN_TOOLS) {
console.log(tool.name.padEnd(24), tool.annotations.openWorldHint ? "network" : "local ", tool.title);
}Server instructions
/**
* 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`.
*/
export const SERVER_INSTRUCTIONS; // defined in packages/mcp/src/instructions.ts
/** Clients cap server instructions; Claude Code cuts them at 4,096 characters. */
export const MAX_INSTRUCTIONS_CHARS = 4096;defined in packages/mcp/src/instructions.ts
The text sent to the client once, at initialisation. It tells the agent to call get_company_profile first, how to treat untrusted data, the evidence rule for claims about code, and which tool to use for what. It names no company: everything company-specific comes from get_company_profile.
MAX_INSTRUCTIONS_CHARS is the length the text must stay under, because clients cap server instructions. The instructions are a constant and cannot be changed through options; a server that needs different ones registers SAFRAN_TOOLS on its own McpServer.
import { MAX_INSTRUCTIONS_CHARS, SERVER_INSTRUCTIONS } from "@safran/mcp";
console.log(SERVER_INSTRUCTIONS.length <= MAX_INSTRUCTIONS_CHARS); // true
console.log(SERVER_INSTRUCTIONS.split("\n")[0]);Output budgets
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;
}defined in packages/mcp/src/tools/shared.ts
Every tool bounds what it returns. Budgets are counted in characters of third-party text unless the name says otherwise. Text over a budget is cut on a line boundary with an explicit marker that says how to get the rest; nothing is cut silently. Change any of them with SafranMcpServerOptions.budgets.
export const DEFAULT_OUTPUT_BUDGETS: OutputBudgets; // defined in packages/mcp/src/tools/shared.ts| Budget | Default constant | Value | What it bounds |
|---|---|---|---|
profileChars | DEFAULT_PROFILE_MAX_CHARS | 24,000 | Text rendering of the whole profile (get_company_profile). |
titleChars | DEFAULT_TITLE_MAX_CHARS | 300 | One title: ticket, page, pull request. |
ticketDescriptionChars | DEFAULT_TICKET_DESCRIPTION_MAX_CHARS | 16,000 | The description of one ticket. |
ticketFieldsChars | DEFAULT_TICKET_FIELDS_MAX_CHARS | 6,000 | All tracker-specific fields of one ticket together. |
ticketFieldChars | DEFAULT_TICKET_FIELD_MAX_CHARS | 3,000 | One tracker-specific field. |
ticketInlineComments | DEFAULT_TICKET_INLINE_COMMENTS | 10 | Number of comments get_ticket shows; the rest is one get_ticket_comments call away. |
ticketInlineCommentsChars | DEFAULT_TICKET_INLINE_COMMENTS_MAX_CHARS | 8,000 | Those inline comments together. |
ticketLinks | DEFAULT_TICKET_LINKS_MAX | 50 | Number of links listed for one ticket. |
ticketLinksChars | DEFAULT_TICKET_LINKS_MAX_CHARS | 6,000 | Rendered size of that link list. |
ticketAttachments | DEFAULT_TICKET_ATTACHMENTS_MAX | 50 | Number of attachments listed for one ticket. |
ticketAttachmentsChars | DEFAULT_TICKET_ATTACHMENTS_MAX_CHARS | 4,000 | Rendered size of that attachment list. |
commentChars | DEFAULT_COMMENT_MAX_CHARS | 6,000 | One comment. |
commentsChars | DEFAULT_COMMENTS_MAX_CHARS | 16,000 | One page of get_ticket_comments. Comments that do not fit move to the next cursor whole. |
historyValueChars | DEFAULT_HISTORY_VALUE_MAX_CHARS | 300 | One old or new value in get_ticket_history. |
historyChars | DEFAULT_HISTORY_MAX_CHARS | 12,000 | One page of get_ticket_history. |
attachmentTextChars | DEFAULT_ATTACHMENT_TEXT_MAX_CHARS | 40,000 | A text attachment (get_ticket_attachment). |
attachmentImageBytes | DEFAULT_ATTACHMENT_IMAGE_MAX_BYTES | 3,500,000 | Largest image returned as an image block, in bytes. |
docChars | DEFAULT_DOC_MAX_CHARS | 40,000 | A page from fetch_linked_doc. |
snippetChars | DEFAULT_SNIPPET_MAX_CHARS | 4,000 | The snippet of one search_code hit. |
searchCodeChars | DEFAULT_SEARCH_CODE_MAX_CHARS | 16,000 | All snippets of one search_code call. Hits past it keep their location and lose the snippet. |
alsoIn | DEFAULT_ALSO_IN_MAX | 5 | Duplicate locations named under one hit. |
grepLineChars | DEFAULT_GREP_LINE_MAX_CHARS | 300 | One matching line of grep_code. |
grepChars | DEFAULT_GREP_MAX_CHARS | 12,000 | All lines of one grep_code call. |
readFileChars | DEFAULT_READ_FILE_MAX_CHARS | 60,000 | The content of one read_file call. |
listRepos | DEFAULT_LIST_REPOS_MAX | 500 | Number of repositories list_repos returns. |
pastWorkFilesPerRecord | DEFAULT_PAST_WORK_FILES_PER_RECORD | 30 | Changed files listed per pull request in find_past_work. |
The source gives the reasoning for the sizes: they are tuned against Claude Code, which warns above roughly 10,000 tokens per tool result, and third-party text is carried twice (in the text and in the structured copy), so list tools stay well under half of that.
Four more exported constants bound output but are not part of OutputBudgets, so they cannot be changed per server:
/** 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;
/** 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;Limits of the list tools
The default and the largest limit each paginated tool accepts. They are constants; a tool call asking for more than the maximum is refused by the tool's input schema.
export const DEFAULT_SEARCH_CODE_LIMIT = 8;
export const DEFAULT_MAX_SEARCH_CODE_LIMIT = 30;
export const DEFAULT_GREP_CODE_LIMIT = 50;
export const DEFAULT_MAX_GREP_CODE_LIMIT = 200;
export const DEFAULT_MAX_GREP_CODE_CONTEXT = 5;export const DEFAULT_SEARCH_TICKETS_LIMIT = 20;
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;| Tool | Default limit | Largest 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); context lines at most 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) |
These are the server's own limits and are smaller than the SDK's: safran.tickets.search defaults to 50 and allows 500 (@safran/core defaults). An agent's context is the scarce resource here.
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;defined in packages/mcp/src/tools/shared.ts
A Logger that writes one line per entry to stderr as [safran-mcp] <level> <message> <fields as JSON>, and drops entries below minLevel (default "warn"). stdout belongs to the protocol when serving over stdio, so this is the default logger of all three entry points. Control and format characters are removed from the line, because logged values include third-party text.
At debug level every tool call is logged with its name, outcome and duration.
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: "binary"; /** Set when the magic bytes name the format. */ mimeType?: string };defined in packages/mcp/src/tools/tickets.ts
Decides how get_ticket_attachment can deliver an attachment, from its bytes alone. The declared MIME type and the file name are not consulted: whoever uploaded the file controls both. It is exported so you can apply the same rule to attachments you read through safran.tickets.attachment.
kind | When | Extra fields |
|---|---|---|
"empty" | No bytes. | — |
"image" | PNG, JPEG, GIF or WebP magic bytes. | mimeType |
"binary" | Other binary content. | mimeType when the magic bytes name the format (PDF, ZIP, gzip) |
"text" | Decodable text. SVG is XML, so it is text and never an image. | text; partial is true when only a prefix was decoded (maxTextChars) |
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" }Common mistakes
- Writing to stdout in a stdio server. One
process.stdout.writefrom your own code breaks the client's stream.serveSafranStdioredirectsconsole.log, but not direct writes. Log to stderr. - Closing the instance too early, or never. The server and the handlers do not own the
Safraninstance. Close the handle first, then the instance. - Passing
token: process.env.Xunchecked. An unset variable givesundefined, which underexactOptionalPropertyTypesis a type error and at run time means "no authentication". An empty string throws. Decide explicitly, asserve-http.tsdoes. - Serving behind a reverse proxy without
allowedHosts. The proxy forwards its publicHost; add that hostname, or every request is answered403 Invalid Host. - Expecting
callToolto reject. Tool failures are results withisError: true. Read the text; it carries the hint. - Raising budgets to "get everything". Larger results are spilled to files or truncated by the client instead. The markers tell the agent how to fetch the rest; keep the budgets and follow them.