Reglyph MCP server: developer reference

Reglyph translates scanned and digital PDFs and keeps their layout. This reference is for developers who connect their own MCP client to Reglyph. It has Python and TypeScript examples that you can run.

To add Reglyph to Claude, ChatGPT, Cursor or another AI app, use the setup guide instead.

Endpoint
https://api.tryreglyph.com/mcp
Transport
Streamable HTTP with JSON responses and no session ID
Sign-in
OAuth authorization code flow with PKCE (S256), dynamic client registration and the email scope
Tools
get_account, request_upload, get_translation, list_translations

Reglyph doesn't offer a separate REST API or API keys. The only plain HTTP request is the file upload, and it only works with a link from request_upload.

Quickstart

You need a Reglyph account with enough pages for your PDF. If you don't have an account, signing in with Google when you connect creates it. get_account shows how many pages are left and where to add more.

A translation takes five steps:

  1. Connect to https://api.tryreglyph.com/mcp and sign in with OAuth.
  2. Call request_upload with the two languages. You get a link for one PDF. This doesn't use any pages.
  3. Upload the PDF to that link. This starts the translation, uses pages and gives you a job_id.
  4. Call get_translation about every 15 seconds until state is done or failed.
  5. Download the PDF from the link you get.

Both examples below do all five steps. To sign in, the Python one opens your browser, and the TypeScript one prints a link for you to open. Both then wait for the browser to come back to http://127.0.0.1:8765/callback. They save the translated PDF and a bilingual PDF next to the original, with the start of the job_id in their names.

Running an example uses pages

The upload uses pages from the account you sign in with, one for each page of the PDF. Start with a short file. To test only the sign-in, run the script with --list. That doesn't use any pages.

Both examples:

  • Ask before they upload. They don't count the PDF's pages. A real app should, so it can say how many will be used and whether any will be left out.
  • Upload the file once. Before the upload, they print two commands that help you find it if the script stops or it isn't clear whether the upload worked. After it, they print one with the job_id. None of these commands uploads the file again.
  • Check every 15 seconds. They stop when the translation is done or has failed, or after checking for 2 hours. If a check fails, they wait a minute and try again, and stop after 3 failures in a row. To keep the code short, they do this for any error except a failed sign-in. In your own client, follow Errors.
  • Only send the access token to the MCP server.
  • Keep the sign-in in memory. Each run registers a new client and asks you to sign in again, so the app may be listed more than once in Connected apps. Disconnect each one when you've finished testing. A real app should save the client ID and tokens safely.
  • Leave refreshing the token to the SDK. With mcp 2.3.0 and @modelcontextprotocol/client 2.4.0, even a temporary error while refreshing starts a new sign-in. The Python script asks you to sign in again. It also does that if the MCP server returns 401. The TypeScript script stops, so use one of the commands it printed to continue. Other versions may work differently. If you write this part yourself, follow Keep the sign-in working.

If a language has more than one word, put it in quotes, such as "Simplified Chinese".

Python

This needs Python 3.10 or later and uses the official mcp package, version 2.3 or a later 2.x. That also installs httpx2, which the script uses. If pip says the environment is externally managed, use a virtual environment. Save the code as translate.py.

Terminal
pip install "mcp>=2.3,<3"
python translate.py contract.pdf German English

When it works, the output looks like this. The TypeScript one is almost the same.

Example output
Sign in to Reglyph in your browser: https://example.com/authorize?client_id=EXAMPLE
contract.pdf: German to English
This uses one page for each page of the PDF. You have 42 left.
If it has more than 300 pages, the rest is left out.
Type yes to upload it: yes
Uploading. If this stops before you see a job_id, the upload may still have
worked, so don't upload the file again yet. Look for it in this list, and
again a minute later:
    python translate.py --list
If you can't tell which one it is, check this upload. If it says
waiting_for_upload, the upload may still have worked:
    python translate.py "contract.pdf" --job up_EXAMPLE
Upload accepted: the translation has started. The PDF has 12 pages; this upload used 12 pages.
If this stops, run: python translate.py "contract.pdf" --job 00000000-0000-4000-8000-000000000001
ocr: 3 of 12 pages
Saved contract.00000000.translated.pdf
Saved contract.00000000.bilingual.pdf
translate.py
"""Translate one PDF with the Reglyph MCP server. Needs Python 3.10 or later.

    pip install "mcp>=2.3,<3"
    python translate.py contract.pdf German English

To go back to a translation you already started, without uploading again:

    python translate.py contract.pdf --job ID

ID is its job_id, or the upload_id if you don't have a job_id yet.

To list the account's recent translations:

    python translate.py --list
"""
import asyncio
import signal
import sys
import threading
import time
import webbrowser
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.parse import parse_qs, urlparse

import httpx2  # installed with mcp
from mcp import Client, MCPError
from mcp.client.auth import AuthorizationCodeResult, OAuthClientProvider, OAuthFlowError
from mcp.client.streamable_http import streamable_http_client
from mcp.shared.auth import OAuthClientMetadata

SERVER_URL = "https://api.tryreglyph.com/mcp"
CALLBACK_PORT = 8765
SIGN_IN_TIMEOUT = 5 * 60     # seconds to finish signing in
POLL_SECONDS = 15            # the server asks for about 15 seconds between checks
MAX_WAIT = 2 * 60 * 60       # stop checking after 2 hours
RETRY_SECONDS = 60           # wait this long before trying a failed check again
MAX_TRIES = 3                # stop after 3 failures in a row
TIMEOUT = httpx2.Timeout(60, read=300, write=300)
REFUSED = {400, 401, 402, 410, 413, 429, 503}  # this upload started nothing
RECOVERY = """Uploading. If this stops before you see a job_id, the upload may still have
worked, so don't upload the file again yet. Look for it in this list, and
again a minute later:
    python translate.py --list
If you can't tell which one it is, check this upload. If it says
waiting_for_upload, the upload may still have worked:
    python translate.py "{pdf}" --job {upload_id}"""
UNCLEAR = ("It isn't clear whether the upload worked. Use the commands above before "
           "you upload the file again.")
USAGE = """Usage: python translate.py FILE.pdf SOURCE_LANGUAGE TARGET_LANGUAGE
       python translate.py FILE.pdf --job ID
       python translate.py --list"""


class CallFailed(RuntimeError):
    """A tool call was refused or didn't get an answer."""


class MemoryStorage:
    """Keeps the sign-in until the script ends. A real app should save both
    values somewhere safe, so people don't have to sign in every time."""

    def __init__(self):
        self.tokens = None
        self.client_info = None

    async def get_tokens(self):
        return self.tokens

    async def set_tokens(self, tokens):
        self.tokens = tokens

    async def get_client_info(self):
        return self.client_info

    async def set_client_info(self, client_info):
        self.client_info = client_info


class Callback(BaseHTTPRequestHandler):
    """Receives the browser's redirect after the person clicks Allow."""

    query = None

    def do_GET(self):
        url = urlparse(self.path)
        if url.path == "/callback":
            Callback.query = parse_qs(url.query)
        self.send_response(200 if url.path == "/callback" else 404)
        self.end_headers()
        self.wfile.write(b"You can close this tab.")

    def log_message(self, *args):
        pass


