# General Translation Overview: Использование ИИ-агентов для написания кода
URL: https://generaltranslation.com/ru/docs/overview/for-coding-agents.mdx
Docs index: https://generaltranslation.com/llms.txt
Description: Как использовать ИИ-агентов для написания кода и LLMs с General Translation, направляя их на стартовый промпт, машиночитаемую документацию, MCP-сервер и наше руководство по быстрому подключению агента.

General Translation создана для работы с ИИ-агентами для написания кода и LLMs. Библиотеки имеют открытый исходный код, конфигурация предсказуема, а документация публикуется в машиночитаемых форматах. Агент, такой как Cursor, Claude Code или Copilot, может добавить и запустить General Translation за вас, используя точный и актуальный контекст.

*Для полностью автоматизированной локализации, которая сама открывает pull request, используйте наш специализированный агент [Locadex](/docs/platform/locadex/quickstart), а не собственного агента.*

## Стартовый промпт [#start-prompt]

Промпт ниже запускает сеанс агента, который добавляет General Translation в ваш проект: агент читает точку входа документации, входит в систему с помощью [`gt login`](/docs/cli/reference/commands/login), выбирает проект, реализует первый перевод и проверяет результат. Именно через [`gt login`](/docs/cli/reference/commands/login) агент работает с платформой General Translation, поэтому промпт начинается с этой команды, а не с запроса API-ключа. Кнопка **Setup for Agents** на [generaltranslation.com](https://generaltranslation.com) копирует в точности этот текст; он же доступен в исходном виде по адресу [`/agent-prompt.md`](/agent-prompt.md). Команда [`init`](/docs/cli/reference/commands/init) из промпта проверена на `gt` 2.24.0 в только что созданном через `create-next-app` проекте: она не задаёт вопросов, устанавливает `gt-next`, добавляет [`GTProvider`](/docs/react/reference/components/gt-provider) в корневой макет и `withGTConfig` в `next.config.ts`, создаёт `loadTranslations.js` и `gt.config.json` и завершается событием об успешном выполнении.

````markdown title="agent-prompt.md"
# Get started with General Translation

I landed on https://generaltranslation.com and clicked "Setup for Agents". Help me add General Translation to my app, website, or content, and get a real translation working. Inspect the project you have access to, choose the appropriate integration with me, and implement it. Continue through setup, translation, and verification rather than stopping at a plan.

## About General Translation

General Translation (GT) combines open-source internationalization libraries, a translation CLI, and a hosted translation platform. Source content stays in your code or content files. The libraries render translations and format locale-sensitive values; the platform generates and manages translations. Locadex is an optional hosted agent that connects to GitHub and maintains localization through pull requests.

- Website: https://generaltranslation.com
- Dashboard: https://dash.generaltranslation.com
- Open-source libraries and CLI: https://github.com/generaltranslation/gt
- Documentation entry point: https://generaltranslation.com/llms.txt
- Complete documentation index: https://generaltranslation.com/llms-index.txt
- API specification: https://generaltranslation.com/openapi.yaml

Fetch the documentation entry point first, then the quickstart and references relevant to this project. Documentation pages are available as raw Markdown by appending `.mdx` to the page URL. Use the complete index when you need a page that is not in the curated index. Read current docs and installed command help instead of guessing APIs, flags, or framework setup. `gt auth` is not a command in current releases; use `gt login`. `gt generate` writes source templates without calling the API and is registered when the CLI detects `gt-next`, `gt-react`, `gt-react-native`, `gt-tanstack-start`, `gt-node`, `gt-vue`, `gt-flask`, or `gt-fastapi`. Use `gt translate` for hosted translation.

## Work with me

Read this entire prompt before acting. Respect the repository's instructions, package manager, architecture, design system, and existing changes.

First inspect the repository for the framework, router, app directory, existing i18n library, GT configuration, source language, and build scripts. In a monorepo, identify the specific app or content directory; do not run setup at the workspace root. Do not ask me things you can determine from the code.

If the intended project is unclear, ask one question: "What would you like to translate?" Offer concrete choices: this app or website, documentation or content files, a backend service, a connected content platform, or a small new demo. Include "Not sure, help me decide." Prefer your interactive question tool when available. If no repository is open, help me open one or choose a small demo before scaffolding anything.

Ask for missing decisions one at a time: source language, target languages, and the first page or workflow to translate. Preserve existing locale choices; do not assume the source language is English or invent target markets. If I want help choosing, propose one target language for the first working example. Reuse an existing i18n setup where appropriate instead of automatically migrating the entire application.

Explain the next meaningful step briefly, then do the work. Ask when a choice affects which organization/project you use, creates an unwanted duplicate, or changes the agreed scope. Once I have chosen the project, languages, and scope, proceed with the setup and translation needed for that outcome.

## Choose the right integration

Read the matching quickstart before making framework changes:

| Project | Integration | Quickstart |
| --- | --- | --- |
| Next.js App Router | `gt-next` | https://generaltranslation.com/docs/react/nextjs-quickstart.mdx |
| Next.js Pages Router | `gt-next` | https://generaltranslation.com/docs/react/nextjs-pages-router-quickstart.mdx |
| React SPA, including Vite | `gt-react` | https://generaltranslation.com/docs/react/react-spa-quickstart.mdx |
| Server-rendered React | `gt-react` | https://generaltranslation.com/docs/react/react-quickstart.mdx |
| TanStack Start | `gt-tanstack-start` | https://generaltranslation.com/docs/react/tanstack-start-quickstart.mdx |
| React Native or Expo | `gt-react-native` | https://generaltranslation.com/docs/react/react-native-quickstart.mdx |
| Vue | `gt-vue` | https://generaltranslation.com/docs/vue/quickstart.mdx |
| Node.js backend | `gt-node` | https://generaltranslation.com/docs/node/quickstart.mdx |
| Python backend | Follow the Python SDK guide | https://generaltranslation.com/docs/python/quickstart.mdx |
| JSON, MDX, Markdown, YAML, or existing translation files | `gt` CLI | https://generaltranslation.com/docs/cli/quickstart.mdx |
| Lower-level JavaScript translation | `generaltranslation` | https://generaltranslation.com/docs/platform/core/quickstart.mdx |

For Mintlify, Sanity, Storyblok, or Google Drive, fetch https://generaltranslation.com/docs/integrations/llms.txt and follow that integration's quickstart. Do not apply a React setup wizard to a content integration. If I want GT to continuously maintain localization through GitHub, read https://generaltranslation.com/docs/platform/locadex/quickstart.mdx and walk me through connecting the repository and creating the appropriate automation. Do not enable auto-merge or change paid plans without my direction.

## Run the CLI without questions

The CLI is interactive. When `init` or `configure` is missing an answer, it does not fail: it asks the question in the terminal and waits, with no timeout. In an agent session that wait never ends. So in this session:

- Always pass `--no-interactive`. With it, a missing answer is a hard error that lists the flags still needed and changes no file.
- Pass a flag for every question before you run the command. `--defaults` accepts the recommended local choices in one flag; you still need `--locales` and, outside local Vite and TanStack Start setups, `--dev-credentials` or `--no-dev-credentials`. Pass explicit `--default-locale`, `--locadex` or `--no-locadex`, `--react-setup` or `--no-react-setup`, and `--file-formats` values only when you want to override the defaults. Local Vite and TanStack Start setups default to `--no-live-translations`; pass `--live-translations` to opt in. Never combine the `--[no-]live-translations` and `--[no-]dev-credentials` flag families.
- Pass `--json` to `init` and `configure`. It implies `--no-interactive`, writes one result event to stdout and the rendered screen to stderr. `translate`, `upload`, `api`, `whoami`, `project create` and `api-key create` have no `--json` flag; `translate` prints a progress screen with terminal control sequences, so judge it by its exit code and by the files it writes: `public/_gt/<locale>.json`, `gt-lock.json` and `gt.config.json`.
- If a command prints a question and stops, you are inside an interactive prompt. End the process and rerun it with `--no-interactive` and the missing flag. Never type an answer into it, and never run a command whose questions you have not answered with flags.
- `gt login` is the one step that needs a person: it opens a browser and waits for the sign-in to finish. If no browser can open from this session, run it with `--no-browser`, give me the URL it prints, and wait for me to confirm. `translate`, `upload`, `api`, `whoami`, `project create` and `api-key create` ask nothing when their flags are complete; a missing required flag is an error.

## Sign in with `gt login`

Use account login for local CLI authentication. Do not begin by asking me to find and paste an API key.

The examples below use `npx gt@latest` to avoid an old local CLI. Use the project's package manager or a current installed `gt` binary when appropriate. Inspect the version and available commands first:

```bash
npm view gt version
npx gt@latest --help
npx gt@latest login --help
```

The CLI has no `--version` flag. `translate` prints "CLI Version: x.y.z" in its banner; `init --json` prints no banner. Read the published version with `npm view gt version` and the installed one from `node_modules/gt/package.json`.

This workflow requires a CLI release with `login`, `whoami`, and `api-key create`. If the installed CLI lacks them, check the latest published release. If they are still unavailable, explain the release blocker and continue with local integration work that does not require credentials. Do not silently substitute the older `gt auth` flow, invent flags, or install an unpublished branch into my project.

Check for an existing session with `npx gt@latest whoami`. If sign-in is needed, run:

```bash
npx gt@latest login
```

Let me complete signup/sign-in and authorization in the browser. Keep the command running while approval is pending. In a remote or headless terminal, use:

```bash
npx gt@latest login --no-browser
```

Show me the verification URL and code returned by that command; wait for successful authorization, then verify with `npx gt@latest whoami`. Do not ask for my password or extract OAuth tokens. Login authenticates the CLI; it does not by itself configure the app's project or create its runtime credentials.

## Select a project and create the credentials we need

Reuse an existing configured project if it is the intended one. Check for conflicting project IDs in configuration and environment variables without printing secret values. Do not overwrite existing credentials or create another key unnecessarily.

For a supported fresh app, run the setup wizard from the app directory after login, with every question answered by a flag. For a Next.js App Router app set up locally, with translations stored in the repository and an existing project reused:

```bash
npx gt@latest init --no-interactive --json --defaults \
  --default-locale <source-locale> --locales <target-locales> \
  --no-locadex --react-setup --file-formats none \
  --no-dev-credentials --project-id <project-id>
```

This run asks nothing, installs gt-next, adds GTProvider to the root layout, adds withGTConfig to next.config.ts, creates loadTranslations.js and gt.config.json, and ends with `{"type":"result","command":"init","outcome":"success"}`. The wizard does not wrap any page text in `<T>`, even though its completedSteps list says "wrapped JSX content". Internationalize every page yourself in step 4 of the implementation section. The wizard runs biome on the files it changes and may replace the project's indentation with tabs; restore the project's formatting. Ignore the warning "Unexpected export type in ./next.config.ts" when withGTConfig() was added correctly. Review the wizard's changes against the framework quickstart: automatic framework setup is experimental.

`--defaults` covers local storage and the translations directory; pass `--storage` and `--translations-dir` only for other values. `--no-dev-credentials --project-id <id>` writes projectId to gt.config.json and creates no env file. Use it when no development key is wanted. If you already have a development key, add `NEXT_PUBLIC_GT_PROJECT_ID` and `NEXT_PUBLIC_GT_DEV_API_KEY` to `.env.development.local` yourself. `--dev-credentials --project-id <id>` saves a new development key and the project ID to `.env.local` instead; `--create-project --org-id <id> --project-name <name>` creates the project first. `--no-react-setup` is for an app that already has the GT library; on an app without one it fails with "No GT runtime is installed, so select at least one file format to translate", which is right, since there would be nothing to translate. Pass `--locadex` only if we agreed to use hosted automation. Before a production build, move the development key (`NEXT_PUBLIC_GT_DEV_API_KEY` or `GT_DEV_API_KEY`) from `.env.local` to `.env.development.local`: `next dev` loads that file and `next build` does not, and a production build refuses to run with a development key present. A production build that ships local translation files needs no key.

If the app already has framework setup, configure it directly from the docs. Use the authenticated CLI to discover resources:

```bash
npx gt@latest api /v2/projects
npx gt@latest api /v2/orgs
```

Follow pagination when present by passing `nextCursor` as `?cursor=<value>`. `/v2/orgs` lists the organizations the signed-in user belongs to (an API key sees only its own). Creating a project also needs the `org:projects:create` permission in that organization; when `project create` is refused, ask me which organization to use or create the project in the Dashboard at https://dash.generaltranslation.com. Use actual returned IDs. Ask me to select when the destination is ambiguous. If my new account has no suitable organization, guide me through creating one at https://dash.generaltranslation.com, then retry discovery.

When a new project is needed in the chosen organization:

```bash
npx gt@latest project create \
  --org-id <selected-organization-id> \
  --name <agreed-project-name> \
  --default-locale <source-locale>
```

Use the returned project ID. `project create` may require an organization key; read `npx gt@latest project create --help` first and fall back to creating the project in the Dashboard. For endpoint details or a missing higher-level command, inspect `npx gt@latest api --spec` and the current API docs before making a request.

Local CLI operations can use the login session. Create separate project keys only where a runtime or unattended CI workflow needs one. Inspect `npx gt@latest api-key create --help` first. The command requires a key name and explicit permissions. A development runtime key needs `project:translations:generate`; a standard file translation workflow needs `project:files:read`, `project:files:write`, and `project:translations:enqueue`. Verify any additional operations against the API specification; do not grant every permission by default.

`gt api-key create` prints the secret once to stdout. Capture that output directly into protected, ignored local configuration or the intended secret store without displaying it in tool output, chat, or logs. Use `--project-id` for the selected project, `--name` for its purpose, and `--permission` for the required permissions. Confirm success and the variable names without showing the key.

Keep these credential roles distinct:

- CLI/CI and server credentials use `GT_API_KEY` and `GT_PROJECT_ID`. Never put `GT_API_KEY` in browser code or a public-prefixed variable.
- Development runtime translation uses `GT_DEV_API_KEY` and a project ID. Browser frameworks may need their documented public prefix, such as `VITE_GT_DEV_API_KEY`; for Next.js the wizard writes `NEXT_PUBLIC_GT_PROJECT_ID` and `NEXT_PUBLIC_GT_DEV_API_KEY`, and the CLI reads that project ID too, so `GT_PROJECT_ID` is only needed in CI. Only expose the narrowly scoped development key where the framework guide requires it; do not ship development credentials in production browser bundles.
- OAuth credentials belong in the CLI's credential store. Do not copy them into the app or CI.

Ensure local environment files are ignored by Git. Use placeholders in committed examples. Preserve unrelated environment settings. Logging in locally does not authenticate CI or a deployed server.

## Implement a complete first translation

1. Install the integration that matches the detected stack. For an existing project, make targeted changes and preserve its current behavior.
2. Create or update `gt.config.json` with the agreed source and target locales, source paths, and file mappings. Use the current configuration reference: https://generaltranslation.com/docs/cli/reference/config.mdx. Preserve existing settings. Configure translation output and loading together; for example, a Vite SPA's imported translation files must live within its source tree. Do not copy one framework's output path or provider setup into another framework. Add the translation output directory (for example `public/_gt/`) to `.gitignore` when translations are not committed.
3. Follow the framework's initialization and routing guide. Next.js App Router and Pages Router differ; React SPAs use `initializeGTSPA` before rendering; server runtimes need request-aware locale handling. Read the installed version's APIs before implementing them.
4. Internationalize the agreed page or workflow, including visible text, validation, placeholders, accessible labels, and metadata where relevant. In React, use `<T>` for coherent static JSX. For standalone strings in gt-next, use `useGT()` in client components and in synchronous server components, and `getGT()` from `gt-next/server` in async server components and in `generateMetadata`. `useGT()` returns the function directly. For Next.js metadata, replace the static `metadata` export with `export async function generateMetadata()` that calls `getGT()` from `gt-next/server` and returns the translated title and description. Use `<Var>` or the framework's interpolation API for dynamic values; keep private values out of translation source. Use locale-aware number, date, currency, and plural handling. Follow the matching Vue, Node, or Python APIs for those stacks.
5. Add a language switcher to a suitable place in an app's existing UI. In gt-next, `<LocaleSelector>` from `gt-next` renders directly inside a server component page; it carries its own client boundary. Give it an `aria-label` through `useGT()`. Preserve navigation and verify the selected locale survives navigation or reload as documented. For a backend or content-only project, verify locale selection and translated output through its actual API or content workflow instead.
6. Add useful context for ambiguous copy. Use the `context` prop on `<T>` and the `$context` option in `gt()` and `getGT()` calls. `$context` on `<T>` is a deprecated alias that the CLI flags when it scans the source. Preserve product names and terminology. Do not send secrets or runtime user data as translation source. For content files, preserve frontmatter, links, variables, and formatting according to the format guide.
7. Inspect the translation scope with `npx gt@latest translate --dry-run`, then run `npx gt@latest translate` for the agreed languages and scope. If this would unexpectedly translate a large corpus or exceed the agreed scope, clarify that before submitting it. `gt translate` also writes `gt-lock.json` and a `_versionId` into `gt.config.json`; commit both. Use the connected-platform workflow instead when the integration requires one.

## Verify and finish

Выполни проверку типов (`npx tsc --noEmit`) и production-сборку (`next build`). Запускай линтер и тесты, только если они уже настроены в проекте. Если доступны инструменты браузера, запусти приложение и проверь, как на самом деле выглядит переведённый интерфейс: переключайся между исходной и целевыми локалями, переходи по страницам, перезагружай их, проверяй интерполяцию и вёрстку. Запрос без заголовка `Accept-Language` и без cookie отображает локаль по умолчанию и при каждом поиске перевода пишет в лог предупреждение «gt-next: No locale could be determined»; для curl без заголовка это ожидаемое поведение. Чтобы проверить целевую локаль, отправь `Accept-Language: <target-locale>` или `Cookie: generaltranslation.locale=<target-locale>`. Если это актуально для выбранного языка, проверь отображение длинного текста и вёрстку справа налево. Для бэкенд- и контент-проектов изучи реальные переведённые ответы или файлы. Не утверждай, что проверил результат в браузере, если не смог этого сделать.

Устрани ошибки настройки и среды выполнения, прежде чем считать интеграцию завершённой. Если застрял, загрузи соответствующий справочный раздел и разберись в ошибках команд, вместо того чтобы раз за разом заново создавать проекты или ключи.

Для приложений с заранее сгенерированными переводами настрой production-рабочий процесс так, чтобы перевод выполнялся до существующей сборки, а сгенерированные файлы были доступны в среде выполнения. Сохрани существующие шаги сборки, задокументируй имена секретов CI и проверь требования выбранной интеграции к локальным файлам или CDN. Если переводы закоммичены, а ключа для CI нет, оставь скрипт сборки без изменений. При каждом изменении исходного текста запускай `npx gt@latest translate` локально в авторизованной сессии, затем коммить `public/_gt/<locale>.json`, `gt-lock.json` и `gt.config.json`. Добавляй `npx gt translate` в скрипт сборки, только если в CI задан `GT_API_KEY` с разрешениями на запись файлов и постановку переводов в очередь. Используй `--publish`, только если этого требует выбранный рабочий процесс с CDN. Не выполняй развёртывание в production и не сливай pull request'ы, если я об этом не просил.

В завершение дай краткую сводку: что изменилось, какой проект и какие локали настроены, как всё запустить, что ты действительно проверил и что ещё осталось сделать мне. Приложи ссылки на соответствующую документацию и Dashboard, но не указывай учётные данные. Ожидаемый результат — работающий перевод в моём проекте и понятный способ поддерживать его в актуальном состоянии.
````

## Руководство по быстрому подключению агента [#agent-guide]

Дайте своему агенту всё необходимое одной вставкой. Скопируйте приведённое ниже руководство в `AGENTS.md` (или `CLAUDE.md`, правило Cursor либо файл инструкций вашего инструмента) в корне проекта, и ваш агент сможет корректно добавить и запустить General Translation. Используйте кнопку копирования в правом верхнем углу блока или получите то же руководство напрямую из [`/AGENTS.md`](/AGENTS.md).

````markdown title="AGENTS.md"
# General Translation — agent guide

Instructions for AI coding agents adding [General Translation](https://generaltranslation.com) to a project. General Translation is a full-stack localization product: open-source i18n libraries plus a CLI that translate an app and its content into any language. Follow these rules when internationalizing code or wiring up translations.

## What to use

Pick the package that matches the stack:

- **Next.js (App Router or Pages Router)** → `gt-next`
- **React (SPA, e.g. Vite)** → `gt-react`
- **TanStack Start** → `gt-tanstack-start`
- **Vue 3** → `gt-vue`
- **Node.js server** → `gt-node`
- **Any JavaScript runtime, or lower-level control** → `generaltranslation` (the Core library)
- **Translating content files (JSON, MDX, YAML, and more) or running translation in CI** → the `gt` CLI

All of these are free and open-source. The libraries work with or without a General Translation account; an API key unlocks on-demand translation in development and the hosted translation API.

## Setup

For a new setup, run from the app directory with `--no-interactive` and a flag for every question. Without `--no-interactive`, a missing answer opens a question in the terminal and the command waits for it; with it, a missing answer is an error that lists the flags still needed and changes no file:

```bash
npx gt init --no-interactive --json --defaults --default-locale en --locales fr es --no-locadex --react-setup --file-formats none --no-dev-credentials
```

For a local Vite or TanStack Start setup, replace `--no-dev-credentials` with `--no-live-translations`. Do not pass both credential flag families.

The wizard detects the framework, creates or updates `gt.config.json`, and can select/create a project and provision a development runtime key. Creating a project or key without a tooling key or saved login signs in first, which a person must approve. Framework rewrites are experimental and need review. Review [init flags and side effects](/docs/cli/reference/commands/init) before running it.

For manual setup, install the packages yourself:

```bash
npm install gt-next   # or gt-react / gt-node / generaltranslation
npm install -D gt
```

Then create `gt.config.json` in the project root — this is the single source of truth for locales:

```json
{
  "defaultLocale": "en",
  "locales": ["es", "fr", "ja"],
  "files": { "gt": { "output": "public/_gt/[locale].json" } }
}
```

- `defaultLocale` — the language the source is written in.
- `locales` — the languages to translate into.
- `files.gt.output` — where the CLI writes translation files (`[locale]` is replaced per language). Add this directory to `.gitignore`; the files are generated.

For a manually configured app, have the developer run `npx gt login`, then bind an existing project with `projectId` in the config or `GT_PROJECT_ID` in the environment. Login does not select a project or write env files; do not rerun init just to authenticate.

For CI, commit the config and inject a separately scoped tooling key through the CI secret store:

```bash
GT_API_KEY="your-api-key"   # Права на весь сценарий работы с CLI, а не только на генерацию
GT_PROJECT_ID="your-project-id"
```

CLI login, runtime development keys, and CI tooling keys are separate. SDKs do not read CLI sessions; init's development runtime key does not replace `GT_API_KEY`. Never commit keys or include them in deployed browser/mobile bundles.

Read [CLI credentials](/docs/cli/guides/configuring#credentials) before configuring authentication. Require human approval for login and key creation; `--no-browser` and quiet mode do not make login unattended.

## Core usage

Wrap user-facing JSX in `<T>`. Write source copy directly — no translation keys needed:

```tsx
import { T } from 'gt-next'; // or 'gt-react'

// Everything inside <T> is translated as a unit
<T>
  <h1>Welcome to my app</h1>
</T>;
```

Use `useGT()` for standalone strings (placeholders, `aria-label`, `alt`, button labels). `useGT()` returns the translation function directly:

```tsx
import { useGT } from 'gt-next';

const gt = useGT(); // ✅ correct
// const { gt } = useGT(); // ❌ wrong — useGT returns the function, not an object

<input placeholder={gt('Search products')} />;
```

In async App Router components, use `getGT` instead. `gt-next/server` does not work with the Pages Router:

```tsx
import { getGT } from 'gt-next/server';

const gt = await getGT();
```

Wrap dynamic or private values (names, emails, IDs) in `<Var>` so they are not translated and never sent to the API. Use `<Currency>`, `<DateTime>`, and `<Num>` for values that should be reformatted but not translated:

```tsx
import { T, Var } from 'gt-next';

// Generates one translation, keeps the name unchanged
<T>
  Hello, <Var>{name}</Var>!
</T>;
```

For Node.js servers, initialize once and resolve translations per request:

```js
import { initializeGT, withGT, getGT } from 'gt-node';

initializeGT({ defaultLocale: 'en', locales: ['en', 'es', 'fr'] });
// оборачивайте обработчики в withGT(locale, ...); затем внутри них `const gt = await getGT()`
```

Держите всю конфигурацию локалей в `gt.config.json` — не разбрасывайте списки локалей по кодовой базе.

## Команды

| Команда                          | Когда запускать                                                                                                                                                     |
| -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `npx gt init` | Пошаговая настройка; с `--no-interactive` и флагами работает без интерактивного режима. Может изменять файлы фреймворка, зависимости, конфигурацию и учётные данные для runtime. |
| `npx gt configure` | Настройка без переписывания React-кода; принимает те же флаги, кроме настройки фреймворка. Может устанавливать зависимости и выдавать учётные данные для runtime. Если нужно изменить только конфигурацию, правьте её вручную. |
| `npx gt login` | Попросите разработчика подтвердить доступ к аккаунту для работы с CLI. |
| `npx gt translate`               | Чтобы перевести проект через API General Translation. Запускайте в CI **перед** сборкой для продакшена; добавляйте `--save-local`, только если сначала нужно синхронизировать локальные правки. |
| `npx gt generate` | Чтобы создать исходные шаблоны для ручного перевода без обращения к API. Доступна для поддерживаемых пакетов, перечисленных в справочнике по [`gt generate`](/docs/cli/reference/commands/generate). |
| `npx gt translate --dry-run` | Чтобы оценить объём перевода, не обращаясь к API и не записывая файлы перевода. |
| `npx gt api --list` | Чтобы вывести список операций API, поставляемых с установленным CLI. |
| `npx gt api --spec <endpoint>` | Чтобы просмотреть одну поставляемую операцию API по ID операции, пути в спецификации или конкретному пути запроса. Не указывайте endpoint, чтобы получить полную спецификацию. |
| `npx gt api <endpoint>`          | Чтобы выполнить аутентифицированный низкоуровневый запрос к API из скрипта или терминала.                                                                                                 |
| `npx gt project create --org-id <orgId> --name <name> --default-locale <locale>` | С разрешения пользователя создайте проект от имени вошедшего пользователя или с ключом организации, у которого есть право org:projects:create. |
| `npx gt project status <job-id>` | Чтобы просмотреть задачу перевода или генерации контекста проекта.                                                                                                         |

Добавьте перевод в продакшен-сборку, чтобы переводы оставались актуальными, например: `"build": "npx gt translate && next build"`.

## Правила — что делать и чего не делать

Делайте:

- Оборачивайте каждый новый пользовательский текст в `<T>` (или `useGT()`/`getGT()` для отдельных строк) сразу при написании.
- Если у вас есть разрешение отправлять контент на облачный перевод, запускайте `npx gt translate` перед коммитом или сборкой для продакшена, чтобы новый текст был переведён.
- Храните список локалей только в `gt.config.json`.
- Оборачивайте динамические и приватные значения в `<Var>` и добавляйте `context`, когда строка неоднозначна.
- Если вы намеренно отредактировали сгенерированный файл перевода, запустите `npx gt save-local` перед следующим скачиванием переводов или передайте `--save-local` при следующем запуске перевода.

Не делайте:

- Не хардкодьте уже переведённые строки в исходниках и не добавляйте ветвления `if`/`switch` по языкам — вместо этого переводите исходный текст.
- Не редактируйте сгенерированные файлы переводов без синхронизации изменений: последующее скачивание может перезаписать несохранённые правки.
- Не коммитьте и не раскрывайте API-ключи, не выводите stdout создания ключей в общие логи и не выпускайте учётные данные без явного разрешения.
- Не дублируйте конфигурацию локалей вне `gt.config.json`.

## Ссылки

- [`llms.txt`](/llms.txt) — курируемая машиночитаемая точка входа в документацию.
- [`llms-index.txt`](/llms-index.txt) — исчерпывающий индекс всех страниц документации.
- [`llms-full.txt`](/llms-full.txt) — полное содержимое документации для инструментов, способных загрузить больший контекст.
- [Индекс React](/docs/react/llms.txt), [индекс CLI](/docs/cli/llms.txt) и [индекс OpenAPI](/docs/platform/openapi/llms.txt) — точки входа для типовых задач.
- [`AGENTS.md`](/AGENTS.md) — это готовое руководство в виде исходного Markdown.
- [`openapi.yaml`](/openapi.yaml) — каноническая спецификация API General Translation.
- [`sitemap.md`](/sitemap.md) — Markdown-индекс всех страниц документации и записей блога.
- [`sitemap.xml`](/sitemap.xml) — стандартная карта сайта для всех опубликованных страниц.
- Быстрые старты: [React](/docs/react/react-quickstart), [Vue](/docs/vue/quickstart), [Node](/docs/node/quickstart), [библиотека Core](/docs/platform/core/quickstart) и [CLI](/docs/cli/quickstart).
- [Ключевые концепции](/docs/overview/key-concepts) — локали, контекст, статический и динамический контент.
- Команды для работы с учётной записью: [`gt login`](/docs/cli/reference/commands/login) и [`gt api-key create`](/docs/cli/reference/commands/api-key-create).
- Справочник CLI: [`gt api`](/docs/cli/reference/commands/api), [`gt project create`](/docs/cli/reference/commands/project-create) и [`gt project status`](/docs/cli/reference/commands/project-status).
````

## Направьте агентов на документацию [#point-agents]

Дайте агенту прямой доступ к документации, чтобы его ответы оставались точными. General Translation публикует несколько машиночитаемых точек входа в корне сайта и по пути `/docs` на хосте документации:

* [`llms.txt`](/llms.txt) — тщательно отобранная точка входа в стиле [llmstxt.org](https://llmstxt.org/) с основными Quickstart и тематическими указателями.
* [`llms-index.txt`](/llms-index.txt) — исчерпывающий указатель ссылок на все опубликованные страницы документации.
* [`llms-full.txt`](/llms-full.txt) — полное содержимое документации в одном файле, без сгенерированного справочника OpenAPI.
* [`AGENTS.md`](/AGENTS.md) — приведённое выше готовое руководство в виде raw Markdown.
* [`agent-prompt.md`](/agent-prompt.md): приведённый выше стартовый промпт в виде raw Markdown.
* [`sitemap.md`](/sitemap.md) — указатель в формате Markdown по всем страницам документации и публикациям блога.
* [`sitemap.xml`](/sitemap.xml) — стандартная XML-карта сайта для всех опубликованных страниц.

Используйте узконаправленный указатель, если агент уже знает, какая часть продукта ему нужна:

* [Overview](/docs/overview/llms.txt)
* [Платформа](/docs/platform/llms.txt) с тематическими указателями для [Dashboard](/docs/platform/dashboard/llms.txt), [Locadex](/docs/platform/locadex/llms.txt), [Ядра](/docs/platform/core/llms.txt) и [OpenAPI](/docs/platform/openapi/llms.txt)
* [CLI](/docs/cli/llms.txt)
* [React](/docs/react/llms.txt)
* [Vue](/docs/vue/llms.txt)
* [Node.js](/docs/node/llms.txt)
* [Python](/docs/python/llms.txt)
* [Integrations](/docs/integrations/llms.txt)

Для работы с API используйте [бандл операций OpenAPI](/docs/platform/openapi/llms-full.txt) или каноническую спецификацию [`openapi.yaml`](/openapi.yaml) вместо парсинга интерактивных страниц эндпоинтов.

Хост документации также отдаёт корневые файлы по пути `/docs`, включая `/docs/llms.txt`, `/docs/llms-index.txt` и `/docs/llms-full.txt`. Каждая страница документации доступна в виде **raw Markdown**: добавьте `.md` или `.mdx` к URL любой страницы, чтобы получить чистый исходник вместо разбора отрендеренного HTML. Сгенерированные указатели и метаданные для обнаружения используют `.mdx`, например `/docs/cli/quickstart.mdx`.

Чтобы добавить документацию в качестве контекста, вставьте URL страницы документации или ссылку на `llms.txt` в контекст вашего агента либо добавьте документацию как источник в инструментах, поддерживающих индексацию документации.

## MCP-сервер [#mcp]

Используйте хостируемый сервер [Model Context Protocol](https://modelcontextprotocol.io) (MCP) по адресу `https://api.gtx.dev/mcp` для получения актуальной информации о проекте и управления контекстом. Он использует streamable HTTP.

Инструменты управления контекстом на этом сервере позволяют просматривать, создавать и обновлять контекстные группы, термины Glossary и Custom Prompts в них, выполнять импорт и экспорт, а также назначать группы проектам. Их возможности соответствуют [Context Management API](/docs/platform/openapi/reference/context-management/list-groups).

Хостируемый сервер также предоставляет [MCP-инструменты Google Drive](/docs/integrations/google-drive/reference/mcp-tools) для поиска подключённых проектов, перевода Google Docs и Google Slides, а также отслеживания прогресса перевода копий.

Добавьте подключение в конфигурационный файл MCP вашего инструмента (например, `.mcp.json`). Названия транспортов и поля конфигурации могут различаться в зависимости от клиента:

```json title=".mcp.json"
{
  "mcpServers": {
    "generaltranslation": {
      "type": "http",
      "url": "https://api.gtx.dev/mcp"
    }
  }
}
```

### Аутентификация в удалённом API

Подключайтесь через поток входа OAuth вашего MCP-клиента или настройте `Authorization: Bearer <api-key>` в его параметрах секретного заголовка. Подключения по API-ключу принимают ключи проекта (`gtx-api-`) и ключи организации (`gtx-org-`). Существующие ключи `gtx-dev-` по-прежнему проходят аутентификацию как ключи проекта. Каждый инструмент проверяет разрешения ключа для запрошенного действия. Настройте [пользовательские разрешения ключей](/docs/platform/dashboard/reference/api-keys) для тех инструментов, которые нужны вашему агенту.

Используйте `list_orgs`, чтобы найти ID организации, и `list_projects`, чтобы найти ID проекта. Ни одному из этих инструментов обнаружения не требуются разрешения на ресурсы. Передавайте полученные ID в другие инструменты как `orgId` и `projectId`. Ключи проекта и организации обнаруживают только привязанные к ним ресурсы, а ключ проекта может не указывать `projectId` — тогда используется его собственный проект.

Для инструментов управления контекстом требуется `org:context:read` или `org:context:write`. Предоставьте ключу организации соответствующее разрешение **Context** или авторизуйте такой же доступ к Context организации при входе через MCP OAuth. Ключи проекта для этих инструментов не подходят. Передайте `orgId` в `list_context_groups` и `create_context_group`, а `groupId` — в инструменты, работающие с существующей группой.

Размер тела MCP-запроса ограничен 100 МиБ. Отдельные инструменты могут устанавливать более строгие ограничения на свои входные данные.

После подключения попросите агента использовать MCP-сервер `generaltranslation`. Попробуйте: «Выведи список моих проектов и покажи настройки локалей для одного из них».

## Советы для отдельных редакторов [#editor-tips]

Большая часть настройки одинакова для всех агентов; вот лишь несколько моментов, где рекомендации отличаются.

* **Cursor** — зарегистрируйте MCP-сервер, затем попросите его «использовать инструмент `generaltranslation`». Добавьте документацию как источник или укажите в запросе `/llms.txt`.
* **Claude Code** — автоматически читает корневой `CLAUDE.md`, поэтому скопируйте [руководство по быстрому подключению агента](#agent-guide) в `CLAUDE.md` вашего проекта. Зарегистрируйте MCP-сервер и попросите его «использовать MCP-сервер `generaltranslation`».
* **Copilot** — поместите общие инструкции для всего репозитория в файл инструкций (например, `.github/copilot-instructions.md`) и укажите там `/llms.txt` из документации.

## Рекомендации [#best-practices]

Агенты хорошо справляются с механической i18n-работой, но качество перевода и конфигурацию всё равно должен проверять человек. Используйте такое разделение:

* **Поручите агенту:** оборачивать пользовательский текст в [`<T>`](/docs/react/reference/components/t), добавлять [`useGT()`](/docs/react/reference/hooks/use-gt) для отдельных строк и подготавливать `gt.config.json`. Перед запуском [`npx gt init`](/docs/cli/reference/commands/init) с `--dev-credentials` или `--create-project` агент должен запросить разрешение: эти флаги создают ключи или проекты.
* **Проверяйте вручную:** [контекст перевода](/docs/overview/key-concepts#context) (Glossary и Custom Prompts), который создаёт агент, конфигурацию локалей (`defaultLocale` и `locales`), а также то, что динамические или приватные значения обернуты в [`<Var>`](/docs/react/reference/components/var).
* **Никогда не позволяйте агенту:** создавать или раскрывать учётные данные без разрешения, редактировать сгенерированные файлы перевода без синхронизации изменений или хардкодить уже переведённые строки вместо перевода исходного текста через CLI.

## Sitemap

See the full [sitemap](https://generaltranslation.com/sitemap.md) for all pages.
