@lionchat/mcp-server 0.2.1 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,248 @@
1
+ # Troubleshooting — Códigos de Erro Comuns
2
+
3
+ Como interpretar e responder a erros do MCP do LionChat.
4
+
5
+ ## HTTP Status Codes
6
+
7
+ ### 200 OK / 201 Created
8
+ Tudo certo. Use o body.
9
+
10
+ ### 204 No Content
11
+ Sucesso, mas sem corpo. Comum em DELETE e algumas updates. NÃO espere JSON de volta.
12
+
13
+ ### 400 Bad Request
14
+ Input malformado. Causas comuns:
15
+ - JSON inválido
16
+ - Campo obrigatório faltando
17
+ - Tipo errado (passou string onde esperava number)
18
+
19
+ **Ação:** Releia a mensagem de erro. Corrija o payload. NÃO retry sem mudar nada.
20
+
21
+ ### 401 Unauthorized
22
+ Token de API inválido ou expirado.
23
+
24
+ **Ação:** Parar. Reportar pro usuário que precisa renovar credenciais. NÃO retry — vai falhar igual.
25
+
26
+ ### 403 Forbidden
27
+ Token válido, mas SEM permissão pra essa ação.
28
+
29
+ Causas:
30
+ - Agente tentando ação de admin
31
+ - Conta diferente do escopo do token
32
+ - Feature flag desativada na conta
33
+ - Recurso pertence a outra conta (multi-tenant)
34
+
35
+ **Ação:** NÃO bypass. Informar limitação ao usuário.
36
+
37
+ ### 404 Not Found
38
+ Recurso não existe.
39
+
40
+ Causas comuns:
41
+ - ID errado
42
+ - Recurso foi deletado
43
+ - Está em outra conta
44
+ - Endpoint URL errado
45
+
46
+ **Ação:** Verificar se ID está correto. Se foi deletado, informar.
47
+
48
+ ### 422 Unprocessable Entity
49
+ Dados passaram na sintaxe mas falharam validação.
50
+
51
+ Exemplo de response:
52
+ ```json
53
+ {
54
+ "errors": {
55
+ "email": ["já está em uso"],
56
+ "phone_number": ["formato inválido"]
57
+ }
58
+ }
59
+ ```
60
+
61
+ **Ação:** Ler `errors`, ajustar dados, reenviar.
62
+
63
+ ### 429 Too Many Requests
64
+ Rate limit estourado.
65
+
66
+ Response inclui header `Retry-After: 60` (segundos).
67
+
68
+ **Ação:**
69
+ - Esperar o tempo indicado
70
+ - Reduzir concorrência
71
+ - Avaliar se está fazendo loop ineficiente
72
+
73
+ NÃO retry imediato — só piora.
74
+
75
+ ### 500 Internal Server Error
76
+ Erro do servidor LionChat.
77
+
78
+ **Ação:**
79
+ - Retry 1x após 2-5 segundos
80
+ - Se persiste, reportar pro usuário com timestamp/request ID
81
+
82
+ ### 502 Bad Gateway / 503 Service Unavailable
83
+ Indisponibilidade temporária (deploy, manutenção, sobrecarga).
84
+
85
+ **Ação:** Retry com backoff exponencial (2s, 4s, 8s). Máx 3 tentativas.
86
+
87
+ ### 504 Gateway Timeout
88
+ Operação demorou demais.
89
+
90
+ Causas:
91
+ - Query muito pesada (sem filtro)
92
+ - Export grande (use exports assíncronos)
93
+
94
+ **Ação:** Reformular a chamada com filtros mais agressivos.
95
+
96
+ ## Erros específicos do MCP
97
+
98
+ ### "mcp_not_enabled"
99
+ Status: 403
100
+
101
+ A conta não tem a feature MCP habilitada.
102
+
103
+ **Ação:** Pedir admin pra ativar no plano ou via Super Admin.
104
+
105
+ ### "admin_required"
106
+ Status: 403
107
+
108
+ Só administradores podem usar essa funcionalidade.
109
+
110
+ **Ação:** Usuário com role `agent` precisa pedir pro admin.
111
+
112
+ ### "invalid_account"
113
+ Status: 400 ou 404
114
+
115
+ `account_id` não pertence ao usuário autenticado.
116
+
117
+ **Ação:** Listar contas do user (`list_my_accounts`) e usar uma válida.
118
+
119
+ ### "feature_disabled"
120
+ Status: 403
121
+
122
+ Feature flag específica (ex: `feature_kanban`, `feature_captain`) está OFF.
123
+
124
+ **Ação:** Reportar qual feature precisa ser ativada.
125
+
126
+ ## Erros de validação comuns
127
+
128
+ ### Conversation
129
+ - `"contact must exist"` — passou `contact_id` inválido
130
+ - `"inbox must exist"` — `inbox_id` errado
131
+ - `"status invalid"` — use 0, 1, 2 ou 3 (open/resolved/pending/snoozed)
132
+
133
+ ### Contact
134
+ - `"email has already been taken"` — duplicado na conta
135
+ - `"phone_number has already been taken"` — mesmo problema
136
+ - `"phone_number must be a valid number with country code"` — formato E.164: `+5511999999999`
137
+
138
+ ### Message
139
+ - `"content can't be blank"` — mensagem vazia (use template se for attachment-only)
140
+ - `"private must be boolean"` — true/false, não string
141
+
142
+ ### KanbanItem
143
+ - `"funnel_stage does not exist in funnel"` — etapa inválida pro funil
144
+ - `"conversation_display_id must exist"` — conversa não existe ou foi deletada
145
+ - `"position must be a positive integer"` — não pode ser negativo
146
+
147
+ ## Cenários problemáticos
148
+
149
+ ### "Estou recebendo 401 mesmo com token correto"
150
+ Possíveis causas:
151
+ - Token foi revogado
152
+ - Conta foi suspensa (`feature_account_suspended`)
153
+ - Token de outra conta
154
+
155
+ Verificar: `GET /api/v1/profile` (se 401 aqui, token tá inválido)
156
+
157
+ ### "GET retorna 200 mas POST/PATCH retorna 403"
158
+ Token tem `scope: read` apenas. Precisa de token com scope completo pra escritas.
159
+
160
+ ### "Operação foi pelo MCP mas não aparece na UI"
161
+ - Frontend pode estar com cache (refresh)
162
+ - WebSocket pode estar caído
163
+ - Pode ter sido criado em outra conta (verificar `account_id`)
164
+
165
+ ### "Timer/job rodou mas dados estão errados"
166
+ Sidekiq pode estar retry-ando. Verificar:
167
+ - Job tem `discard_on` apropriado?
168
+ - Status final no banco vs UI
169
+
170
+ ### "Tool não está disponível"
171
+ Possíveis razões:
172
+ - MCP server não foi atualizado (`npm install -g @lionchat/mcp-server@latest`)
173
+ - Feature flag bloqueando endpoint
174
+ - Plano do cliente não inclui a feature
175
+
176
+ ### "Rate limit constante"
177
+ Padrões que causam:
178
+ - Polling agressivo (use webhooks)
179
+ - Listar tudo sem paginar
180
+ - Não cache de dados estáticos
181
+ - Loop sem `break` apropriado
182
+
183
+ ## Webhooks como alternativa a polling
184
+
185
+ Se você precisa monitorar mudanças em conversas/mensagens, NÃO faça polling:
186
+
187
+ ```
188
+ Polling errado:
189
+ while True: GET /conversations every 5s → MUITO ruim
190
+ ```
191
+
192
+ Use webhooks (config na conta):
193
+ - `conversation_created`
194
+ - `message_created`
195
+ - `conversation_resolved`
196
+ - Etc
197
+
198
+ LionChat envia POST pro seu endpoint quando o evento dispara.
199
+
200
+ ## OAuth (apenas MCP Remote)
201
+
202
+ ### "invalid_client_metadata"
203
+ Cliente OAuth registrado errado. Verifique:
204
+ - `token_endpoint_auth_method` = `none` (pra Claude/ChatGPT)
205
+ - `redirect_uris` exato (https, sem trailing slash extra)
206
+
207
+ ### "invalid_grant"
208
+ Auth code expirou (vida curta — segundos). Refazer login.
209
+
210
+ ### "Conector desconectou sozinho"
211
+ Geralmente: refresh_token expirou (TTL passou).
212
+
213
+ Hoje no LionChat: TTL é ~100 anos. Se desconectar, provavelmente:
214
+ - Token revogado manualmente
215
+ - Conta suspensa
216
+ - Restart do serviço MCP Remote
217
+
218
+ ### "Consent loop infinito"
219
+ Bug conhecido: `Grant` não criado explicitamente. Atualizar MCP Remote pra versão >= 0.3.0.
220
+
221
+ ## Logs e debugging
222
+
223
+ ### Como pegar request ID
224
+ Toda resposta da API tem header `X-Request-ID`. Inclua no relatório se algo falhar.
225
+
226
+ ### Como ver logs do MCP Server local
227
+ ```bash
228
+ # Stdio MCP imprime em stderr — capture no Claude Desktop logs:
229
+ ~/Library/Logs/Claude/mcp*.log
230
+ ```
231
+
232
+ ### Como ver logs do MCP Remote (servidor produção)
233
+ - Painel Portainer → serviço `mcp_remote` → logs
234
+ - Cloudflare Worker logs (se proxy)
235
+ - Sentry pra exceptions
236
+
237
+ ## Quando reportar pro suporte
238
+
239
+ Reporte se:
240
+ - 500/502/503 persistente após 3 retries
241
+ - 401 com token recém-gerado
242
+ - Dados sumindo sem ação clara
243
+ - Comportamento inconsistente entre contas
244
+
245
+ NÃO precisa reportar:
246
+ - 4xx (você fez algo errado)
247
+ - Rate limit (esperado)
248
+ - 404 de recurso deletado
package/dist/index.js CHANGED
@@ -7,6 +7,9 @@ import { dirname, resolve } from 'path';
7
7
  import { loadConfig } from './config.js';