def sign_in_with_browser():
    """OAuth for the MCP connection: the SDK finds the sign-in server,
    registers this app, uses PKCE, checks state and refreshes the token. If
    it can't refresh, even briefly, it asks the person to sign in again."""
    # Threading, because browsers can open spare connections that send nothing.
    listener = ThreadingHTTPServer(("127.0.0.1", CALLBACK_PORT), Callback)
    threading.Thread(target=listener.serve_forever, daemon=True).start()

    async def open_browser(url):
        Callback.query = None
        print("Sign in to Reglyph in your browser:", url)
        webbrowser.open(url)

    async def wait_for_callback():
        deadline = time.monotonic() + SIGN_IN_TIMEOUT
        while Callback.query is None:
            if time.monotonic() > deadline:
                raise TimeoutError("Nobody finished signing in.")
            await asyncio.sleep(0.2)
        query = {name: values[0] for name, values in Callback.query.items()}
        if "code" not in query:
            raise RuntimeError("Sign-in was cancelled or refused.")
        return AuthorizationCodeResult(
            code=query["code"], state=query.get("state"), iss=query.get("iss"))

    auth = OAuthClientProvider(
        server_url=SERVER_URL,
        client_metadata=OAuthClientMetadata(
            client_name="Reglyph example",
            redirect_uris=[f"http://127.0.0.1:{CALLBACK_PORT}/callback"],
            token_endpoint_auth_method="none",
        ),
        storage=MemoryStorage(),
        redirect_handler=open_browser,
        callback_handler=wait_for_callback,
    )
    return auth, listener


async def call(mcp_http, tool, **arguments):
    """Call a tool. Each call opens its own connection, because in this SDK a
    dropped connection ends the client. The server doesn't keep sessions."""
    try:
        transport = streamable_http_client(SERVER_URL, http_client=mcp_http)
        async with Client(transport) as client:
            result = await client.call_tool(tool, arguments)
    except Exception as error:
        while hasattr(error, "exceptions"):  # the SDK can wrap errors in a group
            error = error.exceptions[0]
        if isinstance(error, (httpx2.HTTPError, MCPError)):
            raise CallFailed(f"{tool} didn't work: {error}") from error
        raise error  # for example, the sign-in failed
    # A refused call is still a normal MCP result, so check is_error.
    if result.is_error:
        raise CallFailed(result.content[0].text)
    return result.structured_content


async def check(mcp_http, job_id):
    """Call get_translation. It only reads, so it's safe to try again."""
    for attempt in range(1, MAX_TRIES + 1):
        try:
            return await call(mcp_http, "get_translation", job_id=job_id)
        except CallFailed as error:
            if attempt == MAX_TRIES:
                raise
            print(f"{error}\nTrying again in {RETRY_SECONDS} seconds.")
            await asyncio.sleep(RETRY_SECONDS)


def confirm(pdf, source_lang, target_lang, account):
    """Ask before uploading. A real app should also count the PDF's pages, and
    say how many it will use and whether any will be left out."""
    print(f"{pdf.name}: {source_lang} to {target_lang}")
    print("This uses one page for each page of the PDF. "
          f"You have {account['pages_left']} left.")
    print(f"If it has more than {account['max_pages_per_job']} pages, the rest is left out.")
    if account["plan"] == "free":
        print("If that isn't enough, it only translates as many pages as you have, "
              "starting from page 1. For a PDF over 50 pages, that's at most 50.")
    # asyncio holds back Ctrl-C while input() waits, so use the usual handler here.
    handler = signal.signal(signal.SIGINT, signal.default_int_handler)
    try:
        return input("Type yes to upload it: ").strip().lower() == "yes"
    except EOFError:  # there's nobody to ask
        return False
    finally:
        signal.signal(signal.SIGINT, handler)


async def upload(http, link, pdf):
    """Send the file once. This starts the translation and uses pages."""
    # Print this first: if the script stops now, nothing else says what to do.
    print(RECOVERY.format(pdf=pdf, upload_id=link["upload_id"]), flush=True)
    try:
        with pdf.open("rb") as file:
            response = await http.post(
                link["upload_url"],
                files={link["form_field"]: (pdf.name, file, "application/pdf")})
        answer = response.json()
    except (httpx2.HTTPError, ValueError) as error:
        raise RuntimeError(UNCLEAR) from error
    if response.status_code == 200:
        print(answer["message"])
        return answer["job_id"]
    if response.status_code in REFUSED:
        raise RuntimeError(f"HTTP {response.status_code}: "
                           f"{answer.get('detail')} {answer.get('next', '')}")
    raise RuntimeError(UNCLEAR)  # for example, a 409 or 500


async def wait_until_done(mcp_http, job_id):
    """Check every 15 seconds. Stops when it's done, failed or out of time."""
    deadline = time.monotonic() + MAX_WAIT
    while True:
        job = await check(mcp_http, job_id)
        if job.get("job_id", job_id) != job_id:
            job_id = job["job_id"]  # use this from now on: an upload_id can stop working
            print("job_id:", job_id, flush=True)
        if job["state"] == "done":
            return job
        if job["state"] == "failed":
            raise RuntimeError(f"{job['error']}\n{job['next']}")
        # waiting_for_upload has no page counts. Anything else is still running.
        print(f"{job['state']}: {job.get('pages_done', 0)} of "
              f"{job.get('pages_total', 0)} pages")
        if time.monotonic() >= deadline:
            raise TimeoutError("It's still running. Check it again later with --job.")
        await asyncio.sleep(max(POLL_SECONDS, job.get("next_poll_seconds", 0)))


async def get_bilingual(mcp_http, job_id):
    """Ask for the bilingual PDF, at most 3 times in all. A failed call and a
    bilingual_status, such as "the server is busy", both count."""
    for attempt in range(1, MAX_TRIES + 1):
        try:
            job = await call(mcp_http, "get_translation",
                             job_id=job_id, include_bilingual=True)
            if "bilingual_status" not in job or attempt == MAX_TRIES:
                return job
            problem = job["bilingual_status"]
        except CallFailed as error:
            if attempt == MAX_TRIES:
                raise
            problem = error
        print(f"{problem}\nTrying again in {RETRY_SECONDS} seconds.")
        await asyncio.sleep(RETRY_SECONDS)


async def download(http, url, path):
    """Save a file. An unfinished download keeps the .part name."""
    part = path.with_name(path.name + ".part")
    async with http.stream("GET", url) as response:
        if response.status_code != 200:  # the message leaves out the private link
            raise RuntimeError(f"Download failed: HTTP {response.status_code}. "
                               "Use --job to get a new link.")
        with part.open("wb") as file:
            async for chunk in response.aiter_bytes():
                file.write(chunk)
    part.replace(path)
    print("Saved", path)


async def show_list(mcp_http):
    answer = await call(mcp_http, "list_translations")
    for job in answer["translations"]:
        print(job["created_at"], job["state"], job["name"],
              job["target_lang"], job["job_id"])


async def start(mcp_http, http, pdf, source_lang, target_lang):
    account = await call(mcp_http, "get_account")
    if pdf.stat().st_size > account["max_file_mb"] * 1024 * 1024:
        raise RuntimeError(f"This file is over {account['max_file_mb']} MB.")
    if not confirm(pdf, source_lang, target_lang, account):
        raise RuntimeError("Nothing was uploaded.")
    link = await call(mcp_http, "request_upload", filename=pdf.name,
                      source_lang=source_lang, target_lang=target_lang,
                      bilingual=True)
    job_id = await upload(http, link, pdf)
    print(f'If this stops, run: python translate.py "{pdf}" --job {job_id}', flush=True)
    return job_id


async def save_result(mcp_http, http, job_id, pdf):
    job = await wait_until_done(mcp_http, job_id)
    if job["pages_failed"]:
        print(f"Pages still in the original language: {job['pages_failed']}")
    if "note" in job:
        print(job["note"])
    if "download_url" not in job:
        raise RuntimeError("The translated file isn't available any more.")
    # The ID keeps each translation's files apart. Save this one first, so a
    # problem with the bilingual PDF can't stop it.
    name = f"{pdf.stem}.{job['job_id'][:8]}"
    await download(http, job["download_url"], pdf.with_name(f"{name}.translated.pdf"))

    job = await get_bilingual(mcp_http, job["job_id"])
    if "bilingual_download_url" in job:
        await download(http, job["bilingual_download_url"],
                       pdf.with_name(f"{name}.bilingual.pdf"))
    else:
        print(job.get("bilingual_status", "There's no bilingual PDF."))


