Content
# MCP-1C
**MCP Server для платформы 1C:Предприятие** — metadata analysis, code generation and integration with Claude.
[](https://www.python.org/downloads/)
[](https://opensource.org/licenses/MIT)
## Features
- **Metadata Engine** — parsing and indexing of 1C configuration metadata
- **Code Engine** — code analysis in BSL (1C built-in language)
- **Template Engine** — code generation from templates
- **MXL Engine** — parsing of tabular document layouts
- **Platform Knowledge Base** — knowledge base of the platform API 8.3.24
- **BSL Language Server** — integration with BSL LS for validation and formatting
- **Skills & Agents** — ready-made scenarios for Claude Code
## Installation
### From PyPI (recommended)
```bash
pip install mcp-1c
```
### From sources
```bash
git clone https://github.com/your-org/mcp-1c.git
cd mcp-1c
pip install -e ".[dev]"
```
## Quick start
### 1. MCP Server configuration
#### Global configuration (for Claude Desktop)
Add to `~/.claude/mcp_servers.json` (Linux/Mac) or `%USERPROFILE%\.claude\mcp_servers.json` (Windows):
```json
{
"mcpServers": {
"mcp-1c": {
"command": "mcp-1c",
"args": []
}
}
}
```
#### Local configuration (for a specific 1C configuration)
Create a `.mcp.json` file in the root of the uploaded configuration:
```json
{
"mcpServers": {
"mcp-1c": {
"command": "python",
"args": ["-m", "mcp_1c"]
}
}
}
```
> **Note:** Local configuration is convenient for working with multiple configurations — each uses its own cache.
### 2. Initialization
In Claude Code, run:
```
Инициализируй конфигурацию по пути C:\Projects\MyConfig
```
Or use skill:
```
/1c-metadata Справочник.Номенклатура
```
## Work pipeline
### How indexing works
```
┌─────────────────────────────────────────────────────────────────────┐
│ 1. INITIALIZATION │
├─────────────────────────────────────────────────────────────────────┤
│ metadata.init(config_path) │
│ │ │
│ ▼ │
│ Configuration.xml ──► Parsing the list of objects │
│ │ (Catalogs, Documents, Registers...) │
│ │ │
│ ▼ │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ Catalog/ │ │ Document/ │ │ Register/ │ ... │
│ │ Object.xml │ │ Object.xml │ │ Object.xml │ │
│ └──────┬──────┘ └──────┬──────┘ └──────┬──────┘ │
│ │ │ │ │
│ └──────────────────┼──────────────────┘ │
│ │ │
│ ▼ │
│ Parallel parsing (4 threads) │
│ │ │
│ ▼ │
│ ┌─────────────────────────┐ │
│ │ .mcp_1c_cache.db │ ◄── SQLite database │
│ │ (in the configuration folder)│ with WAL mode │
│ └─────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────┐
│ 2. USING THE CACHE │
├─────────────────────────────────────────────────────────────────────┤
│ │
│ metadata.get("Catalog", "Номенклатура") │
│ │ │
│ ▼ │
│ ┌─────────────────┐ HIT ┌─────────────────┐ │
│ │ LRU In-Memory │ ───────────► │ Data return │ │
│ │ Cache │ └─────────────────┘ │
│ └────────┬────────┘ │
│ │ MISS │
│ ▼ │
│ ┌─────────────────┐ HIT ┌─────────────────┐ │
│ │ SQLite Cache │ ───────────► │ Data return │ │
│ │ (MD5 check) │ │ + update │ │
│ └────────┬────────┘ │ LRU cache │ │
│ │ MISS/STALE └─────────────────┘ │
│ ▼ │
│ ┌─────────────────┐ ┌─────────────────┐ │
│ │ XML parsing │ ───────────► │ Saving to │ │
│ │ file │ │ both caches │ │
│ └─────────────────┘ └─────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────┐
│ 3. INCREMENTAL UPDATE │
├─────────────────────────────────────────────────────────────────────┤
│ │
│ File Watcher (watchfiles) │
│ │ │
│ ▼ │
│ Changing .xml or .bsl file │
│ │ │
│ ▼ │
│ Debounce (500ms) ──► Extracting type/name from path │
│ │ │
│ ▼ │
│ Reparsing only the changed object │
│ │ │
│ ▼ │
│ Updating the entry in SQLite + invalidating the LRU cache │
│ │
└─────────────────────────────────────────────────────────────────────┘
```
### Database structure
The `.mcp_1c_cache.db` database is created **in the configuration folder** and contains:
| Table | Description |
|---------|----------|
| `metadata_objects` | Basic object data (name, type, synonym, UUID) |
| `attributes` | Object attributes |
| `tabular_sections` | Tabular parts |
| `modules` | Paths to modules (.bsl files) |
| `subsystems` | Subsystems and their contents |
### Supported upload formats
| Format | Source | Support |
|--------|----------|-----------|
| XML Configurator | Configurator → Upload configuration to files | ✅ Full |
| EDT Project | 1C:EDT → Export | ✅ Full |
> The format is determined automatically by the `Configuration.xml` structure
## Tools
### Metadata Tools
| Tool | Description |
|------------|----------|
| `metadata.init` | Metadata index initialization |
| `metadata.list` | List of objects by type |
| `metadata.get` | Full object information |
| `metadata.search` | Search by name/synonym |
| `metadata.tree` | Subsystem tree |
| `metadata.attributes` | Object attributes |
| `metadata.forms` | Object forms |
| `metadata.templates` | Object layouts |
| `metadata.registers` | Document registers |
| `metadata.references` | Object links |
### Code Tools
| Tool | Description |
|------------|----------|
| `code.module` | Get module code |
| `code.procedure` | Get procedure code |
| `code.resolve` | Find definition |
| `code.usages` | Find usages |
| `code.dependencies` | Dependency graph |
| `code.analyze` | Advanced module analysis |
| `code.callgraph` | Procedure call graph |
| `code.validate` | Syntax check |
| `code.lint` | Static analysis |
| `code.format` | Code formatting |
| `code.complexity` | Complexity analysis |
### Generate Tools
| Tool | Description |
|------------|----------|
| `generate.query` | Query generation |
| `generate.handler` | Event handler generation |
| `generate.print` | Print form generation |
| `generate.movement` | Register movement generation |
| `generate.api` | API method generation |
| `generate.form_handler` | Form handlers |
| `generate.subscription` | Event subscription |
| `generate.scheduled_job` | Scheduled job |
### Query Tools
| Tool | Description |
|------------|----------|
| `query.parse` | Query parsing |
| `query.validate` | Validation with metadata |
| `query.optimize` | Query optimization |
| `query.explain` | Query explanation |
| `query.tables` | Tables in query |
### Pattern Tools
| Tool | Description |
|------------|----------|
| `pattern.list` | Pattern list |
| `pattern.get` | Get pattern |
| `pattern.apply` | Apply pattern |
| `pattern.suggest` | Suggest pattern |
| `pattern.search` | Pattern search |
### Template Tools (MXL)
| Tool | Description |
|------------|----------|
| `template.get` | Layout structure |
| `template.parameters` | Layout parameters |
| `template.areas` | Layout areas |
| `template.generate_fill_code` | Layout fill code generation |
| `template.find` | Layout search |
### Platform Tools
| Tool | Description |
|------------|----------|
| `platform.method` | Platform method description |
| `platform.type` | Data type description |
| `platform.event` | Object event description |
| `platform.search` | Platform API search |
| `platform.global_context` | Global context |
### Config Tools
| Tool | Description |
|------------|----------|
| `config.options` | Functional options |
| `config.constants` | Constants |
| `config.scheduled_jobs` | Scheduled jobs |
| `config.event_subscriptions` | Event subscriptions |
| `config.exchanges` | Exchange plans |
| `config.http_services` | HTTP services |
## Skills & Agents
### Architecture
Skills and Agents are implemented as MCP Prompts — predefined scenarios that guide Claude through a sequence of actions using server tools.
```
┌─────────────────────────────────────────────────────────────────────┐
│ PROMPTS ARCHITECTURE │
├─────────────────────────────────────────────────────────────────────┤
│ │
│ BasePrompt (base.py) │
│ │ │
│ ├── Skills (skills.py) ─── Simple single-step tasks │
│ │ └── /1c-query, /1c-metadata, /1c-handler... │
│ │ │
│ ├── Agents (agents.py) ─── Complex multi-step workflows │
│ │ └── /1c-explore, /1c-implement, /1c-debug... │
│ │ │
│ └── PromptRegistry (registry.py) ─── Registration and call │
│ │
└─────────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────┐
│ HOW IT WORKS │
├─────────────────────────────────────────────────────────────────────┤
│ │
│ User ──► /1c-query object="Справочник.Номенклатура" │
│ │ │
│ ▼ │
│ PromptRegistry.get_prompt_messages("1c-query", arguments) │
│ │ │
│ ▼ │
│ QuerySkill.generate_messages(arguments) │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────────┐ │
│ │ Prompt with instructions for Claude: │ │
│ │ 1. Use metadata.get to get information │ │
│ │ 2. Use metadata.attributes for attributes │ │
│ │ 3. Use generate.query to generate a query │ │
│ └─────────────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ Claude executes instructions, calling MCP Tools │
│ │
└─────────────────────────────────────────────────────────────────────┘
```
### Skills — simple tasks
Skills solve specific tasks in a few steps. Called via `/` commands.
| Skill | Description | Arguments |
|-------|----------|-----------|
| `/1c-query` | Data query generation | `object` (required), `fields`, `conditions` |
| `/1c-metadata` | Metadata object information | `object` (required) |
| `/1c-handler` | Event handler generation | `object`, `event` (required), `description` |
| `/1c-print` | Print form generation | `object` (required), `template`, `description` |
| `/1c-usages` | Code usage search | `name` (required), `scope` |
| `/1c-validate` | Code syntax check | `module` (required) |
| `/1c-deps` | Module dependency graph | `module` (required), `depth` |
| `/1c-movement` | Register movement generation | `document` (required), `register` |
| `/1c-format` | Code formatting | `module` (required) |
| `/1c-explain` | Code explanation | `module` (required), `procedure` |
### Examples of using Skills
```
# Query generation with conditions
/1c-query object="Справочник.Номенклатура" fields="Код,Наименование" conditions="Родитель = &Группа"
# Full object information
/1c-metadata object="Документ.РеализацияТоваров"
# Event handler generation
/1c-handler object="Документ.ПоступлениеТоваров" event="ПередЗаписью" description="Проверка заполненности склада"
# Print form generation
/1c-print object="Документ.Счет" description="Печатная форма с таблицей товаров и итогами"
# Procedure usage search
/1c-usages name="ПолучитьЦену" scope="all"
# Document movement generation
/1c-movement document="РеализацияТоваров" register="РегистрНакопления.ОстаткиТоваров"
# Dependency analysis
/1c-deps module="Документ.РеализацияТоваров.МодульОбъекта" depth="3"
# Explanation of a specific procedure
/1c-explain module="ОбщийМодуль.РаботаСТоварами" procedure="РассчитатьЦену"
```
### Agents — complex multi-step tasks
Agents are advanced scenarios for complex tasks. They contain a detailed plan of action with many steps.
| Agent | Description | Arguments |
|-------|----------|-----------|
| `/1c-explore` | Configuration exploration | `path` (required), `focus`, `depth` |
| `/1c-implement` | Functionality implementation | `task` (required), `object`, `style` |
| `/1c-debug` | Debugging and diagnostics | `problem` (required), `module`, `error` |
| `/1c-configure` | Standard configuration setup | `goal` (required), `configuration`, `approach` |
### Examples of using Agents
```
# Configuration exploration
/1c-explore path="C:\Projects\MyConfig" focus="documents" depth="detailed"
# New functionality implementation
/1c-implement task="Добавить автоматический расчёт скидки при проведении документа" object="Документ.РеализацияТоваров" style="bsp"
# Problem debugging
/1c-debug problem="Документ не проводится по регистру остатков" module="Документ.РеализацияТоваров.МодульОбъекта" error="Недостаточно остатков на складе"
# Standard configuration setup
/1c-configure goal="Добавить новый вид цены и настроить его расчёт" configuration="УТ" approach="extension"
```
### Difference between Skills and Agents
| Characteristic | Skills | Agents |
|----------------|--------|--------|
| Complexity | Simple tasks | Complex tasks |
| Number of steps | 3-5 steps | 10-20+ steps |
| Scope | Specific operation | Full workflow |
| Example | Generate a query | Explore the entire configuration |
### Creating your own Skills/Agents
Skills and Agents are defined in `src/mcp_1c/prompts/`. To create a new one:
```python
# src/mcp_1c/prompts/skills.py
class MyCustomSkill(BasePrompt):
name: ClassVar[str] = "1c-my-skill"
description: ClassVar[str] = "Описание моего skill"
arguments: ClassVar[list[PromptArgument]] = [
PromptArgument(
name="param",
description="Описание параметра",
required=True,
),
]
async def generate_messages(
self, arguments: dict[str, str]
) -> list[PromptMessage]:
param = arguments.get("param", "")
prompt = f"""Выполни задачу с параметром: {param}
Шаги:
1. Используй metadata.get для ...
2. Используй code.analyze для ...
3. Сформируй результат
"""
return [self.create_user_message(prompt)]
```
Затем зарегистрируйте в `PromptRegistry._register_all_prompts()`.
## Примеры использования
### Анализ метаданных
```python
# Получить информацию о справочнике
metadata.get type="Catalog" name="Номенклатура"
# Найти все документы с "Продажа" в названии
metadata.search query="Продажа" type="Document"
# Получить реквизиты документа
metadata.attributes type="Document" name="РеализацияТоваров"
```
### Анализ кода
```python
# Получить код модуля объекта
code.module type="Document" name="РеализацияТоваров" module_type="ObjectModule"
# Найти все использования процедуры
code.usages type="CommonModule" name="ОбщегоНазначения" procedure="ПолучитьЗначение"
# Получить граф зависимостей
code.dependencies type="Document" name="РеализацияТоваров"
```
### Генерация кода
```python
# Сгенерировать запрос
generate.query template="select_with_filter"
table="Справочник.Номенклатура"
filter_field="Родитель"
# Сгенерировать обработчик
generate.handler template="before_write"
object_type="Document"
object_name="РеализацияТоваров"
# Сгенерировать движения
generate.movement template="expense"
register="РегистрНакопления.ОстаткиТоваров"
document="РеализацияТоваров"
```
## Архитектура
```
mcp-1c/
├── src/mcp_1c/
│ ├── __main__.py # Точка входа
│ ├── server.py # MCP Server
│ ├── config.py # Конфигурация
│ │
│ ├── domain/ # Доменные модели (Pydantic)
│ │ ├── metadata.py # Модели метаданных
│ │ ├── code.py # Модели кода
│ │ ├── templates.py # Модели шаблонов
│ │ ├── mxl.py # Модели макетов
│ │ └── platform.py # Модели платформы
│ │
│ ├── engines/ # Движки обработки
│ │ ├── metadata/ # Metadata Engine
│ │ ├── code/ # Code Engine
│ │ ├── templates/ # Template Engine
│ │ ├── mxl/ # MXL Engine
│ │ └── platform/ # Platform Engine
│ │
│ ├── tools/ # MCP Tools
│ │ ├── metadata_tools.py
│ │ ├── code_tools.py
│ │ ├── generate_tools.py
│ │ ├── query_tools.py
│ │ ├── pattern_tools.py
│ │ ├── template_tools.py
│ │ ├── platform_tools.py
│ │ └── config_tools.py
│ │
│ ├── prompts/ # Skills & Agents
│ │ ├── skills.py
│ │ └── agents.py
│ │
│ └── utils/ # Утилиты
│ ├── logger.py
│ ├── profiler.py
│ └── lru_cache.py
│
└── tests/ # Тесты
```
## Оптимизации
MCP-1C оптимизирован для работы с большими конфигурациями:
- **SQLite WAL mode** — улучшенная производительность записи
- **In-memory LRU Cache** — кэширование частых запросов
- **Parallel Indexing** — параллельная индексация объектов
- **Batch Operations** — пакетные операции записи
- **Incremental Updates** — обновление только изменённых файлов
## Разработка
### Запуск тестов
```bash
pytest
pytest --cov=mcp_1c
```
### Проверка кода
```bash
ruff check .
mypy src/mcp_1c
black --check .
```
### Форматирование
```bash
ruff check --fix .
black .
```
## Требования
- Python 3.11+
- MCP SDK 1.0+
- lxml 5.0+
- aiosqlite 0.19+
- watchfiles 0.21+
### Опционально
- BSL Language Server — для валидации и форматирования BSL кода
## Лицензия
MIT License. См. файл [LICENSE](LICENSE).
## Авторы
- MCP-1C Team
## Ссылки
- [MCP Protocol](https://modelcontextprotocol.io/)
- [1C:Enterprise](https://1c.ru/)
- [BSL Language Server](https://github.com/1c-syntax/bsl-language-server)
MCP Config
Below is the configuration for this MCP Server. You can copy it directly to Cursor or other MCP clients.
mcp.json
Connection Info
You Might Also Like
markitdown
MarkItDown-MCP is a lightweight server for converting URIs to Markdown.
firecrawl
Firecrawl MCP Server enables web scraping, crawling, and content extraction.
servers
Model Context Protocol Servers
Time
A Model Context Protocol server for time and timezone conversions.
Filesystem
Node.js MCP Server for filesystem operations with dynamic access control.
Sequential Thinking
A structured MCP server for dynamic problem-solving and reflective thinking.