8
8
  import { LionChatClient } from './client.js';
9
9
  import { registerTools } from './tools.js';
10
+ import { getServerInstructions } from './instructions.js';
11
+ import { registerResources } from './resources.js';
12
+ import { registerPrompts } from './prompts.js';
10
13
  // AIDEV-NOTE: Read version from package.json to avoid hardcoding in multiple places
11
14
  const __dirname = dirname(fileURLToPath(import.meta.url));
12
15
  const pkg = JSON.parse(readFileSync(resolve(__dirname, '..', 'package.json'), 'utf-8'));
@@ -21,20 +24,33 @@ async function main() {
21
24
  !config.baseUrl.includes('127.0.0.1')) {
22
25
  console.error('WARNING: Base URL is not HTTPS. API token may be transmitted in cleartext.');
23
26
  }
24
- // AIDEV-NOTE: Create MCP server instance with name and version from package.json
27
+ // AIDEV-NOTE: Create MCP server com instructions, capabilities (tools/resources/prompts).
28
+ // Instructions explica modelo de dados, convencoes, glossario pra IA conectada.
25
29
  const server = new McpServer({
26
30
  name: 'lionchat-mcp-server',
27
31
  version: VERSION,
32
+ }, {
33
+ instructions: getServerInstructions(),
34
+ capabilities: {
35
+ tools: {},
36
+ resources: { subscribe: false, listChanged: false },
37
+ prompts: { listChanged: false },
38
+ },
28
39
  });