async def main(pdf=None, source_lang=None, target_lang=None, job_id=None):
    auth, listener = sign_in_with_browser()
    try:
        # Two HTTP clients: the sign-in token goes only to the MCP server,
        # never to the upload or download links.
        async with (
            httpx2.AsyncClient(auth=auth, timeout=TIMEOUT) as mcp_http,
            httpx2.AsyncClient(timeout=TIMEOUT) as http,
        ):
            if pdf is None:
                await show_list(mcp_http)
                return
            if job_id is None:
                job_id = await start(mcp_http, http, pdf, source_lang, target_lang)
            await save_result(mcp_http, http, job_id, pdf)
    finally:
        listener.shutdown()
        listener.server_close()


if __name__ == "__main__":
    args = sys.argv[1:]
    if args == ["--list"]:
        options = {}
    elif len(args) != 3:
        sys.exit(USAGE)
    elif args[1] == "--job":
        options = {"pdf": Path(args[0]), "job_id": args[2]}
    elif Path(args[0]).is_file():
        options = {"pdf": Path(args[0]), "source_lang": args[1], "target_lang": args[2]}
    else:
        sys.exit(f"Can't find {args[0]}")
    try:
        asyncio.run(main(**options))
    except (RuntimeError, OSError, httpx2.HTTPError, OAuthFlowError) as problem:
        sys.exit(str(problem) or type(problem).__name__)
    except KeyboardInterrupt:
        sys.exit("Stopped. If the upload had started, use the commands above first.")

TypeScript

This uses the official @modelcontextprotocol/client package, version 2.4 or a later 2.x. Node.js 22.18 or later runs the file without a build step. Save the code as translate.mts.

Terminal
npm install "@modelcontextprotocol/client@^2.4"
node translate.mts contract.pdf German English
translate.mts
// Translate one PDF with the Reglyph MCP server.
//
//   npm install "@modelcontextprotocol/client@^2.4"
//   node translate.mts contract.pdf German English
//
// To go back to a translation you already started, without uploading again:
//
//   node translate.mts contract.pdf --job ID
//
// ID is its job_id, or the upload_id if you don't have a job_id yet.
//
// To list the account's recent translations:
//
//   node translate.mts --list
//
// Node.js 22.18 or later runs this file as it is.
import { randomBytes } from "node:crypto";
import { once } from "node:events";
import { existsSync, openAsBlob, statSync } from "node:fs";
import { writeFile } from "node:fs/promises";
import { createServer } from "node:http";
import { basename } from "node:path";
import { createInterface } from "node:readline/promises";
import { setTimeout as sleep } from "node:timers/promises";
import {
  Client,
  StreamableHTTPClientTransport,
  UnauthorizedError,
  type OAuthClientProvider,
  type OAuthDiscoveryState,
  type StoredOAuthClientInformation,
  type StoredOAuthTokens,
} from "@modelcontextprotocol/client";

const SERVER_URL = new URL("https://api.tryreglyph.com/mcp");
const CALLBACK_PORT = 8765;
const REDIRECT_URL = `http://127.0.0.1:${CALLBACK_PORT}/callback`;
const SIGN_IN_TIMEOUT = 5 * 60_000; // 5 minutes to finish signing in
const POLL_MS = 15_000; // the server asks for about 15 seconds between checks
const MAX_WAIT = 2 * 60 * 60_000; // stop checking after 2 hours
const RETRY_MS = 60_000; // wait this long before trying a failed check again
const MAX_TRIES = 3; // stop after 3 failures in a row
const CALL_TIMEOUT = 5 * 60_000; // making a bilingual PDF can take over a minute
const REFUSED = [400, 401, 402, 410, 413, 429, 503]; // this upload started nothing
const USAGE = `Usage: node translate.mts FILE.pdf SOURCE_LANGUAGE TARGET_LANGUAGE
       node translate.mts FILE.pdf --job ID
       node translate.mts --list`;

type Json = Record<string, any>;

const recovery = (pdf: string, uploadId: string) =>
  `Uploading. If this stops before you see a job_id, the upload may still have
worked, so don't upload the file again yet. Look for it in this list, and
again a minute later:
    node translate.mts --list
If you can't tell which one it is, check this upload. If it says
waiting_for_upload, the upload may still have worked:
    node translate.mts "${pdf}" --job ${uploadId}`;
const UNCLEAR =
  "It isn't clear whether the upload worked. Use the commands above before " +
  "you upload the file again.";

class NeedsSignIn extends Error {}

// Keeps the sign-in until the script ends. A real app should save the client
// information and tokens somewhere safe, so people don't sign in every time.
let clientInfo: StoredOAuthClientInformation | undefined;
let tokens: StoredOAuthTokens | undefined;
let discovery: OAuthDiscoveryState | undefined;
let codeVerifier = "";
let expectedState = "";
let connected = false;

const authProvider: OAuthClientProvider = {
  redirectUrl: REDIRECT_URL,
  clientMetadata: {
    client_name: "Reglyph example",
    redirect_uris: [REDIRECT_URL],
    token_endpoint_auth_method: "none",
    grant_types: ["authorization_code", "refresh_token"],
    response_types: ["code"],
  },
  state: () => (expectedState = randomBytes(32).toString("base64url")),
  clientInformation: () => clientInfo,
  saveClientInformation: (info) => void (clientInfo = info),
  tokens: () => tokens,
  saveTokens: (saved) => void (tokens = saved),
  // Lets the SDK check that the sign-in came back from the server it started with.
  discoveryState: () => discovery,
  saveDiscoveryState: (found) => void (discovery = found),
  // The SDK calls this when the saved sign-in no longer works.
  invalidateCredentials: (what) => {
    if (what === "all" || what === "tokens") tokens = undefined;
    if (what === "all" || what === "client") clientInfo = undefined;
    if (what === "all" || what === "discovery") discovery = undefined;
  },
  saveCodeVerifier: (verifier) => void (codeVerifier = verifier),
  codeVerifier: () => codeVerifier,
  redirectToAuthorization: (url) => {
    // The SDK refreshes the token when it can. If it can't, even briefly, it
    // starts a new sign-in. Stop instead, because nothing is listening for one.
    if (connected) {
      throw new NeedsSignIn(
        "Couldn't refresh the sign-in. If the upload had started, use the commands above first.",
      );
    }
    console.log("Open this link in your browser and sign in to Reglyph:\n" + url.href);
  },
};

/** Waits for the browser to come back after the person clicks Allow. */
function listenForCallback() {
  let finish!: (params: URLSearchParams) => void;
  let fail!: (error: Error) => void;
  const params = new Promise<URLSearchParams>((resolve, reject) => {
    finish = resolve;
    fail = reject;
  });
  params.catch(() => {}); // only matters if we end up needing to sign in
  const server = createServer((request, response) => {
    const url = URL.parse(request.url ?? "/", REDIRECT_URL); // null if it isn't valid
    const found = url?.pathname === "/callback";
    response.writeHead(found ? 200 : 404, { Connection: "close" });
    response.end("You can close this tab.");
    if (url && found) finish(url.searchParams);
  });
  server.on("error", fail);
  server.listen(CALLBACK_PORT, "127.0.0.1");
  const timer = setTimeout(() => fail(new Error("Nobody finished signing in.")), SIGN_IN_TIMEOUT);
  const close = () => {
    clearTimeout(timer);
    server.close();
    server.closeAllConnections(); // browsers can keep spare connections open
  };
  return { params, close };
}

