lk-tko-mcp
lk-tko-mcp
Servidor MCP (Model Context Protocol) en Python que da a Claude acceso a las herramientas del sistema ЛК (cuenta personal, proyecto lk-tko-v2).
Qué es y para qué
MCP es un protocolo abierto por el que un proceso externo entrega a la LLM un conjunto de «herramientas» (tools): funciones ordinarias con argumentos tipados. Al conectar el servidor a Claude Code, se puede pedir a Claude que invoque una función concreta («obtener el estado del contraparte por INN», «calcular los intereses de demora por período para lkUser», etc.) en lugar de explicar el contexto con texto o tener que entrar en la BD/el código manualmente cada vez.
El objetivo de este pet project es disponer de una capa de herramientas reutilizable sobre la lógica de negocio de ЛК, que se pueda usar desde cualquier futura sesión de Claude Code, y no solo dentro del repositorio principal.
Related MCP server: MikroCLAW
Stack
Python 3.10+, gestor de dependencias —
uvSDK:
mcp[cli](v2, paquetemcp==2.1.0), clasemcp.server.MCPServerTransporte: stdio (Claude Code lanza el proceso y se comunica con él a través de stdin/stdout)
Stack de integración
La primera tool (get_contragent_status) accede a la CUBA REST API v2 de lk-tko-v2 (OAuth2 password grant + generic entity search por rtneo$Contragent), no directamente a la BD. El formato de las peticiones está confirmado por ejemplos funcionales del curls.txt del repositorio lk-tko-v2.
Estructura
lk-tko-mcp/
├── server.py # MCPServer + @mcp.tool() функции — вся логика инструментов
├── lk_client.py # REST-клиент к lk-tko-v2 (OAuth2 + entity search)
├── run.py # точка входа, которую регистрирует Claude Code
├── .env.example # шаблон переменных окружения для доступа к ЛК (реальный .env не коммитится)
├── pyproject.toml
└── uv.lockEjecución y verificación local
uv run mcp dev run.py # открывает MCP Inspector в браузере — можно вручную вызывать toolsConexión con Claude Code
claude mcp add lk-tko-mcp -- uv run run.py
claude mcp list # проверить, что статус ConnectedPlan de desarrollo
Esqueleto — listo. Servidor con
pingyget_contragent_status; se ejecuta localmente y mediante Inspector.Cliente REST — listo.
lk_client.py: OAuth2 password grant con caché de token +search_entity()sobre CUBA REST v2.Primera integración real — lista y probada en vivo.
get_contragent_statusinvoca realmente la REST API de lk-tko-v2 mediantelk_client.search_entity("rtneo$Contragent", ...), probado con MCP Inspector con datos reales del entorno de pruebas.Conexión con Claude Code — lista.
claude mcp add lk-tko-mcp -- uv run run.py, estado✔ Connected. Guía de despliegue para otros desarrolladores — verONBOARDING.md.Deuda/facturación (Prioridad 1 de RESEARCH.md) — listo, 6 de 7 verificados.
get_contragent_debt,get_debt_by_phone,get_debt_by_email,get_serviced_periods,get_calculation_amount_type,get_contract,get_fine_details— todos implementados mediante dos nuevos helpers REST enlk_client.py(call_v3para controladores v3 personalizados,call_servicepara servicios v2 declarativos).get_contragent_billsestá implementado, pero bloqueado por un bug en lk-tko-v2 (ver nota más abajo).get_calculations_tabs,get_debt_breakdown_by_real_estate,find_contragents_with_debt_older_than— no implementados; no tienen ningún wrapper REST en lk-tko-v2 (confirmado con grep en todo el repositorio).
Problemas conocidos
get_contragent_billsfalla con 500. Bug en lk-tko-v2:BillRepository.getBillsByContragentAndPeriod(línea 71) hace referencia a un alias inexistenteb.documentNumberen lugar dee.documentNumber— rompe la compilación JPQL en cualquier llamada a/app/rest/v3/bill. Se ha registrado una tarea aparte para su corrección en lk-tko-v2; nuestro código no tiene nada que ver.
Ampliación del conjunto de herramientas — una herramienta por cada escenario concreto y recurrente (por ejemplo, período/intereses de demora para lkUser — ver la memoria del proyecto
project_lk_user_config), sin abstraer de antemano.(Opcional) acceso del equipo —
claude mcp add lk-tko-mcp --scope project -- uv run run.pycreará un.mcp.jsonen el repositorio, que se puede incluir en un commit (sin secretos).
Verificación (después de rellenar .env)
# 1. Юнит-уровень, без Claude
uv run python -c "from lk_client import search_entity; print(search_entity('rtneo$Contragent', [{'property':'inn','operator':'=','value':'<реальный ИНН>'}]))"
# 2. Через MCP Inspector
uv run mcp dev run.py
# 3. End-to-end
claude mcp add lk-tko-mcp -- uv run run.py
claude mcp listNotas de seguridad
.envno se hace commit; los secretos reales (client_id/secret, login/contraseña) se guardan solo localmente.Por defecto, apunta a una instancia local de desarrollo de lk-tko-v2 (
http://localhost:8080), no a staging/prod — allí puede haber datos personales no anonimizados.La entidad
Contragentno tiene un campo «estado» confirmado de antemano —get_contragent_statusdevuelve la entidad encontrada completa; el campo para el estado real debe determinarse según la respuesta de la REST API.
Available Tools
10 toolsget_calculation_amount_typeC
Тип расчёта начислений и текущий долг по лицевому счёту/ИНН.
Inputs: pa_or_inn (required).
get_contractB
Список договоров контрагента с суммами начислений/платежей/пеней/долга.
contragent_id — UUID контрагента (см. поле "id" в get_contragent_status).
Inputs: contragent_id (required).
get_contragent_billsB
Счета контрагента за период.
contragent_id — UUID контрагента (см. поле "id" в get_contragent_status). date_from/date_to — даты в формате dd.MM.yyyy.
Inputs: contragent_id (required), date_to, is_paid, date_from.
get_contragent_debtA
Долг контрагента (основной долг, пени, госпошлина) по лицевому счёту или ИНН.
Inputs: pa_or_inn (required).
get_contragent_statusB
Найти контрагента ЛК по ИНН и вернуть его данные.
Возвращает найденную сущность Contragent целиком через REST API lk-tko-v2 — отдельного поля "статус" может не быть, это нужно смотреть по реальным данным, которые вернёт CUBA REST.
Inputs: inn (required).
get_debt_by_emailB
Долг по всем лицевым счетам, привязанным к email.
Inputs: email (required).
get_debt_by_phoneB
Долг по всем лицевым счетам, привязанным к телефону.
Inputs: phone (required).
get_fine_detailsA
Детализация пеней по лицевому счёту за период, по договорам и месяцам.
date_from/date_to — даты в формате dd.MM.yyyy.
Inputs: date_to (required), date_from (required), personal_account (required).
get_serviced_periodsB
Периоды обслуживания (даты начала/окончания) лицевого счёта или ИНН.
Inputs: pa_or_inn (required).
pingA
Проверка того, что сервер жив и подключён.
Inputs: no named parameters. Returns: result
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 10 tools
There are several debt-related tools (get_contragent_debt, get_debt_by_phone, get_debt_by_email, get_calculation_amount_type, get_contract) whose outputs overlap in debt/penalty figures; descriptions clarify different lookup keys or levels, but an agent could still struggle to choose among them. ping and the document/period tools are clearly distinct.
All tools follow a get_ prefix and snake_case, and most use a readable get_<resource>_<detail> or get_<detail>_by_<identifier> pattern. The deviations are minor: ping has no get_, and names like get_calculation_amount_type are less intuitive than the rest.
Ten tools is a reasonable size for a debt/contract lookup server. Each tool covers a distinct query need without excessive redundancy or an overwhelming surface.
The set provides solid read-only coverage: contragent lookup, debt by multiple identifiers, bills, contracts, service periods, and fine details. A minor gap is the lack of a direct debt lookup by contragent UUID, which would require using an INN from get_contragent_status as a workaround.
Related MCP Connectors
Remote MCP utilities for agents: structured data, commerce checks, and x402 paid API discovery.
One MCP endpoint for Claude, GPT & Gemini: 100+ tools + no-code connectors + agent workers.
MCP server unifying ERPs, CRMs, APIs and knowledge base for Claude, ChatGPT and Gemini.
Pay-per-use tool marketplace for AI agents. Search, price-check, and call APIs via MCP.
Related MCP Servers
- AlicenseNot gradedqualityBmaintenanceEnables Claude to interact with Acumatica ERP through a remote MCP server with per-user OAuth, role-based access, and 44 tools for querying and managing ERP data.21Apache 2.0
- AlicenseBqualityCmaintenanceMCP server that enables Claude Code to access, monitor, and manage MikroTik RouterOS devices via its REST API, with 92 tools for read-only and optional write operations.92Apache 2.0
- FlicenseNot gradedqualityDmaintenanceConnects Claude to the Qoyod accounting system via its REST API, enabling natural language management of customers, invoices, vendors, journal entries, and other accounting resources through MCP tools.-
- AlicenseNot gradedqualityCmaintenanceEnables Claude Code to access amoCRM data such as pipelines, deals, contacts, and users via the MCP protocol.ISC