29
40
  // AIDEV-NOTE: Create HTTP client that wraps fetch calls to LionChat API
30
41
  const client = new LionChatClient(config);
31
42
  // AIDEV-NOTE: Register tools from endpoints.json, filtered by config.categories if set
32
43
  const toolCount = registerTools(server, config, client);
44
+ // AIDEV-NOTE: Resources (docs sob demanda) + Prompts (templates de workflow)
45
+ registerResources(server);
46
+ registerPrompts(server);
33
47
  // AIDEV-NOTE: Use stderr for logs — stdout is reserved for MCP JSON-RPC protocol
34
48
  console.error(`LionChat MCP Server v${VERSION}`);
35
49
  console.error(`Base URL: ${config.baseUrl}`);
36
50
  console.error(`Account: ${config.accountId}`);
37
51
  console.error(`Tools registered: ${toolCount}`);
52
+ console.error(`Resources registered: 8 (glossary, data-model, reports-guide, api-conventions, conversation-flows, kanban-deep-dive, best-practices, troubleshooting)`);
53
+ console.error(`Prompts registered: 8 (productivity_report, stuck_leads, weekly_recap, customer_health, inactive_contacts, team_load_balance, quality_audit, whatsapp_template_usage)`);
38
54
  if (config.categories) {
39
55
  console.error(`Categories filter: ${config.categories.join(', ')}`);
40
56
  }
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAEA,OAAO,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAC;AACpE,OAAO,EAAE,oBAAoB,EAAE,MAAM,2CAA2C,CAAC;AACjF,OAAO,EAAE,YAAY,EAAE,MAAM,IAAI,CAAC;AAClC,OAAO,EAAE,aAAa,EAAE,MAAM,KAAK,CAAC;AACpC,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AACxC,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAC7C,OAAO,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAE3C,oFAAoF;AACpF,MAAM,SAAS,GAAG,OAAO,CAAC,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;AAC1D,MAAM,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,YAAY,CAAC,OAAO,CAAC,SAAS,EAAE,IAAI,EAAE,cAAc,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC;AACxF,MAAM,OAAO,GAAW,GAAG,CAAC,OAAO,CAAC;AAEpC,KAAK,UAAU,IAAI;IACjB,IAAI,CAAC;QACH,6FAA6F;QAC7F,MAAM,MAAM,GAAG,UAAU,EAAE,CAAC;QAE5B,+EAA+E;QAC/E,IACE,CAAC,MAAM,CAAC,OAAO,CAAC,UAAU,CAAC,UAAU,CAAC;YACtC,CAAC,MAAM,CAAC,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAC;YACrC,CAAC,MAAM,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AAC;QACtE,CAAC;QAED,kEAAkE;QAClE,MAAM,SAAS,GAAG,IAAI,oBAAoB,EAAE,CAAC;QAC7C,MAAM,MAAM,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;IAClC,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,CAAC,KAAK,CAAC,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;QACtE,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC;AACH,CAAC;AAED,IAAI,EAAE,CAAC"}
@@ -0,0 +1 @@
1
+ export declare function getServerInstructions(): string;
@@ -0,0 +1,26 @@
1
+ // AIDEV-NOTE: Carrega instructions.md de src/docs (dev) ou dist/docs (prod).
2
+ // Sincronizado de docs-lionchat/mcp/instructions.md via sync-to-mcps.sh.
3
+ // Conteudo enviado pra IA conectada via McpServer instructions option.
4
+ import { readFileSync, existsSync } from 'node:fs';
5
+ import { dirname, join } from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+ const __dirname = dirname(fileURLToPath(import.meta.url));
8
+ let cachedInstructions = null;
9
+ export function getServerInstructions() {
10
+ if (cachedInstructions !== null)
11
+ return cachedInstructions;
12
+ const candidates = [
13
+ join(__dirname, '../docs/instructions.md'),
14
+ join(__dirname, '../../src/docs/instructions.md'),
15
+ ];
16
+ for (const filepath of candidates) {
17
+ if (existsSync(filepath)) {
18
+ cachedInstructions = readFileSync(filepath, 'utf-8');
19
+ return cachedInstructions;
20
+ }
21
+ }
22
+ cachedInstructions =
23
+ 'LionChat MCP Server — Plataforma brasileira de atendimento. Consulte resources/list pra mais info.';
24
+ return cachedInstructions;
25
+ }
26
+ //# sourceMappingURL=instructions.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"instructions.js","sourceRoot":"","sources":["../src/instructions.ts"],"names":[],"mappings":"AAAA,6EAA6E;AAC7E,yEAAyE;AACzE,uEAAuE;AAEvE,OAAO,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACnD,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAEzC,MAAM,SAAS,GAAG,OAAO,CAAC,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;AAE1D,IAAI,kBAAkB,GAAkB,IAAI,CAAC;AAE7C,MAAM,UAAU,qBAAqB;IACnC,IAAI,kBAAkB,KAAK,IAAI;QAAE,OAAO,kBAAkB,CAAC;IAE3D,MAAM,UAAU,GAAG;QACjB,IAAI,CAAC,SAAS,EAAE,yBAAyB,CAAC;QAC1C,IAAI,CAAC,SAAS,EAAE,gCAAgC,CAAC;KAClD,CAAC;IAEF,KAAK,MAAM,QAAQ,IAAI,UAAU,EAAE,CAAC;QAClC,IAAI,UAAU,CAAC,QAAQ,CAAC,EAAE,CAAC;YACzB,kBAAkB,GAAG,YAAY,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;YACrD,OAAO,kBAAkB,CAAC;QAC5B,CAAC;IACH,CAAC;IAED,kBAAkB;QAChB,oGAAoG,CAAC;IACvG,OAAO,kBAAkB,CAAC;AAC5B,CAAC"}
@@ -0,0 +1,2 @@
1
+ import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
+ export declare function registerPrompts(server: McpServer): void;
@@ -0,0 +1,70 @@
1
+ // AIDEV-NOTE: Registra MCP Prompts no McpServer (high-level SDK).
2
+ // Templates JSON sincronizados de docs-lionchat/mcp/prompts/.
3
+ // Cada prompt declara argumentos opcionais e um template Mustache-style ({{var|default}}).
4
+ import { readFileSync, readdirSync, existsSync } from 'node:fs';
5
+ import { dirname, join } from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+ import { z } from 'zod';
8
+ const __dirname = dirname(fileURLToPath(import.meta.url));
9
+ function findPromptsDir() {
10
+ const candidates = [
11
+ join(__dirname, '../docs/prompts'),
12
+ join(__dirname, '../../src/docs/prompts'),
13
+ ];
14
+ for (const p of candidates) {
15
+ if (existsSync(p))
16
+ return p;
17
+ }
18
+ return null;
19
+ }
20
+ function loadPrompts() {
21
+ const dir = findPromptsDir();
22
+ if (!dir) {
23
+ console.error('[mcp] prompts directory not found');
24
+ return [];
25
+ }
26
+ const files = readdirSync(dir).filter((f) => f.endsWith('.json'));
27
+ const prompts = [];
28
+ for (const file of files) {
29
+ try {
30
+ const parsed = JSON.parse(readFileSync(join(dir, file), 'utf-8'));
31
+ if (parsed.name && parsed.template)
32
+ prompts.push(parsed);
33
+ }
34
+ catch (err) {
35
+ console.error(`[mcp] failed to parse ${file}: ${err.message}`);
36
+ }
37
+ }
38
+ return prompts;
39
+ }
40
+ function renderTemplate(template, args) {
41
+ return template.replace(/\{\{(\w+)(?:\|([^}]*))?\}\}/g, (_m, name, fallback) => {
42
+ const value = args[name];
43
+ if (value !== undefined && value !== '')
44
+ return String(value);
45
+ return fallback ?? '';
46
+ });
47
+ }
48
+ export function registerPrompts(server) {
49
+ const prompts = loadPrompts();
50
+ for (const prompt of prompts) {
51
+ // Build Zod schema from argument list (all optional)
52
+ const argsSchema = {};
53
+ for (const arg of prompt.arguments) {
54
+ argsSchema[arg.name] = z.string().optional().describe(arg.description);
55
+ }
56
+ server.prompt(prompt.name, prompt.description, argsSchema, async (args) => {
57
+ const rendered = renderTemplate(prompt.template, args);
58
+ return {
59
+ description: prompt.title,
60
+ messages: [
61
+ {
62
+ role: 'user',
63
+ content: { type: 'text', text: rendered },
64
+ },
65
+ ],
66
+ };
67
+ });
68
+ }
69
+ }
70
+ //# sourceMappingURL=prompts.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prompts.js","sourceRoot":"","sources":["../src/prompts.ts"],"names":[],"mappings":"AAAA,kEAAkE;AAClE,8DAA8D;AAC9D,2FAA2F;AAE3F,OAAO,EAAE,YAA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;gBACzB,QAAQ,EAAE;oBACR;wBACE,IAAI,EAAE,MAAM;wBACZ,OAAO,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE;qBAC1C;iBACF;aACF,CAAC;QACJ,CAAC,CACF,CAAC;IACJ,CAAC;AACH,CAAC"}
@@ -0,0 +1,10 @@
1
+ import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
+ interface ResourceDef {
3
+ name: string;
4
+ uri: string;
5
+ description: string;
6
+ filename: string;
7
+ }
8
+ export declare const RESOURCES: ResourceDef[];
9
+ export declare function registerResources(server: McpServer): void;
10
+ export {};
@@ -0,0 +1,90 @@
1
+ // AIDEV-NOTE: Registra MCP Resources no McpServer (high-level SDK).
2
+ // 4 docs Markdown sincronizados de docs-lionchat/mcp/resources/.
3
+ import { readFileSync, existsSync } from 'node:fs';
4
+ import { dirname, join } from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ const __dirname = dirname(fileURLToPath(import.meta.url));
7
+ export const RESOURCES = [
8
+ {
9
+ name: 'Glossario LionChat',
10
+ uri: 'lionchat://docs/glossary',
11
+ description: 'Glossario completo de termos, status codes, enums e conceitos. Consulte sempre que encontrar campo numerico ou enum desconhecido.',
12
+ filename: 'glossary.md',
13
+ },
14
+ {
15
+ name: 'Modelo de Dados',
16
+ uri: 'lionchat://docs/data-model',
17
+ description: 'Mapa completo de entidades, relacionamentos e FKs. Use quando precisar entender como dados conectam.',
18
+ filename: 'data-model.md',
19
+ },
20
+ {
21
+ name: 'Guia de Relatorios',
22
+ uri: 'lionchat://docs/reports-guide',
23
+ description: 'Como interpretar cada um dos 19 endpoints de relatorio. Unidades, comparativos, business hours, CSAT, SLA.',
24
+ filename: 'reports-guide.md',
25
+ },
26
+ {
27
+ name: 'Convencoes da API',
28
+ uri: 'lionchat://docs/api-conventions',
29
+ description: 'Auth, paginacao, filtros, datas, codigos HTTP, rate limits. Use quando tiver duvida sobre como chamar endpoint.',
30
+ filename: 'api-conventions.md',
31
+ },
32
+ {
33
+ name: 'Fluxos de Conversacao',
34
+ uri: 'lionchat://docs/conversation-flows',
35
+ description: 'Ciclo de vida de uma conversa: criacao, greeting, auto-assignment, Captain IA, resolucao, snooze. Use pra diagnosticar comportamento de conversas.',
36
+ filename: 'conversation-flows.md',
37
+ },
38
+ {
39
+ name: 'Kanban Detalhado',
40
+ uri: 'lionchat://docs/kanban-deep-dive',
41
+ description: 'Estrutura completa do Kanban: Funnel, stages, KanbanItem, item_details, pipeline, activities. Use ao trabalhar com cards ou funis.',
42
+ filename: 'kanban-deep-dive.md',
43
+ },
44
+ {
45
+ name: 'Boas Praticas',
46
+ uri: 'lionchat://docs/best-practices',
47
+ description: 'Como economizar tokens, evitar rate limits, usar filtros, paginar. Consulte antes de workflows pesados ou loops em massa.',
48
+ filename: 'best-practices.md',
49
+ },
50
+ {
51
+ name: 'Troubleshooting',
52
+ uri: 'lionchat://docs/troubleshooting',
53
+ description: 'Codigos HTTP, erros comuns (401/403/422/429), erros MCP, debugging, quando reportar suporte. Use pra interpretar erros.',
54
+ filename: 'troubleshooting.md',
55
+ },
56
+ ];
57
+ function findDocsPath(filename) {
58
+ const candidates = [
59
+ join(__dirname, '../docs/resources', filename),
60
+ join(__dirname, '../../src/docs/resources', filename),
61
+ ];
62
+ for (const p of candidates) {
63
+ if (existsSync(p))
64
+ return p;
65
+ }
66
+ return null;
67
+ }
68
+ export function registerResources(server) {
69
+ for (const res of RESOURCES) {
70
+ server.registerResource(res.name, res.uri, {
71
+ description: res.description,
72
+ mimeType: 'text/markdown',
73
+ }, async (uri) => {
74
+ const filepath = findDocsPath(res.filename);
75
+ if (!filepath) {
76
+ throw new Error(`Resource file missing: ${res.filename}`);
77
+ }
78
+ return {
79
+ contents: [
80
+ {
81
+ uri: uri.href,
82
+ mimeType: 'text/markdown',
83
+ text: readFileSync(filepath, 'utf-8'),
84
+ },
85
+ ],
86
+ };
87
+ });
88
+ }
89
+ }
90
+ //# sourceMappingUR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