/** Connects, and signs in first if needed. */
async function connect(): Promise<Client> {
  const newClient = () => new Client({ name: "reglyph-example", version: "1.0.0" });
  const newTransport = () => new StreamableHTTPClientTransport(SERVER_URL, { authProvider });

  const callback = listenForCallback();
  try {
    const transport = newTransport();
    const client = newClient();
    try {
      await client.connect(transport);
      return client;
    } catch (error) {
      if (!(error instanceof UnauthorizedError)) throw error;
    }
    const params = await callback.params;
    // The SDK doesn't check this, so check it before using anything else.
    if (!expectedState || params.get("state") !== expectedState) {
      throw new Error("This sign-in wasn't started here.");
    }
    if (!params.has("code")) throw new Error("Sign-in was cancelled or refused.");
    await transport.finishAuth(params);
    const signedIn = newClient();
    await signedIn.connect(newTransport());
    return signedIn;
  } finally {
    connected = true;
    callback.close();
  }
}

/** Calls a tool. A refused call is still a normal MCP result: check isError. */
async function call(client: Client, name: string, args: Json = {}): Promise<Json> {
  const result = await client.callTool({ name, arguments: args }, { timeout: CALL_TIMEOUT });
  if (result.isError) {
    const first = result.content[0];
    throw new Error(first?.type === "text" ? first.text : `${name} failed`);
  }
  return result.structuredContent as Json;
}

/** Calls get_translation. It only reads, so it's safe to try again. */
async function check(client: Client, jobId: string): Promise<Json> {
  for (let attempt = 1; ; attempt++) {
    try {
      return await call(client, "get_translation", { job_id: jobId });
    } catch (error) {
      if (error instanceof NeedsSignIn || attempt === MAX_TRIES) throw error;
      console.log(`${(error as Error).message}\nTrying again in ${RETRY_MS / 1000} seconds.`);
      await sleep(RETRY_MS);
    }
  }
}

/** Asks before uploading. A real app should also count the PDF's pages, and
 * say how many it will use and whether any will be left out. */
async function confirm(name: string, languages: string, account: Json): Promise<boolean> {
  console.log(`${name}: ${languages}`);
  console.log(`This uses one page for each page of the PDF. You have ${account.pages_left} left.`);
  console.log(`If it has more than ${account.max_pages_per_job} pages, the rest is left out.`);
  if (account.plan === "free") {
    console.log(
      "If that isn't enough, it only translates as many pages as you have, " +
        "starting from page 1. For a PDF over 50 pages, that's at most 50.",
    );
  }
  const prompt = createInterface({ input: process.stdin, output: process.stdout });
  const closed = once(prompt, "close").then(() => "no"); // there's nobody to ask
  try {
    const answer = await Promise.race([prompt.question("Type yes to upload it: "), closed]);
    return answer.trim().toLowerCase() === "yes";
  } finally {
    prompt.close();
  }
}

/** Sends the file once. This starts the translation and uses pages. */
async function upload(link: Json, pdf: string): Promise<string> {
  const form = new FormData();
  form.append(link.form_field, await openAsBlob(pdf, { type: "application/pdf" }), basename(pdf));
  // Print this first: if the script stops now, nothing else says what to do.
  console.log(recovery(pdf, link.upload_id));
  let response: Response;
  let answer: Json;
  try {
    // No Authorization header: the link itself allows this one upload.
    response = await fetch(link.upload_url, {
      method: "POST",
      body: form,
      signal: AbortSignal.timeout(15 * 60_000),
    });
    answer = (await response.json()) as Json;
  } catch (error) {
    throw new Error(UNCLEAR, { cause: error });
  }
  if (response.status === 200) {
    console.log(answer.message);
    return answer.job_id;
  }
  if (REFUSED.includes(response.status)) {
    throw new Error(`HTTP ${response.status}: ${answer.detail} ${answer.next ?? ""}`);
  }
  throw new Error(UNCLEAR); // for example, a 409 or 500
}

/** Checks every 15 seconds. Stops when it's done, failed or out of time. */
async function waitUntilDone(client: Client, jobId: string): Promise<Json> {
  const deadline = Date.now() + MAX_WAIT;
  for (;;) {
    const job = await check(client, jobId);
    if (job.job_id && job.job_id !== jobId) {
      jobId = job.job_id; // use this from now on: an upload_id can stop working
      console.log("job_id:", jobId);
    }
    if (job.state === "done") return job;
    if (job.state === "failed") throw new Error(`${job.error}\n${job.next}`);
    // waiting_for_upload has no page counts. Anything else is still running.
    console.log(`${job.state}: ${job.pages_done ?? 0} of ${job.pages_total ?? 0} pages`);
    if (Date.now() >= deadline) {
      throw new Error("It's still running. Check it again later with --job.");
    }
    await sleep(Math.max(POLL_MS, (job.next_poll_seconds ?? 0) * 1000));
  }
}

/** Asks for the bilingual PDF, at most 3 times in all. A failed call and a
 * bilingual_status, such as "the server is busy", both count. */
async function getBilingual(client: Client, jobId: string): Promise<Json> {
  for (let attempt = 1; ; attempt++) {
    let problem: string;
    try {
      const args = { job_id: jobId, include_bilingual: true };
      const job = await call(client, "get_translation", args);
      if (!job.bilingual_status || attempt === MAX_TRIES) return job;
      problem = job.bilingual_status;
    } catch (error) {
      if (error instanceof NeedsSignIn || attempt === MAX_TRIES) throw error;
      problem = (error as Error).message;
    }
    console.log(`${problem}\nTrying again in ${RETRY_MS / 1000} seconds.`);
    await sleep(RETRY_MS);
  }
}

async function download(url: string, path: string): Promise<void> {
  const response = await fetch(url, { signal: AbortSignal.timeout(10 * 60_000) });
  if (!response.ok) {
    // The message leaves out the link, which is private.
    throw new Error(`Download failed: HTTP ${response.status}. Use --job to get a new link.`);
  }
  await writeFile(path, new Uint8Array(await response.arrayBuffer()));
  console.log("Saved", path);
}

async function showList(client: Client): Promise<void> {
  const { translations } = await call(client, "list_translations");
  for (const job of translations) {
    console.log(job.created_at, job.state, job.name, job.target_lang, job.job_id);
  }
}

async function start(client: Client, pdf: string, source: string, target: string): Promise<string> {
  const account = await call(client, "get_account");
  if (statSync(pdf).size > account.max_file_mb * 1024 * 1024) {
    throw new Error(`This file is over ${account.max_file_mb} MB.`);
  }
  if (!(await confirm(basename(pdf), `${source} to ${target}`, account))) {
    throw new Error("Nothing was uploaded.");
  }
  const link = await call(client, "request_upload", {
    filename: basename(pdf),
    source_lang: source,
    target_lang: target,
    bilingual: true,
  });
  const jobId = await upload(link, pdf);
  console.log(`If this stops, run: node translate.mts "${pdf}" --job ${jobId}`);
  return jobId;
}

async function saveResult(client: Client, jobId: string, pdf: string): Promise<void> {
  const job = await waitUntilDone(client, jobId);
  if (job.pages_failed) {
    console.log(`Pages still in the original language: ${job.pages_failed}`);
  }
  if (job.note) console.log(job.note);
  if (!job.download_url) throw new Error("The translated file isn't available any more.");
  // The ID keeps each translation's files apart. Save this one first, so a
  // problem with the bilingual PDF can't stop it.
  const name = `${pdf.replace(/\.pdf$/i, "")}.${job.job_id.slice(0, 8)}`;
  await download(job.download_url, `${name}.translated.pdf`);

  const bilingual = await getBilingual(client, job.job_id);
  if (bilingual.bilingual_download_url) {
    await download(bilingual.bilingual_download_url, `${name}.bilingual.pdf`);
  } else {
    console.log(bilingual.bilingual_status ?? "There's no bilingual PDF.");
  }
}

