paperless-mcp
Paperless-NGX MCP Server
MCP-сервер (Model Context Protocol) для взаимодействия с API-сервером Paperless-NGX. Этот сервер предоставляет инструменты для управления документами, тегами, корреспондентами и типами документов в вашем экземпляре Paperless-NGX.
Быстрый старт
Установка
Добавьте это в ваш файл конфигурации MCP:
// Режим STDIO (рекомендуется для локального или CLI-использования)
"paperless": {
"command": "npx",
"args": [
"-y",
"@baruchiro/paperless-mcp@latest",
],
"env": {
"PAPERLESS_URL": "http://your-paperless-instance:8000",
"PAPERLESS_API_KEY": "your-api-token",
"PAPERLESS_PUBLIC_URL": "https://your-public-domain.com"
}
}// Режим HTTP (рекомендуется для Docker или удалённого использования)
"paperless": {
"command": "docker",
"args": [
"run",
"-i",
"--rm",
"ghcr.io/baruchiro/paperless-mcp:latest",
],
"env": {
"PAPERLESS_URL": "http://your-paperless-instance:8000",
"PAPERLESS_API_KEY": "your-api-token",
"PAPERLESS_PUBLIC_URL": "https://your-public-domain.com"
}
}Получите ваш API-токен:
Войдите в свой экземпляр Paperless-NGX
Нажмите на ваше имя пользователя в правом верхнем углу
Выберите "My Profile"
Нажмите кнопку с круговой стрелкой, чтобы сгенерировать новый токен
Замените заполнители в вашем файле конфигурации MCP:
http://your-paperless-instance:8000на URL вашего Paperless-NGXyour-api-tokenна только что сгенерированный токенhttps://your-public-domain.comна ваш публичный URL Paperless-NGX (необязательно, по умолчанию используется PAPERLESS_URL)
Переменные окружения
Переменная | Обязательная | По умолчанию | Описание |
| Да | — | Базовый URL вашего экземпляра Paperless-NGX |
| Да | — | API-токен из вашего профиля Paperless-NGX |
| Нет |
| Публичный URL для ссылок на документы |
| Нет |
| Версия REST API Paperless-ngx. |
| Нет | — | Разделённый двоеточием список разрешённых каталогов для загрузок через |
Вот и всё! Теперь вы можете попросить Claude помочь вам управлять документами Paperless-NGX.
Примеры использования
Вот что можно попросить Claude сделать:
«Покажи все документы с тегом „Invoice“»
«Найди документы, содержащие „tax return“»
«Создай новый тег „Receipts“ с цветом #FF0000»
«Скачай документ #123»
«Покажи всех корреспондентов»
«Создай новый тип документа „Bank Statement“»
Related MCP server: mcp-paperless-ngx
Доступные инструменты
Операции с документами
list_documents
Получить постраничный список документов с простыми фильтрами. Используйте это для простых задач вывода списка. Для полнотекстовых запросов, структурированной фильтрации по пользовательским полям или расширенных фильтров Paperless используйте query_documents.
Параметры:
page (необязательно): Номер страницы
page_size (необязательно): Количество документов на странице
search (необязательно): Простой поисковый запрос Paperless
correspondent (необязательно): ID корреспондента
document_type (необязательно): ID типа документа
tag (необязательно): ID тега
storage_path (необязательно): ID пути хранения
created__date__gte (необязательно): Дата создания не ранее YYYY-MM-DD
created__date__lte (необязательно): Дата создания не позднее YYYY-MM-DD
ordering (необязательно): Поле сортировки Paperless
archive_serial_number (необязательно): Архивный серийный номер
archive_serial_number__isnull (необязательно): Пуст ли архивный серийный номер
custom_field_query (необязательно): Сырая строка запроса пользовательских полей Paperless в формате JSON
custom_fields__icontains (необязательно): Поиск подстроки без учёта регистра по значениям пользовательских полей
list_documents({
page: 1,
page_size: 25
})query_documents
Канонический инструмент запроса документов. Поддерживает полнотекстовые запросы, простой поиск Paperless, фильтры пользовательских полей и документированные параметры запроса Paperless /api/documents/.
Параметры:
page (необязательно): Номер страницы
page_size (необязательно): Количество документов на странице
ordering (необязательно): Поле сортировки Paperless
query (необязательно): Строка полнотекстового запроса
search (необязательно): Простой поисковый запрос Paperless
more_like_id (необязательно): Найти документы, похожие на этот ID документа
correspondent (необязательно): ID корреспондента
document_type (необязательно): ID типа документа
tag (необязательно): ID тега
storage_path (необязательно): ID пути хранения
created__date__gte (необязательно): Дата создания не ранее YYYY-MM-DD
created__date__lte (необязательно): Дата создания не позднее YYYY-MM-DD
custom_field_query (необязательно): Структурированный запрос пользовательских полей Paperless с использованием листьев
[field_name_or_id, operator, value]или групп["AND" | "OR", [clause1, clause2]]paperless_filters (необязательно): Дополнительные документированные параметры запроса Paperless
/api/documents/, передаваемые как пары ключ/значение
// Full-text query
query_documents({
query: "invoice 2024"
})
// Simple search term
query_documents({
search: "acme"
})
// Custom field exact match
query_documents({
custom_field_query: ["Invoice Number", "exact", "12345"]
})
// Custom field empty
query_documents({
custom_field_query: ["OR", [
["Invoice Number", "isnull", true],
["Invoice Number", "exact", ""]
]]
})
// Custom field missing
query_documents({
custom_field_query: ["Invoice Number", "exists", false]
})
// Combined filters
query_documents({
query: "invoice",
tag: 5,
created__date__gte: "2024-01-01",
custom_field_query: ["Invoice Number", "exists", true]
})
// One documented Paperless filter that is not a first-class argument
query_documents({
paperless_filters: {
id__in: [101, 202, 303]
}
})get_document
Получить конкретный документ по ID.
Параметры:
id: ID документа
get_document({
id: 123
})search_documents
Устаревшая обёртка совместимости для полнотекстового поиска. Для новых интеграций предпочитайте query_documents({ query: ... }).
Параметры:
query: Строка поискового запроса
search_documents({
query: "invoice 2024"
})download_document
Скачать файл документа по ID.
Параметры:
id: ID документа
original (необязательно): Если true, скачивает исходный файл вместо архивированной версии
download_document({
id: 123,
original: false
})get_document_thumbnail
Получить миниатюру документа (предпросмотр изображения) по ID. Возвращает миниатюру как ресурс изображения WebP в кодировке base64.
Параметры:
id: ID документа
get_document_thumbnail({
id: 123
})bulk_edit_documents
Выполнить массовые операции над несколькими документами.
Параметры:
documents: Массив ID документов
method: Одно из:
set_correspondent: Установить корреспондента для документов
set_document_type: Установить тип документа для документов
set_storage_path: Установить путь хранения для документов
add_tag: Добавить тег к документам
remove_tag: Удалить тег из документов
modify_tags: Добавить и/или удалить несколько тегов
delete: Удалить документы
reprocess: Переобработать документы
set_permissions: Установить права доступа к документам
merge: Объединить несколько документов
split: Разделить документ на несколько документов
rotate: Повернуть страницы документа
delete_pages: Удалить определённые страницы из документа
Дополнительные параметры в зависимости от метода:
correspondent: ID для set_correspondent
document_type: ID для set_document_type
storage_path: ID для set_storage_path
tag: ID для add_tag/remove_tag
add_tags: Массив ID тегов для modify_tags
remove_tags: Массив ID тегов для modify_tags
set_permissions: Объект для set_permissions с пользователями и группами на просмотр/изменение (
{"view": {"users": [], "groups": []}, "change": {...}}). Пропущенные действия/списки остаются без измененийowner: ID пользователя (или null для удаления) для set_permissions. Если merge не равен true, отсутствие owner очищает текущего владельца
merge: Логическое значение для set_permissions — true добавляет к существующим правам и сохраняет владельца; false (по умолчанию) заменяет указанных пользователей/группы
metadata_document_id: ID для merge, указывающий источник метаданных
delete_originals: Логическое значение для merge/split
pages: Строка для split "[1,2-3,4,5-7]" или delete_pages "[2,3,4]"
degrees: Число для rotate (90, 180 или 270)
Примеры:
// Add a tag to multiple documents
bulk_edit_documents({
documents: [1, 2, 3],
method: "add_tag",
tag: 5
})
// Set correspondent and document type
bulk_edit_documents({
documents: [4, 5],
method: "set_correspondent",
correspondent: 2
})
// Merge documents
bulk_edit_documents({
documents: [6, 7, 8],
method: "merge",
metadata_document_id: 6,
delete_originals: true
})
// Split document into parts
bulk_edit_documents({
documents: [9],
method: "split",
pages: "[1-2,3-4,5]"
})
// Modify multiple tags at once
bulk_edit_documents({
documents: [10, 11],
method: "modify_tags",
add_tags: [1, 2],
remove_tags: [3, 4]
})
// Modify custom fields
bulk_edit_documents({
documents: [12, 13],
method: "modify_custom_fields",
add_custom_fields: [
{ field: 2, value: "year" }
],
remove_custom_fields: []
})
// Set an empty custom field value, e.g. a date field used as a pending marker
bulk_edit_documents({
documents: [14],
method: "modify_custom_fields",
add_custom_fields: [
{ field: 9, value: "" }
],
remove_custom_fields: []
})post_document
Загрузить новый документ в Paperless-NGX.
Два режима загрузки:
Режим Base64 (традиционный): укажите
file(содержимое в кодировке base64) +filenameРежим файловой системы (эффективный): укажите
file_path(абсолютный путь на сервере)
Примечание по безопасности: При использовании file_path задайте переменную окружения PAPERLESS_MCP_UPLOAD_PATHS (разделённый двоеточием список разрешённых каталогов), чтобы ограничить загрузку определёнными местами. Без этого может быть загружен любой файл из файловой системы сервера.
Параметры:
file (необязательно): Содержимое файла в кодировке Base64. Требуется либо
file, либоfile_path.file_path (необязательно): Абсолютный путь к файлу в файловой системе сервера. Требуется либо
file, либоfile_path.filename (необязательно): Имя файла. Обязательно для
file, необязательно дляfile_path(берётся из пути).title (необязательно): Название документа
created (необязательно): Дата и время создания документа (например, «2024-01-19» или «2024-01-19 06:15:00+02:00»)
correspondent (необязательно): ID корреспондента
document_type (необязательно): ID типа документа
storage_path (необязательно): ID пути хранения
tags (необязательно): Массив ID тегов
archive_serial_number (необязательно): Архивный серийный номер
custom_fields (необязательно): Массив ID пользовательских полей
Ограничение размера файла: 100MB для обоих режимов
// Base64 mode (traditional)
post_document({
file: "base64_encoded_content",
filename: "invoice.pdf",
title: "January Invoice",
created: "2024-01-19",
correspondent: 1,
document_type: 2,
tags: [1, 3],
archive_serial_number: "2024-001",
custom_fields: [1, 2]
})
// Filesystem mode (more efficient for large files)
post_document({
file_path: "/var/uploads/invoice.pdf",
title: "January Invoice",
correspondent: 1,
document_type: 2,
tags: [1, 3]
})Заметки к документам
list_document_notes
Перечислить все заметки, прикреплённые к документу.
Параметры:
id: ID документа
list_document_notes({
id: 123
})create_document_note
Добавить заметку к документу. Возвращает полный список заметок документа.
Параметры:
id: ID документа
note: Текст добавляемой заметки
create_document_note({
id: 123,
note: "Invoice paid on 2026-06-30 from Commerzbank account."
})delete_document_note
⚠️ Удалить одну заметку из документа по её ID. Эта операция необратима.
Параметры:
id: ID документа
note_id: ID удаляемой заметки
confirm: Должно быть
true, чтобы подтвердить эту разрушительную операцию
delete_document_note({
id: 123,
note_id: 5,
confirm: true
})Операции с тегами
list_tags
Получить все теги.
list_tags()create_tag
Создать новый тег.
Параметры:
name: Название тега
color (необязательно): Шестнадцатеричный код цвета (например, «#ff0000»)
match (необязательно): Текстовый шаблон для сопоставления
matching_algorithm (необязательно): Число от 0 до 6: 0 — нет 1 — любое слово 2 — все слова 3 — точное совпадение 4 — регулярное выражение 5 — нечёткое слово 6 — автоматически
create_tag({
name: "Invoice",
color: "#ff0000",
match: "invoice",
matching_algorithm: 5
})Операции с корреспондентами
list_correspondents
Получить всех корреспондентов.
list_correspondents()create_correspondent
Создать нового корреспондента.
Параметры:
name: Имя корреспондента
match (необязательно): Текстовый шаблон для сопоставления
matching_algorithm (необязательно): Число от 0 до 6: 0 — нет 1 — любое слово 2 — все слова 3 — точное совпадение 4 — регулярное выражение 5 — нечёткое слово 6 — автоматически
create_correspondent({
name: "ACME Corp",
match: "ACME",
matching_algorithm: 5
})Операции с типами документов
list_document_types
Получить все типы документов.
list_document_types()create_document_type
Создать новый тип документа.
Параметры:
name: Имя типа документа
match (необязательно): Текстовый шаблон для сопоставления
matching_algorithm (необязательно): Число от 0 до 6: 0 - Нет 1 - Любое слово 2 - Все слова 3 - Точное совпадение 4 - Регулярное выражение 5 - Нечёткое слово 6 - Автоматически
create_document_type({
name: "Invoice",
match: "invoice total amount due",
matching_algorithm: 1
})Операции с пользовательскими полями
list_custom_fields
Получить все пользовательские поля.
list_custom_fields()get_custom_field
Получить конкретное пользовательское поле по ID.
Параметры:
id: ID пользовательского поля
get_custom_field({
id: 1
})create_custom_field
Создать новое пользовательское поле.
Параметры:
name: Имя пользовательского поля
data_type: Одно из "string", "url", "date", "boolean", "integer", "float", "monetary", "documentlink", "select"
extra_data (необязательно): Дополнительные данные для пользовательского поля, например, параметры выбора
create_custom_field({
name: "Invoice Number",
data_type: "string"
})update_custom_field
Обновить существующее пользовательское поле.
Параметры:
id: ID пользовательского поля
name (необязательно): Новое имя пользовательского поля
data_type (необязательно): Новый тип данных
extra_data (необязательно): Дополнительные данные для пользовательского поля
update_custom_field({
id: 1,
name: "Updated Invoice Number",
data_type: "string"
})delete_custom_field
Удалить пользовательское поле.
Параметры:
id: ID пользовательского поля
delete_custom_field({
id: 1
})bulk_edit_custom_fields
Выполнить массовые операции над несколькими пользовательскими полями.
Параметры:
custom_fields: Массив ID пользовательских полей
operation: Одно из "delete"
bulk_edit_custom_fields({
custom_fields: [1, 2, 3],
operation: "delete"
})Почтовые операции
Инструменты для управления почтовыми аккаунтами Paperless и почтовыми правилами, которые управляют автоматическим импортом электронной почты. Пароли/токены аккаунтов никогда не раскрываются: они скрываются во всех ответах инструментов.
list_mail_accounts
Список почтовых аккаунтов, чтобы вы могли выбрать ID аккаунта, необходимый при создании почтового правила. Пароли скрыты.
Параметры:
page (необязательно): Номер страницы
page_size (необязательно): Количество результатов на странице
list_mail_accounts()get_mail_account
Получить один почтовый аккаунт по ID. Поля пароля/токена скрыты.
Параметры:
id: ID почтового аккаунта
get_mail_account({
id: 1
})process_mail_account
Вручную запустить обработку почты Paperless для одного аккаунта. Это может обработать подходящие письма в соответствии с включёнными почтовыми правилами аккаунта.
Параметры:
id: ID почтового аккаунта
process_mail_account({
id: 1
})list_mail_rules
Список почтовых правил с необязательной постраничной навигацией.
Параметры:
page (необязательно): Номер страницы
page_size (необязательно): Количество результатов на странице
list_mail_rules()get_mail_rule
Получить одно почтовое правило по ID.
Параметры:
id: ID почтового правила
get_mail_rule({
id: 1
})create_mail_rule
Создать почтовое правило. Сначала используйте list_mail_accounts, чтобы выбрать аккаунт.
Обязательные параметры:
name: Имя правила
account: ID почтового аккаунта
folder: IMAP-папка для сканирования (например, "INBOX")
Часто используемые необязательные параметры:
enabled (по умолчанию true): Активно ли правило
filter_from / filter_to / filter_subject / filter_body: Сопоставление входящей почты
maximum_age: Обрабатывать только почту не старше указанного количества дней
action: 1=Удалить, 2=Переместить в папку, 3=Пометить как прочитанное, 4=Пометить флагом, 5=Добавить тег
action_parameter: Целевая папка/тег для выбранного действия
assign_title_from: 1=Тема, 2=Имя файла вложения, 3=Не назначать
assign_tags / assign_correspondent / assign_document_type: Применяемые метаданные
assign_correspondent_from: 1=Нет, 2=Адрес почты, 3=Имя отправителя, 4=Использовать assign_correspondent
attachment_type: 1=Только вложения, 2=Все файлы, включая встроенные
consumption_scope: 1=Только вложения, 2=Полное письмо как .eml, 3=Оба
pdf_layout: 0=Системный по умолчанию, 1=Текст+HTML, 2=HTML+текст, 3=Только HTML, 4=Только текст
create_mail_rule({
name: "Invoices",
account: 1,
folder: "INBOX",
filter_subject: "invoice",
action: 3,
attachment_type: 1
})update_mail_rule
Обновить существующее почтовое правило. Изменяются только указанные вами поля.
Параметры:
id: ID почтового правила
...любые поля из
create_mail_ruleдля обновления
update_mail_rule({
id: 1,
enabled: false
})delete_mail_rule
Удалить почтовое правило. Требуется явный флаг подтверждения. Это изменяет поведение будущего импорта почты, но не удаляет существующие документы.
Параметры:
id: ID почтового правила
confirm: Должно быть
trueдля подтверждения удаления
delete_mail_rule({
id: 1,
confirm: true
})Обработка ошибок
Сервер покажет понятные сообщения об ошибках, если:
URL Paperless-NGX или API-токен неверны
Сервер Paperless-NGX недоступен
Запрошенная операция не удалась
Предоставленные параметры недействительны
Тестирование
Модульные тесты
Запустите набор модульных тестов (внешние зависимости не требуются):
npm testE2E-тесты
Набор E2E-тестов запускает пустой экземпляр Paperless-ngx, запускает скомпилированный MCP-сервер и выполняет детерминированный последовательный сценарий через запросы tools/call — создание тега, корреспондента и типа документа, загрузку PDF, а затем проверку list / get / search / download / thumbnail / bulk-edit для того же документа. Никаких LLM и никакого REST-клиента Paperless вне MCP.
Предварительные требования: Docker, Docker Compose и jq.
# 1. Build the MCP server
npm run build
# 2. Start Paperless-ngx
docker compose -f docker-compose.e2e.yml up -d
# 3. Wait for Paperless to be ready, then get a token
TOKEN=$(curl -s -X POST http://localhost:8000/api/token/ \
-H 'Content-Type: application/json' \
-d '{"username":"admin","password":"admin123"}' | jq -r '.token')
# 4. Start the MCP server
node build/index.js --http --port 3001 \
--baseUrl http://localhost:8000 --token "$TOKEN" &
MCP_PID=$!
# 5. Run the E2E tests
MCP_URL=http://localhost:3001/mcp \
PAPERLESS_URL=http://localhost:8000 \
PAPERLESS_TOKEN="$TOKEN" \
npm run test:e2e
# 6. Cleanup
kill "$MCP_PID"
docker compose -f docker-compose.e2e.yml down -vE2E-тесты также автоматически запускаются в CI при каждом pull request и push в main, охватывая как CLI build/index.js, так и опубликованный Docker-образ.
Разработка
Хотите внести вклад или изменить сервер? Вот что вам нужно знать:
Клонируйте репозиторий
Установите зависимости:
npm installВнесите изменения в server.js
Протестируйте локально:
node server.js http://localhost:8000 your-test-tokenСервер построен с использованием:
litemcp: TypeScript-фреймворк для создания MCP-серверов
zod: Схемная валидация, ориентированная на TypeScript
Документация API
Этот MCP-сервер реализует конечные точки REST API Paperless-NGX. Для получения дополнительных сведений о базовом API см. официальную документацию.
Запуск MCP-сервера
MCP-сервер можно запускать в двух режимах:
1. stdio (по умолчанию)
Это режим по умолчанию. Сервер общается через stdio, подходит для CLI и прямых интеграций.
npm run start -- <baseUrl> <token>2. HTTP (потоковый HTTP-транспорт)
Чтобы запустить сервер как HTTP-сервис, используйте флаг --http. Также можно указать порт с помощью --port (по умолчанию: 3000). Этот режим требует установки Express (он включён в зависимости).
npm run start -- <baseUrl> <token> --http --port 3000MCP API будет доступен по адресу
POST /mcpна указанном порту.Каждый запрос обрабатывается без сохранения состояния, следуя шаблону StreamableHTTPServerTransport.
Запросы GET и DELETE к
/mcpбудут возвращать 405 Method Not Allowed.
API-токен для каждого запроса (режим HTTP/Docker)
В режиме HTTP клиенты проходят аутентификацию, предоставляя API-токен Paperless-NGX через стандартный заголовок Authorization:
Authorization: Bearer <paperless-ngx-api-token>Токен передаётся напрямую в Paperless-NGX, поэтому собственные разрешения Paperless каждого клиента соблюдаются на всём пути. Это позволяет одному экземпляру сервера обслуживать нескольких пользователей, каждый со своим токеном. То же поведение применяется к конечным точкам /mcp и /sse.
⚠️ Критическое изменение в v2.0.0 — режим HTTP теперь аутентифицирован по умолчанию.
Ранее запрос без заголовка
Authorizationнезаметно использовал серверныйPAPERLESS_API_KEY, что оставляло HTTP-конечную точку открытой для любого, кто мог достичь порта. Начиная с v2.0.0, запросы без токенаBearerотклоняются с401 Unauthorized. Серверный токен никогда не используется для неаутентифицированных запросов, если вы явно не включите это с помощью--no-auth.
Сценарий |
|
|
Клиент отправляет |
|
|
Нет заголовка, задан |
| серверный токен |
Нет заголовка, нет серверного токена |
|
|
Миграция с v1.x: если вы полагались на старый запасной вариант (единый общий PAPERLESS_API_KEY с клиентами, которые не отправляют токен), у вас есть два варианта:
Рекомендуется: пусть каждый клиент отправляет
Authorization: Bearer <paperless-token>.Восстановите старое поведение (только доверенные/локальные сети): запустите сервер с флагом
--no-auth, например, добавьте его вcommand/args Docker или в вызов CLI. Для этого требуется настроить серверный токен (PAPERLESS_API_KEYили--token).
MCP-сервер можно развернуть с помощью Docker и Docker Compose. Docker-образ автоматически запускается в режиме HTTP с поддержкой SSE (Server-Sent Events) на порту 3000.
Конфигурация Docker Compose
Создайте файл docker-compose.yml:
services:
paperless-mcp:
container_name: paperless-mcp
image: ghcr.io/baruchiro/paperless-mcp:latest
environment:
- PAPERLESS_URL=http://your-paperless-ngx-server:8000
- PAPERLESS_API_KEY=your-paperless-api-key
- PAPERLESS_PUBLIC_URL=https://paperless-ngx.yourpublicurl.com
ports:
- "3000:3000"
restart: unless-stoppedЗатем выполните:
docker-compose up -dИспользование с расширением Continue для VS Code
Если вы используете расширение Continue для VS Code, вы можете настроить его на использование Docker-версии MCP-сервера через SSE.
Создайте или отредактируйте .continue/mcpServers/paperless-mcp.yaml в корне вашего рабочего пространства:
name: Paperless
version: 0.0.1
schema: v1
mcpServers:
- name: Paperless
type: sse
url: http://localhost:3000/sseПримечания:
Замените
localhostна IP-адрес или имя хоста вашего Docker-хоста, если вы работаете на удалённом сервереDocker-контейнер обрабатывает аутентификацию через переменные окружения, поэтому в конфигурации Continue не нужны учётные данные
Конечная точка SSE доступна по адресу
/sseна настроенном порту (по умолчанию: 3000)
Благодарности
Этот проект является форком nloui/paperless-mcp. Большое спасибо оригинальному автору за его работу. Вклад и улучшения могут быть возвращены в исходный проект.
Отладка
Для отладки MCP-сервера в VS Code используйте следующую конфигурацию запуска:
{
"type": "node",
"request": "launch",
"name": "Debug Paperless MCP (HTTP, ts-node ESM)",
"program": "${workspaceFolder}/node_modules/ts-node/dist/bin.js",
"args": [
"--esm",
"src/index.ts",
"--http",
"--baseUrl",
"http://your-paperless-instance:8000",
"--token",
"your-api-token",
"--port",
"3002"
],
"env": {
"NODE_OPTIONS": "--loader ts-node/esm",
},
"console": "integratedTerminal",
"skipFiles": [
"<node_internals>/**"
]
}Важно: Перед отладкой раскомментируйте следующую строку в src/index.ts (около строки 175):
// await new Promise((resolve) => setTimeout(resolve, 1000000));Это предотвращает немедленный выход сервера и позволяет устанавливать точки останова и отлаживать код.
Available Tools
47 toolsacknowledge_tasksAIdempotent
Mark tasks as acknowledged (seen and handled) by their numeric task IDs from list_tasks. This only sets the acknowledged flag; it does not delete tasks or retry them. Returns the number of tasks acknowledged.
Inputs: tasks (required).
bulk_edit_correspondentsBDestructiveIdempotent
Bulk edit correspondents. ⚠️ WARNING: 'delete' operation permanently removes correspondents from the entire system.
Inputs: operation (required), correspondent_ids (required), merge, owner, +2 more.
bulk_edit_custom_fieldsBDestructiveIdempotent
Bulk edit custom fields. ⚠️ WARNING: 'delete' operation permanently removes custom fields from the entire system.
Inputs: operation (required), custom_fields (required), confirm.
bulk_edit_documentsBDestructive
Perform bulk operations on multiple documents. Note: 'remove_tag' removes a tag from specific documents (tag remains in system), while 'delete_tag' permanently deletes a tag from the entire system. ⚠️ WARNING: 'delete' moves documents to the trash on Paperless-ngx 2.10+ (temporarily restorable; retention depends on server policy and documents may be permanently removed automatically or manually); older versions permanently delete them. Confirmation is required in all versions.
Inputs: method (required), documents (required), tag, merge, +14 more.
bulk_edit_document_typesBDestructiveIdempotent
Bulk edit document types. ⚠️ WARNING: 'delete' operation permanently removes document types from the entire system.
Inputs: operation (required), document_type_ids (required), merge, owner, +2 more.
bulk_edit_tagsCDestructiveIdempotent
Bulk edit tags. ⚠️ WARNING: 'delete' operation permanently removes tags from the entire system. Use with caution.
Inputs: tag_ids (required), operation (required), merge, owner, +2 more.
create_correspondentB
Create a new correspondent with optional matching pattern and algorithm for automatic document assignment.
Inputs: name (required), match, matching_algorithm.
create_custom_fieldB
Create a new custom field with a specified data type (string, url, date, boolean, integer, float, monetary, documentlink, or select). For monetary fields, values must use currency code prefix format (e.g., USD10.00, GBP123.45) — NOT trailing symbol format (e.g., 10.00$).
Inputs: name (required), data_type (required), extra_data.
create_document_noteA
Add a note to a document. Use this to record an audit trail or progress note directly on the document. Returns the document's full list of notes after the note is added.
Inputs: id (required), note (required).
create_document_typeB
Create a new document type with optional matching pattern and algorithm for automatic document classification.
Inputs: name (required), match, matching_algorithm.
create_mail_ruleBDestructive
Create a Paperless mail rule. Use list_mail_accounts first to choose account. Prefer attachment-only rules for invoices unless the full mail must be archived.
Inputs: name (required), folder (required), account (required), order, +20 more.
create_tagA
Create a new tag with optional color, matching pattern, and matching algorithm for automatic document tagging.
Inputs: name (required), color, match, matching_algorithm.
delete_correspondentBDestructiveIdempotent
⚠️ DESTRUCTIVE: Permanently delete a correspondent from the entire system. This will affect ALL documents that use this correspondent.
Inputs: id (required), confirm (required).
delete_custom_fieldBDestructiveIdempotent
⚠️ DESTRUCTIVE: Permanently delete a custom field from the entire system. This will remove the field from ALL documents that use it.
Inputs: id (required), confirm (required).
delete_document_noteBDestructiveIdempotent
⚠️ DESTRUCTIVE: Permanently delete a single note from a document by its note ID. This operation is irreversible. Returns the document's remaining notes.
Inputs: id (required), confirm (required), note_id (required).
delete_document_typeADestructiveIdempotent
⚠️ DESTRUCTIVE: Permanently delete a document type from the entire system. This will affect ALL documents that use this type.
Inputs: id (required), confirm (required).
delete_mail_ruleADestructiveIdempotent
Delete one Paperless mail rule. This changes future mail ingestion behavior but does not delete documents.
Inputs: id (required), confirm (required).
delete_tagADestructiveIdempotent
⚠️ DESTRUCTIVE: Permanently delete a tag from the entire system. This will remove the tag from ALL documents that use it. Use with extreme caution.
Inputs: id (required), confirm (required).
download_documentARead-onlyIdempotent
Download a document file by ID. Returns a paperless:// resource URI; read the resource to fetch the file content.
Inputs: id (required), original.
get_correspondentBRead-onlyIdempotent
Get a specific correspondent by ID with full details including matching rules.
Inputs: id (required).
get_custom_fieldARead-onlyIdempotent
Get a specific custom field by ID with full details including data type and extra configuration.
Inputs: id (required).
get_documentARead-onlyIdempotent
Get a specific document by ID with full details including correspondent, document type, tags, and custom fields. Note: Document content is excluded from results by default. Use 'get_document_content' to retrieve content when needed.
Inputs: id (required).
get_document_contentARead-onlyIdempotent
Get the text content of a specific document by ID. Use this when you need to read or analyze the actual document text.
Inputs: id (required).
get_document_thumbnailARead-onlyIdempotent
Get a document thumbnail (image preview) by ID. Returns a paperless:// resource URI; read the resource to fetch the image content.
Inputs: id (required).
get_document_typeBRead-onlyIdempotent
Get a specific document type by ID with full details including matching rules.
Inputs: id (required).
get_mail_accountARead-onlyIdempotent
Get one Paperless mail account by ID. Password/token fields are redacted if the server returns them.
Inputs: id (required).
get_mail_ruleARead-onlyIdempotent
Get one Paperless mail rule by ID.
Inputs: id (required).
list_correspondentsBRead-onlyIdempotent
List all correspondents with optional filtering and pagination. Correspondents represent entities that send or receive documents.
Inputs: page, ordering, page_size, name__iexact, +3 more.
list_custom_fieldsARead-onlyIdempotent
List all custom fields. IMPORTANT: When a user query may refer to a custom field, you should fetch all custom fields up front (with a large enough page_size), cache them for the session, and search locally for matches by name before making further API calls. This reduces redundant requests and handles ambiguity efficiently.
Inputs: page, ordering, page_size, name__iexact, +3 more.
list_document_notesARead-onlyIdempotent
List all notes attached to a document. Notes are free-text comments on a document and are the natural place for an audit trail (e.g. "invoice paid on X from account Y") or progress notes on an action item.
Inputs: id (required).
list_documentsARead-onlyIdempotent
List and filter documents with pagination and common Paperless filters such as title search, correspondent, document type, tag, storage path, creation date, archive serial number, and simple custom field filters. Use 'query_documents' for full-text query, structured custom field conditions, or advanced documented /api/documents/ query parameters. IMPORTANT: For queries like 'the last 3 contributions' or when searching by tag, correspondent, document type, or storage path, first use the relevant lookup tool to find the correct ID. Note: Document content is excluded from results by default. Use 'get_document_content' when you need the document text.
Inputs: tag, page, search, ordering, +10 more.
list_document_typesARead-onlyIdempotent
List all document types. IMPORTANT: When a user query may refer to a document type or tag, you should fetch all document types and all tags up front (with a large enough page_size), cache them for the session, and search locally for matches by name or slug before making further API calls. This reduces redundant requests and handles ambiguity between tags and document types efficiently.
Inputs: page, ordering, page_size, name__iexact, +3 more.
list_mail_accountsARead-onlyIdempotent
List Paperless mail accounts for selecting the account ID needed by mail rules. Does not expose account passwords.
Inputs: page, page_size.
list_mail_rulesBRead-onlyIdempotent
List Paperless mail rules with optional pagination.
Inputs: page, page_size.
list_storage_pathsBRead-onlyIdempotent
List storage paths with optional filtering and pagination. Returns one page of path IDs, names, path templates and matching rules without modifying storage paths or documents.
Inputs: id, page, id__in, ordering, +10 more.
list_tagsBRead-onlyIdempotent
List all tags. IMPORTANT: When a user query may refer to a tag or document type, you should fetch all tags and all document types up front (with a large enough page_size), cache them for the session, and search locally for matches by name or slug before making further API calls. This reduces redundant requests and handles ambiguity between tags and document types efficiently.
Inputs: page, ordering, page_size, name__iexact, +3 more.
list_tasksARead-onlyIdempotent
List Paperless consumer-queue tasks, including failed uploads (unsupported file type, duplicate of an existing document, unreadable file). Each task has its status, result message (the failure reason), and, for uploads, the file name and related document; these two can be null for other tasks. Use status failure with acknowledged false to find unacknowledged failures. A failure can remain unacknowledged after its underlying issue is resolved.
Inputs: type, status, task_name, acknowledged.
post_documentA
Upload a new document to Paperless-NGX with optional metadata like title, correspondent, document type, tags, and custom fields. Provide either 'file' (base64-encoded content) or 'file_path' (absolute path to a file on the server's filesystem). Using file_path avoids base64 encoding overhead for large files. SECURITY: When using file_path, set PAPERLESS_MCP_UPLOAD_PATHS environment variable to restrict uploads to specific directories (colon-separated paths).
Inputs: file, tags, title, created, +7 more.
process_mail_accountBDestructive
Manually run Paperless mail processing for one account. This can consume matching mails according to enabled Paperless mail rules.
Inputs: id (required).
query_documentsARead-onlyIdempotent
Query documents using the full-text query engine plus structured Paperless filters. Use this for complex filtering, custom field conditions, or any documented /api/documents/ query parameters that are not exposed as first-class arguments. Prefer the dedicated top-level arguments where available. custom_field_query supports [field_name_or_id, operator, value] leaves or ['AND'|'OR', [clause1, clause2]] groups. Note: Document content is excluded from results by default. Use 'get_document_content' when you need the document text.
Inputs: tag, page, query, search, +13 more.
search_documentsARead-onlyIdempotent
Deprecated compatibility wrapper for full-text document search. Use 'query_documents' with the 'query' argument for new integrations. Note: Document content is excluded from results by default. Use 'get_document_content' to retrieve content when needed.
Inputs: query (required).
update_correspondentBIdempotent
Update an existing correspondent's name, matching pattern, or matching algorithm.
Inputs: id (required), name, match, matching_algorithm.
update_custom_fieldBIdempotent
Update an existing custom field's name, data type, or extra configuration data.
Inputs: id (required), name, data_type, extra_data.
update_documentADestructiveIdempotent
Update a specific document with new values (title, correspondent, document type, storage path, tags, custom fields, and more). Top-level fields you omit are left unchanged. IMPORTANT: custom_fields is the exception — see its parameter description; it replaces the document's entire custom-field set.
Inputs: id (required), tags, owner, title, +7 more.
update_document_typeBIdempotent
Update an existing document type's name, matching pattern, or matching algorithm.
Inputs: id (required), name, match, matching_algorithm.
update_mail_ruleBDestructiveIdempotent
Patch an existing Paperless mail rule. Only supplied fields are changed.
Inputs: id (required), name, order, owner, +21 more.
update_tagBIdempotent
Update an existing tag's name, color, matching pattern, or matching algorithm.
Inputs: id (required), name, color, match, +1 more.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 47 tools
Most tools map to a distinct resource and action across Paperless-ngx, with clear separation between document metadata, content, notes, tags, correspondents, document types, custom fields, mail rules, and tasks. However, list_documents, query_documents, and the deprecated search_documents overlap on document retrieval, and bulk_edit_* operations partly duplicate individual delete/update verbs.
Tool names are uniformly snake_case and follow a predictable verb-first pattern such as list_tags, create_tag, delete_mail_rule, and bulk_edit_documents. Verb choices vary by operation (post_document, process_mail_account, acknowledge_tasks), but the verb_noun structure remains consistent throughout.
At 47 tools, the surface is very large for a single MCP server even though Paperless-ngx is a broad domain with many entity types. This is well beyond the typical well-scoped range and lands in the rubric's 25+ 'too many' category.
Core document workflows and metadata lifecycle operations are well covered, including notes, tags, correspondents, document types, custom fields, mail rules, and task acknowledgment. However, storage paths only expose list_storage_paths with no get/create/update/delete, and mail accounts are read/process-only, leaving notable lifecycle gaps.
Maintenance
Related MCP Connectors
MCP server for the PDFGate API. Generate PDFs, manage documents and handle e-signatures.
Model Context Protocol server for the Apideck Unified API. Connect any MCP-compatible agent framework to 100+ accounting systems, HRIS platforms, file storage providers, and more through one integration. More information https://www.apideck.com/mcp-server
An MCP server that provides read access to your cloud storage providers, bank accounts and more.
Related MCP Servers
- FlicenseAqualityCmaintenanceMCP server for Paperless-ngx document management. Enables AI models to search, retrieve, update documents and manage metadata.7-
- AlicenseNot gradedqualityCmaintenanceA read-only and write MCP server for Paperless-ngx, enabling document listing, metadata retrieval, and creation of tags, correspondents, document types, and sorting workflows via natural language.MIT
- FlicenseNot gradedqualityNot gradedmaintenanceMCP server for Paperless-ngx document management, enabling search, OCR content access, metadata updates, tag/correspondent/type management, and duplicate detection via natural language.1-
- AlicenseAqualityCmaintenanceAn MCP server that puts a paperless-ngx document archive within reach of AI assistants, enabling full-text search, reading, filing, uploading, and managing documents and taxonomy through the paperless-ngx REST API.1631 npmMIT