Skip to content
safran

Type to search. Enter opens the first result.

    @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.

    acme.ts
    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"),
      });
    }
    in-process.ts
    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 instance

    Two 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

    ExportKindWhat it is
    createSafranMcpServer, SafranMcpServerOptionsfunction, typeThe server over an instance.
    serveSafranStdio, SafranStdioOptions, SafranStdioHandlefunction, typesServe over stdin/stdout.
    createSafranHttpHandler, SafranHttpHandlerOptions, SafranHttpHandlerfunction, typesA Streamable HTTP fetch handler.
    SAFRAN_TOOLS, SafranToolconstant, typeEvery tool of the server, as data.
    SERVER_NAME, DEFAULT_SERVER_VERSIONconstantsWhat the server reports to clients.
    SERVER_INSTRUCTIONS, MAX_INSTRUCTIONS_CHARSconstantsThe instructions sent at initialisation.
    OutputBudgets, DEFAULT_OUTPUT_BUDGETS, DEFAULT_*_MAX_CHARS and friendstype, constantsHow much text each tool may return.
    DEFAULT_*_LIMIT, DEFAULT_MAX_*_LIMITconstantsDefault and largest limit of the list tools.
    DEFAULT_HTTP_PATH, HEALTH_PATH, DEFAULT_HTTP_MAX_BODY_BYTESconstantsDefaults of the HTTP handler.
    createStderrLoggerfunctionA logger that never writes to stdout.
    sniffAttachment, SniffedAttachmentfunction, typeHow 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.

    OptionTypeDefaultMeaning
    versionstringDEFAULT_SERVER_VERSIONVersion reported to clients.
    budgetsPartial<OutputBudgets>DEFAULT_OUTPUT_BUDGETSOutput budgets to change; the rest keep their default.
    loggerLoggercreateStderrLogger(): warnings and errors to stderrWhere 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:

    OptionTypeDefaultMeaning
    guardConsolebooleantrueRedirect console.log / info / debug to stderr while serving.
    MemberTypeMeaning
    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.

    serve-stdio.ts
    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.

    OptionTypeDefaultMeaning
    tokenstringnone (no authentication)Static bearer token. When set, every request except the health check must send Authorization: Bearer <token>. An empty string is refused.
    allowedHostsstring[]localhost, 127.0.0.1, [::1]Hostnames accepted in the Host header, without port.
    allowedOriginsstring[]localhost, 127.0.0.1, [::1]Hostnames accepted in a browser's Origin header.
    pathstringDEFAULT_HTTP_PATH (/mcp)Path the endpoint is served at. Both path and path/ answer directly, without a redirect.
    maxBodyBytesnumberDEFAULT_HTTP_MAX_BODY_BYTES (1 MiB)Largest request body accepted.

    It also takes every option of SafranMcpServerOptions (version, budgets, logger, now).

    MemberTypeMeaning
    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.

    #CheckAnswer when it fails
    1The Host header names an allowed hostname403, JSON-RPC error Invalid Host: … (or Missing Host header)
    2An Origin header, when present, names an allowed hostname403, JSON-RPC error Invalid Origin: …
    3GET or HEAD on /healthzanswered here: 200 with the body ok, no authentication
    4With token set: Authorization: Bearer <token> matches (compared in constant time)401 {"error":"unauthorized",…} with a WWW-Authenticate: Bearer realm="safran" header
    5The path is path or path/404 {"error":"not_found"}
    6A declared Content-Length is at most maxBodyBytes413 {"error":"payload_too_large",…}
    7The MCP transport handles the requeste.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.

    serve-http.ts
    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:

    http.test.ts
    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.

    MemberTypeMeaning
    namestringTool name, tracker-neutral (get_ticket).
    titlestringHuman-readable title.
    descriptionstringThe description the model reads.
    inputSchemaz.ZodTypezod schema of the arguments.
    outputSchemaz.ZodTypezod 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.
    metaRecord<string, unknown> (optional)_meta published in tools/list.
    register(server: McpServer, env: ToolEnv) => voidPuts the tool on a server. createSafranMcpServer calls it for you.

    The tools, with the section of the MCP reference that documents each:

    ToolReaches the networkReference
    get_company_profile, who_ownsnoCompany
    get_ticket, get_ticket_comments, get_ticket_attachment, get_ticket_history, search_tickets, fetch_linked_docyesTickets
    search_code, grep_code, read_file, list_reposnoCode
    find_past_worknoHistory
    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
    BudgetDefault constantValueWhat it bounds
    profileCharsDEFAULT_PROFILE_MAX_CHARS24,000Text rendering of the whole profile (get_company_profile).
    titleCharsDEFAULT_TITLE_MAX_CHARS300One title: ticket, page, pull request.
    ticketDescriptionCharsDEFAULT_TICKET_DESCRIPTION_MAX_CHARS16,000The description of one ticket.
    ticketFieldsCharsDEFAULT_TICKET_FIELDS_MAX_CHARS6,000All tracker-specific fields of one ticket together.
    ticketFieldCharsDEFAULT_TICKET_FIELD_MAX_CHARS3,000One tracker-specific field.
    ticketInlineCommentsDEFAULT_TICKET_INLINE_COMMENTS10Number of comments get_ticket shows; the rest is one get_ticket_comments call away.
    ticketInlineCommentsCharsDEFAULT_TICKET_INLINE_COMMENTS_MAX_CHARS8,000Those inline comments together.
    ticketLinksDEFAULT_TICKET_LINKS_MAX50Number of links listed for one ticket.
    ticketLinksCharsDEFAULT_TICKET_LINKS_MAX_CHARS6,000Rendered size of that link list.
    ticketAttachmentsDEFAULT_TICKET_ATTACHMENTS_MAX50Number of attachments listed for one ticket.
    ticketAttachmentsCharsDEFAULT_TICKET_ATTACHMENTS_MAX_CHARS4,000Rendered size of that attachment list.
    commentCharsDEFAULT_COMMENT_MAX_CHARS6,000One comment.
    commentsCharsDEFAULT_COMMENTS_MAX_CHARS16,000One page of get_ticket_comments. Comments that do not fit move to the next cursor whole.
    historyValueCharsDEFAULT_HISTORY_VALUE_MAX_CHARS300One old or new value in get_ticket_history.
    historyCharsDEFAULT_HISTORY_MAX_CHARS12,000One page of get_ticket_history.
    attachmentTextCharsDEFAULT_ATTACHMENT_TEXT_MAX_CHARS40,000A text attachment (get_ticket_attachment).
    attachmentImageBytesDEFAULT_ATTACHMENT_IMAGE_MAX_BYTES3,500,000Largest image returned as an image block, in bytes.
    docCharsDEFAULT_DOC_MAX_CHARS40,000A page from fetch_linked_doc.
    snippetCharsDEFAULT_SNIPPET_MAX_CHARS4,000The snippet of one search_code hit.
    searchCodeCharsDEFAULT_SEARCH_CODE_MAX_CHARS16,000All snippets of one search_code call. Hits past it keep their location and lose the snippet.
    alsoInDEFAULT_ALSO_IN_MAX5Duplicate locations named under one hit.
    grepLineCharsDEFAULT_GREP_LINE_MAX_CHARS300One matching line of grep_code.
    grepCharsDEFAULT_GREP_MAX_CHARS12,000All lines of one grep_code call.
    readFileCharsDEFAULT_READ_FILE_MAX_CHARS60,000The content of one read_file call.
    listReposDEFAULT_LIST_REPOS_MAX500Number of repositories list_repos returns.
    pastWorkFilesPerRecordDEFAULT_PAST_WORK_FILES_PER_RECORD30Changed 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;
    ToolDefault limitLargest limit
    search_codeDEFAULT_SEARCH_CODE_LIMIT (8)DEFAULT_MAX_SEARCH_CODE_LIMIT (30)
    grep_codeDEFAULT_GREP_CODE_LIMIT (50)DEFAULT_MAX_GREP_CODE_LIMIT (200); context lines at most DEFAULT_MAX_GREP_CODE_CONTEXT (5)
    search_ticketsDEFAULT_SEARCH_TICKETS_LIMIT (20)DEFAULT_MAX_SEARCH_TICKETS_LIMIT (50)
    get_ticket_commentsDEFAULT_COMMENTS_LIMIT (30)DEFAULT_MAX_COMMENTS_LIMIT (100)
    get_ticket_historyDEFAULT_HISTORY_LIMIT (50)DEFAULT_MAX_HISTORY_LIMIT (200)
    find_past_workDEFAULT_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.

    kindWhenExtra 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.write from your own code breaks the client's stream. serveSafranStdio redirects console.log, but not direct writes. Log to stderr.
    • Closing the instance too early, or never. The server and the handlers do not own the Safran instance. Close the handle first, then the instance.
    • Passing token: process.env.X unchecked. An unset variable gives undefined, which under exactOptionalPropertyTypes is a type error and at run time means "no authentication". An empty string throws. Decide explicitly, as serve-http.ts does.
    • Serving behind a reverse proxy without allowedHosts. The proxy forwards its public Host; add that hostname, or every request is answered 403 Invalid Host.
    • Expecting callTool to reject. Tool failures are results with isError: 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.