async function main(args: string[]): Promise<void> {
  const list = args.length === 1 && args[0] === "--list";
  if (!list && args.length !== 3) throw new Error(USAGE);
  const [pdf = "", second = "", third = ""] = args;
  const resume = second === "--job";
  if (!list && !resume && !existsSync(pdf)) throw new Error(`Can't find ${pdf}`);

  const client = await connect();
  try {
    if (list) return await showList(client);
    const jobId = resume ? third : await start(client, pdf, second, third);
    await saveResult(client, jobId, pdf);
  } finally {
    await client.close();
  }
}

process.once("SIGINT", () => {
  console.error("Stopped. If the upload had started, use the commands above first.");
  process.exit(130);
});
await main(process.argv.slice(2)).catch((error: Error) => {
  console.error(error.message);
  process.exitCode = 1;
});

Connect and sign in

Official MCP SDKs can handle this for you. Here is what happens, in case you're writing the client yourself or looking into a problem.

1. Find the sign-in server

Without a valid access token, the server returns HTTP 401. The WWW-Authenticate header says where to look next and which scope to ask for:

401 header
WWW-Authenticate: Bearer resource_metadata="https://api.tryreglyph.com/.well-known/oauth-protected-resource/mcp", scope="email"

If a token was sent but isn't valid or has expired, the header also has error="invalid_token".

The address in resource_metadata returns:

Protected resource metadata
{
  "resource": "https://api.tryreglyph.com/mcp",
  "authorization_servers": [
    "https://api.tryreglyph.com"
  ],
  "scopes_supported": [
    "email"
  ],
  "bearer_methods_supported": [
    "header"
  ],
  "resource_name": "Reglyph"
}

Then read the sign-in server's metadata:

Terminal
curl -sS https://api.tryreglyph.com/.well-known/oauth-authorization-server

It lists the authorization_endpoint, token_endpoint and registration_endpoint. Use these addresses as they are. They can be on another host and can change, so don't hard-code them.

2. Register your client

Send a POST request to the registration_endpoint. The response includes your client_id. Save it so you can use it again. This is the body for a desktop or command-line app, which can't keep a client secret:

Registration request body
{
  "client_name": "Your app",
  "redirect_uris": [
    "http://127.0.0.1:8765/callback"
  ],
  "grant_types": [
    "authorization_code",
    "refresh_token"
  ],
  "response_types": [
    "code"
  ],
  "token_endpoint_auth_method": "none",
  "scope": "email offline_access"
}
  • Redirect address: use HTTP on localhost or 127.0.0.1 for an app on the person's computer. Otherwise, use HTTPS. Register the exact address, including any port.
  • Backend: if it can keep a secret, set token_endpoint_auth_method to client_secret_basic or client_secret_post. The response then includes a client_secret. Use the same method in step 4. Each person signs in separately, so keep their tokens apart.

3. Ask the person to sign in

Open the authorization_endpoint with these parameters in the person's usual browser. Google doesn't allow signing in from a browser embedded in an app. The person signs in to Reglyph, checks the request and clicks Allow.

ParameterValue
response_typecode
client_idThe ID from step 2
redirect_uriExactly the same as one you registered, including the port
scopeemail offline_access. Leave out offline_access if your client doesn't use refresh tokens. Both SDKs in the quickstart choose these for you.
stateA new random value. When the browser comes back, stop if it's different. If your SDK doesn't check this, your code has to.
code_challengeThe PKCE challenge, with code_challenge_method=S256
resourcehttps://api.tryreglyph.com/mcp

Don't ask for openid. Reglyph doesn't give apps this permission, so the request is refused.

4. Get and use the access token

When the browser comes back with a code, send it to the token_endpoint with your PKCE verifier. Send form fields, not JSON:

Terminal
curl -sS "$TOKEN_ENDPOINT" \
  --data-urlencode "grant_type=authorization_code" \
  --data-urlencode "code=$CODE" \
  --data-urlencode "code_verifier=$CODE_VERIFIER" \
  --data-urlencode "client_id=$CLIENT_ID" \
  --data-urlencode "redirect_uri=http://127.0.0.1:8765/callback" \
  --data-urlencode "resource=https://api.tryreglyph.com/mcp"

This is for a client without a secret. With client_secret_post, add client_secret. With client_secret_basic, send the ID and secret with HTTP Basic authentication instead of client_id. Do the same when you refresh the token.

The JSON answer has access_token, token_type, expires_in and usually refresh_token. Send the access token with every MCP request:

Request header
Authorization: Bearer ACCESS_TOKEN

expires_in is how many seconds the access token is valid for. If you have a refresh token, use it to get a new one:

Terminal
curl -sS "$TOKEN_ENDPOINT" \
  --data-urlencode "grant_type=refresh_token" \
  --data-urlencode "refresh_token=$REFRESH_TOKEN" \
  --data-urlencode "client_id=$CLIENT_ID" \
  --data-urlencode "resource=https://api.tryreglyph.com/mcp"

5. Keep the sign-in working

  • Refresh one at a time for each sign-in. If the answer has a new refresh_token, save it in place of the old one before you do anything else. Using an old one can end the sign-in.
  • If the refresh returns HTTP 408, 409, 429 or 5xx, or there's no answer, keep the tokens, wait a minute and try again. Stop after 3 tries.
  • If it returns any other 4xx, ask the person to sign in again.
  • If the MCP server returns 401, refresh the token once and send the request once more. If it's still 401, or you don't have a refresh token, ask the person to sign in again.
  • If signing in with a saved client ID doesn't work, check client_id and redirect_uri. The browser may show an error instead of coming back. If they're right, the client may no longer be registered. Register it again once, delete the tokens you got with the old ID, and ask the person to sign in.

A connected app can't make payments. People can disconnect it at any time in Connected apps. Its access token then stops working within a minute, and the server returns 401.

Requests and results

Call the server from a desktop app, a command-line tool or your own backend. JavaScript on another website can't call it, because the server doesn't accept cross-origin (CORS) requests from other sites. Don't upload that way either: the translation could start, but your page couldn't read the answer. Use your backend or upload_page_url.

The server uses JSON-RPC 2.0 over HTTP POST. If you aren't using an SDK, do the MCP handshake once when your client starts. Send initialize. Use the result.protocolVersion in the answer, or stop if your client doesn't support it. Then send notifications/initialized.

initialize
{
  "jsonrpc": "2.0",
  "id": 0,
  "method": "initialize",
  "params": {
    "protocolVersion": "2025-06-18",
    "capabilities": {},
    "clientInfo": {
      "name": "your-app",
      "version": "1.0.0"
    }
  }
}
notifications/initialized
{
  "jsonrpc": "2.0",
  "method": "notifications/initialized"
}

The notification returns HTTP 202 with no body. There's no session ID to keep. Send the protocol version you agreed on in the MCP-Protocol-Version header of later requests. For example, after the handshake, this calls a tool:

Terminal
curl -sS https://api.tryreglyph.com/mcp \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -H "Accept: application/json, text/event-stream" \
  -H "MCP-Protocol-Version: 2025-06-18" \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"get_account","arguments":{}}}'

