Skip to content
safran

Type to search. Enter opens the first result.

    HTTP mode and embedding

    The MCP server speaks two transports. stdio is what Claude Code starts by itself; it is described on registering the MCP server. This page covers the other one, Streamable HTTP, with the exact checks the endpoint makes, and the three functions of @safran/mcp for running the server inside your own process.

    safran mcp --http

    $ safran mcp --http --port 0 --profile /work/acme/safran.yaml
    ✔ Safran MCP server for acme listening on http://127.0.0.1:52358/mcp
      health: http://127.0.0.1:52358/healthz   auth: none (loopback only)
    
    Register it in Claude Code:
      claude mcp add --transport http safran http://127.0.0.1:52358/mcp
    
    Ctrl-C stops the server.

    The banner goes to stderr; stdout stays empty, so the command can be supervised like the stdio one. Register the URL it prints:

    claude mcp add --transport http safran http://127.0.0.1:3939/mcp
    FlagDefaultMeaning
    --httpoffServe Streamable HTTP instead of stdio. The other flags of this table are refused without it.
    --port <n>3939Port to listen on, 0 to 65535. 0 picks a free one; the banner shows which.
    --host <address>127.0.0.1Address to bind. Anything other than 127.0.0.1, localhost or ::1 needs --token-env.
    --token-env <NAME>noneName of the environment variable that holds a bearer token clients must send. The variable may also be in the .env next to the profile.
    --path </mcp>/mcpEndpoint path.
    --allow-host <hostname>noneExtra hostname accepted in the Host header, for a server that is not bound to loopback. Repeatable.

    The global options (--profile, --data-dir, --allow-plugins, --verbose) apply as for every command; see the CLI reference.

    Serving beyond loopback

    The server gives read access to your tickets and your source code. Bound to loopback, only processes on the same machine can reach it. Bound to any other address, everyone who can reach the port can, so the command refuses to do that without a token:

    $ safran mcp --http --host 0.0.0.0 --profile /work/acme/safran.yaml
    ✘ Refusing to bind 0.0.0.0 without a token
    → The server gives read access to your tickets and source code and has no other authentication. Keep the default 127.0.0.1, or name a variable holding a bearer token: --token-env SAFRAN_MCP_TOKEN

    With a token, and the hostname clients will use:

    $ safran mcp --http --port 0 --host 0.0.0.0 --token-env SAFRAN_MCP_TOKEN --allow-host safran.acme.test --profile /work/acme/safran.yaml
    ✔ Safran MCP server for acme listening on http://127.0.0.1:52384/mcp
      health: http://127.0.0.1:52384/healthz   auth: bearer token from SAFRAN_MCP_TOKEN
      accepted Host names: localhost, 127.0.0.1, [::1], safran.acme.test (add more with --allow-host)
    
    Register it in Claude Code:
      claude mcp add --transport http safran http://127.0.0.1:52384/mcp --header "Authorization: Bearer $SAFRAN_MCP_TOKEN"
    
    Ctrl-C stops the server.
    • The token is read from the named variable when the server starts. An unset or empty variable is AUTH_MISSING; the token is never passed on the command line.
    • When the server is bound to a wildcard address (0.0.0.0 or ::), the accepted Host names are the three loopback names plus every --allow-host. Bound to one specific non-loopback address, that address is accepted too. A client that reaches the server under any other name is refused, so name the hostname your clients use.
    • The banner prints a loopback URL for a wildcard bind. Clients on other machines use the server's hostname instead.

    The security model

    Every request passes these checks, in this order. The first that fails answers.

    #CheckOn failure
    1The Host header names an allowed hostname. Default: localhost, 127.0.0.1, [::1].403
    2An Origin header, when present, names an allowed hostname. Default: the same three. A request without Origin (every non-browser client) passes.403
    3GET or HEAD on /healthz answers 200 with the body ok, without authentication, and says nothing else.
    4When a token is configured, the request carries Authorization: Bearer <token>.401 with a WWW-Authenticate challenge
    5The path is the endpoint path or the same with one trailing slash.404
    6A declared Content-Length is not larger than the body limit (1 MiB by default).413

    Then the request is handed to the MCP transport, which enforces the same body limit while reading.

    Host and Origin: the DNS-rebinding defence. A server on localhost is reachable from any web page the user has open, if the page can make the browser talk to it. A page on another origin sends its own Origin; a page that rebinds its hostname to 127.0.0.1 sends its own hostname in Host. Checks 1 and 2 refuse both, before anything else is looked at:

    $ curl -s -H 'Host: evil.example' http://127.0.0.1:3939/mcp
    {"jsonrpc":"2.0","error":{"code":-32000,"message":"Invalid Host: evil.example"},"id":null}

    No CORS headers. The handler never sends Access-Control-Allow-Origin or any other CORS header, and does not answer preflight requests with permission. A browser therefore cannot read a response cross-origin either.

    The health check is the only thing served without the token. It still passes the Host and Origin checks.

    The bearer token is compared in constant time: both sides are hashed with SHA-256 and the digests compared with timingSafeEqual, so the comparison leaks neither content nor length. An empty token is refused when the handler is created, so an unset environment variable cannot open the server by accident.

    The 401 challenge follows RFC 6750: WWW-Authenticate: Bearer realm="safran" when no credentials were sent, and Bearer realm="safran", error="invalid_token" when wrong ones were. It does not advertise OAuth resource metadata, because there is no authorization server behind it and advertising one would start a discovery flow in clients that can only fail.

    $ curl -s -i -X POST http://127.0.0.1:3939/mcp -d '{}'
    HTTP/1.1 401 Unauthorized
    Cache-Control: no-store
    X-Content-Type-Options: nosniff
    Content-Type: application/json
    www-authenticate: Bearer realm="safran"
    
    {"error":"unauthorized","message":"A valid bearer token is required."}

    Only the endpoint path is served, as /mcp and /mcp/, both directly. There is no redirect between them, because a client that follows a redirect may drop the body of its POST. Every other path is 404 with {"error":"not_found"}. Because authentication comes first, a client without the token cannot learn which paths exist.

    Body size. Tool calls are a few hundred bytes of JSON; the default limit of 1,048,576 bytes leaves room for batches and long cursors. A larger declared body is refused with 413 and {"error":"payload_too_large", …}.

    Stateless. Each request gets a fresh MCP server over the shared Safran instance. There are no sessions to hijack or to expire, and one handler serves any number of clients. The Safran instance, with its open index and connectors, is shared.

    Response headers. The handler's own responses carry Cache-Control: no-store and X-Content-Type-Options: nosniff.

    Failures. The handler's fetch never rejects. An unexpected exception is logged and answered with 500 and {"error":"internal"}; no detail reaches the client.

    Embedding the HTTP handler

    createSafranHttpHandler returns an object with a fetch function in the Web-standard shape, so it plugs into Bun.serve or any runtime that serves Request → Response. This is what safran mcp --http does, written out:

    serve-http.ts
    import { createSafran } from "@safran/core";
    import { createSafranHttpHandler, DEFAULT_HTTP_PATH, HEALTH_PATH } from "@safran/mcp";
    
    const token = process.env.SAFRAN_MCP_TOKEN;
    if (token === undefined || token.trim() === "") throw new Error("Set SAFRAN_MCP_TOKEN to a long random value");
    
    const safran = await createSafran({ profile: "/work/acme/safran.yaml" });
    const handler = createSafranHttpHandler(safran, {
      token,
      // The names clients will use to reach this server, besides the loopback ones.
      allowedHosts: ["localhost", "127.0.0.1", "[::1]", "safran.acme.test"],
    });
    
    const server = Bun.serve({
      hostname: "0.0.0.0",
      port: 3939,
      fetch: (request) => handler.fetch(request),
    });
    console.error(`MCP endpoint: http://safran.acme.test:${server.port}${DEFAULT_HTTP_PATH} (health: ${HEALTH_PATH})`);
    
    process.on("SIGINT", async () => {
      await server.stop(true);
      await handler.close(); // aborts in-flight requests
      await safran.close(); // the handler does not own the instance
      process.exit(0);
    });
    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;
    }

    defined in packages/mcp/src/http.ts

    OptionDefaultMeaning
    tokennoneStatic bearer token. When set, every request except the health check must carry it. An empty or blank string throws INVALID_INPUT.
    allowedHostslocalhost, 127.0.0.1, [::1]Hostnames accepted in the Host header, without port. Passing a list replaces the default, so include the loopback names when you still want them.
    allowedOriginslocalhost, 127.0.0.1, [::1]Hostnames accepted in a browser's Origin header.
    path/mcpEndpoint path, with or without a trailing slash. Must be absolute, without ? or #, and not /healthz.
    maxBodyBytes1048576Largest request body accepted, in bytes. Must be a positive number.

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

    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

    Embedding over stdio

    serveSafranStdio serves an instance on the process's stdin and stdout:

    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.4.0" });
    
    // The client ends the session by closing stdin.
    process.stdin.on("end", async () => {
      await handle.close();
      await safran.close();
    });

    stdout carries JSON-RPC frames and nothing else. The default logger writes warnings and errors to stderr, and while serving, console.log, console.info and console.debug are pointed at stderr too, because one stray line on stdout corrupts the stream for the client. close() gives the console back.

    export interface SafranStdioOptions extends SafranMcpServerOptions {
      /**
       * While serving, `console.log` / `info` / `debug` are pointed at stderr, because one stray
       * line on stdout corrupts the protocol stream for the client. Default: true.
       */
      guardConsole?: boolean;
    }
    
    export interface SafranStdioHandle {
      /** Stops serving and gives the console back. Does not close the Safran instance. */
      close(): Promise<void>;
    }

    defined in packages/mcp/src/stdio.ts

    The server object

    Both transports are built on createSafranMcpServer, which returns the MCP SDK's server with the thirteen tools registered and the instructions set. Use it directly to connect another transport, or to test an agent against a Safran built from fakes:

    in-memory.test.ts
    import { expect, test } from "bun:test";
    import { Client } from "@modelcontextprotocol/client";
    import { InMemoryTransport } from "@modelcontextprotocol/server";
    import { createSafran } from "@safran/core";
    import { FakeCodeIndex, FakeEmbedder, FakeTracker, fakePlugins } from "@safran/kit/testing";
    import { createSafranMcpServer, SAFRAN_TOOLS } from "@safran/mcp";
    
    test("the server answers get_ticket", async () => {
      const jira = new FakeTracker({
        id: "jira",
        tickets: [{ key: "PAY-1423", title: "Kısmi iade işlemi İstanbul şubesinde başarısız oluyor" }],
      });
      await using safran = await createSafran({
        profile: {
          version: 1,
          company: "acme",
          trackers: [{ id: "jira", type: "fake", projects: ["PAY"] }],
          embeddings: { type: "fake" },
        },
        builtinPlugins: false,
        plugins: fakePlugins({ trackers: [jira] }),
        embedder: new FakeEmbedder(),
        index: new FakeCodeIndex(),
        env: {},
      });
    
      const server = createSafranMcpServer(safran, { now: () => new Date("2026-11-23T12:00:00Z") });
      const [clientSide, serverSide] = InMemoryTransport.createLinkedPair();
      await server.connect(serverSide);
      const client = new Client({ name: "acme-tests", version: "0.0.0" });
      await client.connect(clientSide);
    
      const listed = await client.listTools();
      expect(listed.tools.map((tool) => tool.name)).toEqual(SAFRAN_TOOLS.map((tool) => tool.name));
    
      const result = await client.callTool({ name: "get_ticket", arguments: { ref: "PAY-1423", include: [] } });
      expect(result.isError).not.toBe(true);
      expect(JSON.stringify(result.structuredContent)).toContain("Kısmi iade");
    
      await client.close();
      await server.close();
    });
    export interface SafranMcpServerOptions {
      /** Version reported to clients. Default: `DEFAULT_SERVER_VERSION`. */
      version?: string;
      /** Output budgets to change; the rest keep their `DEFAULT_*` value. */
      budgets?: Partial<OutputBudgets>;
      /** Where failures are logged. Default: warnings and errors to stderr. Never stdout. */
      logger?: Logger;
      /** Clock used for relative ages in the text output. */
      now?: () => Date;
    }

    defined in packages/mcp/src/server.ts

    Three things to know when embedding:

    • The instance is not closed with the server. Whoever created the Safran instance owns it, and one instance can back many servers; the HTTP handler creates one per request.
    • The default logger writes to stderr, warnings and errors only, and never to stdout. Pass logger to send it elsewhere.
    • budgets changes some output budgets and keeps the rest.

    SAFRAN_TOOLS lists every tool with its name, title, description, schemas and annotations, in the order of the reference. The full export list of the package is on the API page.