Only POST is needed. Don't send GET to open a stream, because the request may just wait without getting anything. Content-Type has to be application/json, and Accept has to allow it. Call tools/list for the current tool descriptions and input schemas. The output schemas don't list fields, so use the tables below.

Read the result

  • Check isError first. A failed tool call still returns HTTP 200.
  • If it's false, read the data in structuredContent. content[0].text has the same data as JSON text.
  • If it's true, content[0].text says what went wrong. There's no structuredContent.
  • message and next are written for an AI assistant, so they can say “Tell the user”. Tool errors can too. If your app doesn't use an AI assistant, write your own text from the other fields. The examples print them as they are.
  • The tables below say when each field is included. New fields can be added, so ignore any you don't know.

The responses on this page are examples. Their IDs, links, names and dates are placeholders. Except for get_account, successful tool responses only show structuredContent.

get_account

Returns the person's plan, the pages they have left and the file limits. Read-only. No parameters.

Full response
{
  "jsonrpc": "2.0",
  "id": 1,
  "result": {
    "content": [
      {
        "type": "text",
        "text": "{\n  \"plan\": \"lite\",\n  \"pages_left\": 42,\n  \"max_file_mb\": 100,\n  \"max_pages_per_job\": 300,\n  \"account_url\": \"https://tryreglyph.com/app/billing\"\n}"
      }
    ],
    "structuredContent": {
      "plan": "lite",
      "pages_left": 42,
      "max_file_mb": 100,
      "max_pages_per_job": 300,
      "account_url": "https://tryreglyph.com/app/billing"
    },
    "isError": false
  }
}

All of these fields are always included:

FieldTypeDescription
planstringfree, lite or pro. free means there's no subscription. The account can still have pages it bought.
pages_leftintegerPages the account can use now.
max_file_mbintegerThe largest file allowed, in MB. 1 MB is 1,048,576 bytes.
max_pages_per_jobintegerThe most pages one translation can have. If a PDF is longer, the rest is left out.
account_urlstringWhere the person can see their pages and add more.

request_upload

Returns a link for uploading one PDF. Calling it doesn't start a translation or use any pages. The upload does.

ParameterTypeRequiredDescription
filenamestringYesThe PDF's name or path. It's only used to fill in the curl command.
source_langstringYesThe language the PDF is in. Use a name from the language list.
target_langstringYesThe language you want, from the same list. It can't be the same as source_lang.
bilingualbooleanNo. Default: falseMake a PDF with the original and the translation side by side during the translation, so it's usually ready sooner. It doesn't use extra pages. To get its link, use include_bilingual in get_translation. That also works if this was false.
Request
{
  "jsonrpc": "2.0",
  "id": 2,
  "method": "tools/call",
  "params": {
    "name": "request_upload",
    "arguments": {
      "filename": "contract.pdf",
      "source_lang": "German",
      "target_lang": "English",
      "bilingual": true
    }
  }
}
Response (structuredContent)
{
  "upload_id": "up_EXAMPLE",
  "upload_url": "https://api.tryreglyph.com/api/agent/upload?ticket=EXAMPLE",
  "method": "POST",
  "form_field": "file",
  "expires_in_seconds": 900,
  "max_pages": 300,
  "curl": "curl -sS -F 'file=@\"contract.pdf\"' -w '\\nHTTP %{http_code}\\n' 'https://api.tryreglyph.com/api/agent/upload?ticket=EXAMPLE'",
  "upload_page_url": "https://tryreglyph.com/app/agent-upload#EXAMPLE",
  "next": "Over 300 pages? Only the first 300 would be translated: split the PDF before uploading. Run curl and read its answer: job_id and a message, or why it was refused and what to do. If no JSON comes back (a timeout, a 502), call list_translations before uploading again: it may have worked. If you can't run commands, give the user upload_page_url to open in a browser. Then call get_translation with the job_id or with upload_id about every 15 seconds until state is 'done' or 'failed'."
}

All of these fields are always included:

FieldTypeDescription
upload_idstringFollow this upload with get_translation until you have a job_id, for example when the person uploads the file in their browser. Then use the job_id, because an upload_id can stop working.
upload_urlstringThe link to send the file to. Use it exactly as it is.
methodstringAlways POST.
form_fieldstringThe form field for the file. Always file.
expires_in_secondsintegerHow long the link is valid for: 900, or 15 minutes. The upload has to finish before then.
max_pagesintegerThe most pages one translation can have. Check the PDF's length before you upload it, and split it if it's longer.
curlstringA command for bash or zsh that uploads the file, for AI assistants that can run commands. In your own code, use upload_url. It prints the JSON answer, then a last line such as HTTP 200, which isn't part of the JSON.
upload_page_urlstringA page where the person can pick the file in their browser. Use this if your app can't send the file. Like curl, it contains the upload link, so keep it private.
nextstringWhat to do next.

Upload the PDF

Send the PDF to upload_url in a multipart/form-data POST request, in the field file. Include a file name, or you get HTTP 400. The file name becomes the translation's name. The part's Content-Type isn't checked. Don't send the access token: the link is enough. Each link can start one translation.

Terminal
curl -sS -F 'file=@"contract.pdf"' -w '\nHTTP %{http_code}\n' "$UPLOAD_URL"

If the upload is accepted, you get HTTP 200 and the translation starts. None of the tools can cancel it.

200 response
{
  "job_id": "00000000-0000-4000-8000-000000000001",
  "document_pages": 12,
  "pages_charged": 12,
  "message": "Upload accepted: the translation has started. The PDF has 12 pages; this upload used 12 pages.",
  "next": "Call get_translation with this job_id about every 15 seconds until state is 'done' or 'failed'."
}

duplicate is only included when it's true. The other fields are always included:

FieldTypeDescription
job_idstringThe translation's ID. Use it with get_translation.
document_pagesintegerHow many pages the PDF has.
pages_chargedintegerHow many pages this upload used.
duplicatebooleanYou got an earlier translation instead of a new one.
messagestringWhat happened, including any pages that were left out. Make sure the person knows about those.
nextstringWhat to do next.

When fewer pages are translated

  • The PDF has more than 300 pages. At most the first 300 are translated and charged. Only this answer says so: get_translation and the browser upload page don't. If you didn't see it and pages_total is 300, compare that with the PDF's length.
  • The account doesn't have enough pages and has no subscription. The first pages it can pay for are translated. For files over 50 pages, that's at most 50. With Lite or Pro, the upload is refused with HTTP 402 instead.

In both cases, pages_charged is lower than document_pages, and message says why. If duplicate is true, pages_charged is always 0, so check whether document_pages is over 300 instead. For example, for a 320-page PDF:

200 response: only the first 300 pages
{
  "job_id": "00000000-0000-4000-8000-000000000001",
  "document_pages": 320,
  "pages_charged": 300,
  "message": "Upload accepted: the translation has started. The PDF has 320 pages; this upload used 300 pages. Only the first 300 pages can be in one translation, so what comes after page 300 is left out. Tell the user: to translate that too, save it as a separate PDF and upload it (it uses pages as usual).",
  "next": "Call get_translation with this job_id about every 15 seconds until state is 'done' or 'failed'."
}

Uploading the same file again

If the same account uploads the same file within 24 hours, with the same languages and bilingual choice, it normally gets the earlier translation and no pages are used:

200 response: same file again
{
  "job_id": "00000000-0000-4000-8000-000000000001",
  "duplicate": true,
  "document_pages": 12,
  "pages_charged": 0,
  "message": "This account already has a translation of this same file into the same language, so that one was returned instead of starting another. No pages were used. The PDF has 12 pages.",
  "next": "Call get_translation with this job_id about every 15 seconds until state is 'done' or 'failed'."
}

A new translation starts, and uses pages, if the earlier one failed, had pages that couldn't be translated, was deleted, no longer has its file, or only covered the first pages because the account didn't have enough. A server update can also clear the record of earlier uploads, so don't rely on this to avoid charges.

If you want the bilingual PDF of a file that's already translated, call get_translation with its job_id and include_bilingual. Don't upload it again. With a different bilingual choice, that's a new translation, and it uses pages again.

Upload in the browser

If your app can't send the file, tell the person to split a PDF that has more than 300 pages, then give them upload_page_url. They don't need to sign in there. The translation uses pages from the account that requested the link. Call get_translation with the upload_id about every 15 seconds. Once the file is uploaded, the answer includes its job_id. Use that from then on, because the upload_id can stop working if the server restarts.

Use expires_in_seconds to work out when the link expires. If there's still no job_id by then, stop checking. Before you request a new link, ask the person if they uploaded the file. If they did, ask for its name and check whether it worked.

Check whether an upload worked

After an HTTP 409 or 500, or if there's no clear answer, the translation may have started and used pages. Check before you upload the file again:

  1. Call list_translations. Look for a new translation with the same name and target_lang. name is the file name sent with the upload, not the filename in request_upload. If more than one could be the right one, ask the person.
  2. If it isn't there, wait a minute and check once more.
  3. If it still isn't there, ask the person before you upload the file again. Tell them it could use pages again: the check for repeated files can't be relied on to prevent that.
  4. If they agree, call request_upload and upload the file once with the new link. Don't use the old link, even if it still works. If that fails too, stop and tell the person.

To see which translations are new, save the job_ids from list_translations before you upload. Otherwise, use created_at, which comes from the server's clock. You can also call get_translation with the upload_id. If the answer has a job_id, that's your translation, so use that ID from then on. But waiting_for_upload doesn't mean the upload failed, so check the list too.

get_translation

Returns a translation's progress, then links for downloading the result. Read-only.

ParameterTypeRequiredDescription
job_idstringYesThe job_id from the upload, or the upload_id from request_upload.
include_bilingualbooleanNo. Default: falseAlso return a link for the bilingual PDF. If it isn't ready yet, making it can take more than a minute. Only ask once the translation is done, and let the call take up to 5 minutes.
Request
{
  "jsonrpc": "2.0",
  "id": 3,
  "method": "tools/call",
  "params": {
    "name": "get_translation",
    "arguments": {
      "job_id": "00000000-0000-4000-8000-000000000001",
      "include_bilingual": true
    }
  }
}

States

stateMeaningWhat to do
waiting_for_uploadNo file yet. You only get this with an upload_id.Check again after next_poll_seconds.
doneThe translation is finished.Download the PDF. Check pages_failed and note to see if any pages weren't translated.
failedThe translation failed.Stop, show error and do what next says. Check refunded to see if the pages were given back.
Anything elseIt's still running, for example ocr. These values can change.Check again after next_poll_seconds. Don't rely on the exact value.

Wait about 15 seconds between checks, and set a maximum time. A long PDF can take more than an hour. If you reach your limit, keep the job_id and check it later. Don't upload the file again.

waiting_for_upload (structuredContent)
{
  "upload_id": "up_EXAMPLE",
  "state": "waiting_for_upload",
  "next_poll_seconds": 15,
  "expires_in_seconds": 840
}
Running (structuredContent)
{
  "job_id": "00000000-0000-4000-8000-000000000001",
  "name": "contract.pdf",
  "state": "ocr",
  "pages_done": 3,
  "pages_failed": 0,
  "pages_total": 12,
  "refunded": false,
  "web_url": "https://tryreglyph.com/app/compare/00000000-0000-4000-8000-000000000001",
  "next_poll_seconds": 15
}
done, with include_bilingual (structuredContent)
{
  "job_id": "00000000-0000-4000-8000-000000000001",
  "name": "contract.pdf",
  "state": "done",
  "pages_done": 12,
  "pages_failed": 0,
  "pages_total": 12,
  "refunded": false,
  "web_url": "https://tryreglyph.com/app/compare/00000000-0000-4000-8000-000000000001",
  "download_url": "https://example.com/translated.pdf?signature=EXAMPLE",
  "download_url_expires_in_seconds": 600,
  "result_expires_at": "2026-12-02T09:34:00+00:00",
  "bilingual_download_url": "https://example.com/bilingual.pdf?signature=EXAMPLE"
}
failed (structuredContent)
{
  "job_id": "00000000-0000-4000-8000-000000000001",
  "name": "contract.pdf",
  "state": "failed",
  "pages_done": 0,
  "pages_failed": 0,
  "pages_total": 12,
  "refunded": true,
  "web_url": "https://tryreglyph.com/app/compare/00000000-0000-4000-8000-000000000001",
  "error": "Translation failed",
  "error_kind": "permanent_internal",
  "next": "Every page was given back. Tell the user. The same PDF can be uploaded once more (request_upload); if that fails too, stop: the user can write to support@tryreglyph.com with this job_id."
}

Fields

While state is waiting_for_upload, you only get upload_id, state, next_poll_seconds and expires_in_seconds, the seconds left to finish the upload. After that:

FieldTypeIncludedDescription
job_idstringAlwaysThe translation's ID.
namestringAlwaysThe PDF's file name.
statestringAlwaysSee the table above.
pages_doneintegerAlwaysPages translated so far, not counting failed ones.
pages_failedintegerAlwaysPages that couldn't be translated. They stay in the original language, and the person gets those pages back when the translation is done.
pages_totalintegerAlwaysPages in this translation. It can be 0 at the start.
refundedbooleanAlwaystrue if the translation failed and all its pages were given back. If it failed and this is false, it hadn't used any pages.
web_urlstringAlwaysWhere the person can sign in and compare the original with the translation.
next_poll_secondsintegerWhile it's runningHow many seconds to wait before checking again.
document_pagesintegerIf there weren't enough pages to translate all of itHow many pages could have been translated. For a PDF over 300 pages, this is at most 300. The upload's answer has the full number.
notestringWith document_pagesHow many pages this translation covers, in words.
download_urlstringIf it's done and the file is availableThe link to the translated PDF. If it's done but there's no link, the file can't be downloaded, for example because it has been deleted.
download_url_expires_in_secondsintegerWith download_urlHow long it's valid for when it's created, 600 seconds. If it has expired, call the tool again.
result_expires_atstringWith download_url, if knownWhen the files will be deleted (ISO 8601). It's about 24 hours after the translation is done.
bilingual_download_urlstringIf it's done, you used include_bilingual and the bilingual PDF is readyA separate link to the bilingual PDF. It's valid for 10 minutes from when it's created.
bilingual_statusstringIf it's done and you used include_bilingual, but the bilingual PDF can't be made right now or is too largeThe reason. You can wait a minute and ask again, up to 3 times in all. If you get neither this nor a link, there's no bilingual PDF.
errorstringIf it failedWhat went wrong.
error_kindstring or nullIf it failedA short code, or null. With result_too_large, split the PDF and upload the parts. With anything else, do what next says. More codes can be added.
nextstringIf it failedWhat to do next.

Download the files

Send a GET request to download_url without the access token. Do the same with bilingual_download_url if there is one.

Terminal
curl -sS --fail -o contract.translated.pdf "$DOWNLOAD_URL"

list_translations

Returns the account's 20 most recent translations, newest first. This includes translations started on the website. Read-only. No parameters.

Use it to find a lost job_id, or to check whether an upload worked.

Response (structuredContent)
{
  "translations": [
    {
      "job_id": "00000000-0000-4000-8000-000000000001",
      "name": "contract.pdf",
      "state": "done",
      "pages": 12,
      "total_pages": 12,
      "quota_capped": false,
      "target_lang": "English",
      "created_at": "2026-12-01T09:30:00+00:00",
      "has_result": true,
      "result_expires_at": "2026-12-02T09:34:00+00:00",
      "refunded": false
    }
  ]
}

Each item in translations always has all of these fields. pages is the same as pages_total in get_translation, but total_pages isn't:

FieldTypeDescription
job_idstringThe translation's ID.
namestringThe PDF's file name.
statestringThe same as in get_translation, but never waiting_for_upload.
pagesintegerPages in this translation.
total_pagesintegerPages that could be translated, at most 300. This is higher than pages if the account didn't have enough pages.
quota_cappedbooleantrue if only part was translated because the account didn't have enough pages.
target_langstringThe language to translate into. It can be empty.
created_atstringWhen it was started (ISO 8601).
has_resultbooleanWhether the translated PDF is available. Call get_translation for a download link.
result_expires_atstring or nullWhen the files will be deleted (ISO 8601), or null if there's nothing to download.
refundedbooleantrue if the translation failed and all its pages were given back.

Errors

WhereHow to tellWhat to do
Sign-inNo code when the browser comes back, or an HTTP error from the registration or token endpointSay that the sign-in didn't work, and let the person try again. Don't retry on your own.
RefreshAn HTTP error or no answer from the token endpointSee Keep the sign-in working.
ConnectionHTTP 400, 401, 406 or another 4xx from the MCP server400: check the JSON-RPC body and the Content-Type and MCP-Protocol-Version headers. 401: see Keep the sign-in working. 406: fix the Accept header. Any other 4xx: don't retry on your own.
No answerA timeout, a dropped connection, or HTTP 500, 502, 503 or 504 from the MCP serverNone of the tools uses pages, so wait a minute and try again. Stop after 3 tries.
MCP requestA JSON-RPC errorRead error.code and error.message. This usually means there's a mistake in the client.
Tool callHTTP 200 and isError: trueRead content[0].text, and see Tool errors.
File uploadAn HTTP status other than 200, or no JSONdetail says what went wrong, and next says what to do. See Upload errors.
DownloadAn HTTP status other than 200The link may have expired. Call get_translation for a new one and try again. Stop after 3 tries. Do the same if the download stops early.

Use the status or isError to decide what your code does, not the wording of a message, which can change.

Tool errors

200 response: tool error
{
  "jsonrpc": "2.0",
  "id": 5,
  "result": {
    "content": [
      {
        "type": "text",
        "text": "Error executing tool request_upload: source_lang and target_lang are the same. Choose the language to translate into, or ask the user which one they want."
      }
    ],
    "isError": true
  }
}

Tool errors don't have codes. If an AI model makes the calls, pass it the whole message, which often says what to do next. If your code makes them:

  • If get_account, get_translation or list_translations fails, wait a minute and call it again. After 3 failures in a row, stop and show the message.
  • If request_upload fails, show the message and let the person decide what to do.

This table can help the person, or the model, fix the problem:

ToolProblemWhat to do
get_translationNo translation, or no upload, with this ID on the accountCall list_translations to find the right job_id. An upload_id can also stop working if the server restarts.
get_translationNothing was uploaded before the link expiredIf someone did send the file, check whether it worked. Otherwise, call request_upload for a new link.
request_uploadA language is missing, isn't supported, or is the same as the other oneUse two different names from the language list.
request_uploadThe account has no pages leftAsk the person to add pages on the Reglyph website.
request_upload3 translations are already queued or runningWait until one of them is done or has failed.
Any toolToo many calls in a minuteWait a minute, then call again.
Any toolReglyph couldn't answer just nowNo pages were used. Wait a minute, then call again. Stop after 3 failures in a row.
Any toolNot signed in to ReglyphAsk the person to connect again and sign in.

An unknown tool name or an invalid parameter is also returned as a tool error.

Upload errors

402 response
{
  "detail": "Not enough pages: 5 left, but this document needs 12. Add the pages you need and translate it now.",
  "next": "This upload used no pages. Tell the user: they can add pages at https://tryreglyph.com/app/billing, or choose a PDF with fewer pages. Then run the same upload again (or call request_upload first if the link has expired)."
}

If the answer isn't JSON, use the last row, whatever the status is. Do the same for a status that isn't in the table.

StatusProblemWhat to do
400No file arrived, or it isn't a PDF that opens and has pages.Fix the file or the form, then use the same link.
401The link isn't valid, for example because part of it is missing.Call request_upload for a new link and use it exactly as it is.
402The account doesn't have enough pages.Ask the person to add pages or choose a shorter PDF, then use the same link.
409The link was already used.Check whether an upload worked before you ask for a new link.
410The link has expired.If you sent the file to this link earlier, check whether it worked before you ask for a new one.
413The file is too large.Make it smaller, or split it and upload each part with its own link.
4293 translations are already queued or running, Reglyph is busy, or large files have reached today's limit.Don't retry on your own. Show detail, so the person knows when to try again with the same link.
500Something went wrong, and the translation may or may not have started.Don't upload again yet. Check whether it worked first.
503Reglyph is temporarily unavailable.Wait a minute, then use the same link. Stop after 3 refusals in a row.
No JSONA timeout, a dropped connection or a 502. The upload may have worked.Don't upload again yet. Check whether it worked first.

“Use the same link” only works until the link expires. After that, call request_upload for a new one.

A 429 doesn't have a code or Retry-After to say which limit was reached. If you have several files, use list_translations to keep at most 3 queued or running, and upload the next one when one is done.

Limits

WhatLimit
File typePDF only, scanned or digital
File size100 MB. Check max_file_mb for the account's limit.
Pages per translation300. Check max_pages or max_pages_per_job, and split longer PDFs first.
Files over 50 pagesThey share a daily limit across all Reglyph users. When it's reached, the upload returns 429 and no pages are used. Try again the next day (UTC).
Translations at once3 per account, queued or running, including ones started on the website
Tool calls30 a minute for each app connected to an account
Upload linksEach can start one translation. The upload has to finish within 15 minutes.
Download linksValid for 10 minutes from when they're created. Call the tool again for new ones.
File deletionDeleted about 24 hours after the translation is done

Each page of the PDF uses one page from the account. If a page can't be translated, the person gets it back when the translation is done. If the whole translation fails, they get all the pages back. This is machine translation, not certified translation.

Languages

Use these exact names, in English. They also appear as enum values in the input schema from tools/list.

For both source_lang and target_lang:

Arabic, Bulgarian, Catalan, Croatian, Czech, Danish, Dutch, English, Estonian, Filipino, Finnish, French, German, Greek, Hindi, Hungarian, Indonesian, Italian, Japanese, Korean, Latvian, Lithuanian, Malay, Marathi, Nepali, Norwegian, Polish, Portuguese, Romanian, Russian, Simplified Chinese, Slovak, Slovenian, Spanish, Swahili, Swedish, Thai, Traditional Chinese, Turkish, Ukrainian, Vietnamese.

For source_lang only: Georgian.

Keep accounts safe

  • Ask before you upload. Tell the person which file you're sending and how many pages it will use.
  • Keep tokens private. Only send the access token to https://api.tryreglyph.com/mcp. Only send the refresh token to the token_endpoint. Don't put either in logs.
  • Keep links private. Until they expire, anyone who has an upload link can upload a file to that account, and anyone who has a download link can open that PDF.
  • Tell people what your app can see. This includes their plan, pages left, recent translations and download links. The sign-in also gives your app their email address and sign-in method, and usually their name and picture.

Support

For help, or to report a security problem, email support@tryreglyph.com. Include the job_id and what happened. Don't send access tokens, refresh tokens, upload links, download links or confidential files.