agent-master-devsecops 0.0.0-stage → 5.1.0

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.
Files changed (61) hide show
  1. package/README.md +204 -2
  2. package/agents/AGENT_DEVSECOPS.md +32 -0
  3. package/agents/AGENT_INFRA.md +31 -0
  4. package/agents/AGENT_ORCHESTRATOR.md +39 -0
  5. package/agents/AGENT_QA.md +58 -0
  6. package/agents/AGENT_SCRUM.md +23 -0
  7. package/agents/AGENT_SRE.md +22 -0
  8. package/agents/AGENT_UIUX.md +26 -0
  9. package/docs/ARCHITECTURE.md +152 -0
  10. package/docs/CALCULATIONS.md +17 -0
  11. package/docs/CHANGELOG.md +112 -0
  12. package/docs/ENGINEERING_RULES.md +56 -0
  13. package/docs/IDEAS.md +17 -0
  14. package/docs/LOCAL_BACKLOG.md +20 -0
  15. package/docs/STATE.md +111 -0
  16. package/docs/playbooks/PLAYBOOK_CIRCUIT_BREAKER_LLM.md +58 -0
  17. package/docs/playbooks/PLAYBOOK_OPENTELEMETRY_TRACING.md +58 -0
  18. package/package.json +57 -4
  19. package/scripts/auditors/a11y_auditor.js +462 -0
  20. package/scripts/auditors/code_quality_auditor.js +444 -0
  21. package/scripts/auditors/contract_test_validator.js +396 -0
  22. package/scripts/auditors/eval_harness.js +213 -0
  23. package/scripts/auditors/git_hygiene_linter.js +391 -0
  24. package/scripts/auditors/pr_reviewer.js +627 -0
  25. package/scripts/auditors/sast_scanner.js +442 -0
  26. package/scripts/auditors/sca_dependency_auditor.js +673 -0
  27. package/scripts/bin/bootstrap_cli.js +597 -0
  28. package/scripts/bin/domain_idea_miner.js +658 -0
  29. package/scripts/bin/smart_onboarding.js +905 -0
  30. package/scripts/bin/web_inspector.js +578 -0
  31. package/scripts/core/architecture_advisor.js +378 -0
  32. package/scripts/core/ast_skeletonizer.js +413 -0
  33. package/scripts/core/autonomous_remediation_engine.js +305 -0
  34. package/scripts/core/circuit_breaker.js +546 -0
  35. package/scripts/core/context_compressor.js +237 -0
  36. package/scripts/core/fast_feature_scaffold.js +840 -0
  37. package/scripts/core/hot_state_cache.js +238 -0
  38. package/scripts/core/knowledge_gateway.js +888 -0
  39. package/scripts/core/magic_prompt_generator.js +250 -0
  40. package/scripts/core/multi_agent_orchestrator.js +421 -0
  41. package/scripts/core/otel_tracer.js +335 -0
  42. package/scripts/core/perf_benchmark.js +212 -0
  43. package/scripts/core/sarif_engine.js +299 -0
  44. package/scripts/core/sre_remediation_engine.js +236 -0
  45. package/scripts/core/universal_packager.js +357 -0
  46. package/scripts/integrations/atlassian_client.js +600 -0
  47. package/scripts/integrations/atlassian_sync_action.js +576 -0
  48. package/scripts/integrations/confluence_sync.js +684 -0
  49. package/scripts/integrations/credentials_guard.js +500 -0
  50. package/scripts/integrations/jira_manager.js +722 -0
  51. package/scripts/mcp/handlers/atlassian_handlers.js +300 -0
  52. package/scripts/mcp/handlers/core_handlers.js +419 -0
  53. package/scripts/mcp/handlers/qa_handlers.js +502 -0
  54. package/scripts/mcp/handlers/rules_handlers.js +379 -0
  55. package/scripts/mcp/handlers/scaffold_handlers.js +334 -0
  56. package/scripts/mcp/handlers/sre_handlers.js +443 -0
  57. package/scripts/mcp/resources_registry.js +453 -0
  58. package/scripts/mcp/server.js +408 -0
  59. package/scripts/mcp/tool_handlers.js +444 -0
  60. package/scripts/mcp/tools_registry.js +1123 -0
  61. package/scripts/mcp_server.js +236 -0
@@ -0,0 +1,1123 @@
1
+ /**
2
+ * Tools Registry — Catálogo e Perfis de Ferramentas MCP
3
+ * Define o esquema JSON-RPC 2.0 e os perfis de late-binding (Regra 18).
4
+ * Versão: 5.1.0 Enterprise
5
+ */
6
+
7
+ 'use strict';
8
+
9
+ const { createSarifReport } = require('../core/sarif_engine.js');
10
+
11
+ const TOOLS = [
12
+ {
13
+ name: 'agent_get_rule',
14
+ description: 'Consulta um dos 10 Princípios Canônicos de Engenharia de Software & Governança (v5.0 Enterprise) ou mapeia regras legadas do ecossistema Agent Master.',
15
+ inputSchema: {
16
+ type: 'object',
17
+ properties: {
18
+ ruleNumber: {
19
+ type: 'integer',
20
+ description: 'Número do princípio canônico (1 a 10) ou regra legada (1 a 27)'
21
+ }
22
+ },
23
+ required: ['ruleNumber']
24
+ }
25
+ },
26
+ {
27
+ name: 'agent_validate_idea',
28
+ description: 'Aplica a Regra 14 (Ideation Sanity Filter): avalia criticamente uma ideia contra a stack, arquitetura e restrições reais do projeto.',
29
+ inputSchema: {
30
+ type: 'object',
31
+ properties: {
32
+ ideaTitle: { type: 'string', description: 'Título da ideia' },
33
+ ideaDescription: { type: 'string', description: 'Descrição da proposta' },
34
+ projectStack: { type: 'string', description: 'Stack tecnológica do projeto real' },
35
+ projectDomain: { type: 'string', description: 'Propósito/domínio do projeto' }
36
+ },
37
+ required: ['ideaTitle', 'ideaDescription', 'projectStack', 'projectDomain']
38
+ }
39
+ },
40
+ {
41
+ name: 'agent_recommend_architecture',
42
+ description: 'Atua como Principal Software Architect agnóstico: analisa requisitos e recomenda a melhor arquitetura e stack com análise imparcial de trade-offs e alerta de overengineering.',
43
+ inputSchema: {
44
+ type: 'object',
45
+ properties: {
46
+ description: { type: 'string', description: 'Descrição da necessidade ou problema de negócio' },
47
+ domain: { type: 'string', description: 'Domínio funcional (ex: pagamentos, iot, calculadora, dashboard, analytics)' },
48
+ scale: { type: 'string', description: 'Escala prevista: prototype, low, medium, high, extreme' },
49
+ criticality: { type: 'string', description: 'Criticidade: low, medium, high, critical' },
50
+ teamSize: { type: 'string', description: 'Contexto de equipe: solo, small, enterprise' },
51
+ userPreference: {
52
+ type: 'object',
53
+ properties: {
54
+ stack: { type: 'string', description: 'Stack pretendida pelo usuário (opcional)' },
55
+ architecture: { type: 'string', description: 'Arquitetura pretendida pelo usuário (opcional)' }
56
+ }
57
+ }
58
+ },
59
+ required: ['description']
60
+ }
61
+ },
62
+ {
63
+ name: 'agent_ground_knowledge',
64
+ description: 'Consulta o Dynamic Knowledge Gateway (v5.0 Enterprise) com grounding vivo em documentações e APIs oficiais (W3C WCAG/WAI-ARIA, CVEs OSV.dev, Spring Initializr Java 21 LTS e lifecycles de runtimes).',
65
+ inputSchema: {
66
+ type: 'object',
67
+ properties: {
68
+ action: {
69
+ type: 'string',
70
+ enum: [
71
+ 'query_osv',
72
+ 'get_wcag_spec',
73
+ 'get_spring_blueprint',
74
+ 'get_runtime_lts',
75
+ 'lookup_doc',
76
+ 'get_cache_stats',
77
+ 'clear_cache'
78
+ ],
79
+ description: 'Ação de consulta ou gestão de conhecimento oficial'
80
+ },
81
+ package: { type: 'string', description: 'Nome do pacote/dependência para auditoria OSV' },
82
+ version: { type: 'string', description: 'Versão do pacote para auditoria OSV' },
83
+ ecosystem: { type: 'string', description: 'Ecossistema (npm, Maven, PyPI, Go)' },
84
+ criterion: { type: 'string', description: 'Critério ou regra WCAG (ex: WCAG-1.1.1, alt, contraste)' },
85
+ tech: { type: 'string', description: 'Tecnologia ou runtime (java, node, go, python, spring)' },
86
+ topic: { type: 'string', description: 'Tópico de documentação arquitetural' },
87
+ bootVersion: { type: 'string', description: 'Versão do Spring Boot para blueprint' },
88
+ javaVersion: { type: 'string', description: 'Versão do Java LTS para blueprint' }
89
+ }
90
+ }
91
+ },
92
+ {
93
+ name: 'agent_audit_code',
94
+ description: 'Aciona o Revisor Crítico Adversário (AGENT_QA.md) para analisar um diff de código contra vulnerabilidades OWASP, ReDoS e integridade de testes.',
95
+ inputSchema: {
96
+ type: 'object',
97
+ properties: {
98
+ codeDiff: { type: 'string', description: 'Diff ou código a ser auditado friamente' },
99
+ context: { type: 'string', description: 'Contexto da funcionalidade ou card' }
100
+ },
101
+ required: ['codeDiff']
102
+ }
103
+ },
104
+ {
105
+ name: 'agent_full_dev_status',
106
+ description: 'Consulta o status atual do Modo Full Developer e a próxima ideia priorizada do backlog.',
107
+ inputSchema: {
108
+ type: 'object',
109
+ properties: {}
110
+ }
111
+ },
112
+ {
113
+ name: 'agent_eval_harness',
114
+ description: 'Executa avaliação empírica de conformidade da resposta de uma LLM contra os 10 Princípios Canônicos de Engenharia de Software & Governança (v5.0 Enterprise).',
115
+ inputSchema: {
116
+ type: 'object',
117
+ properties: {
118
+ modelName: { type: 'string', description: 'Nome do modelo avaliado (ex: Claude 3.5, GPT-4o, Gemini Pro, DeepSeek-R1)' },
119
+ promptSent: { type: 'string', description: 'Prompt de instrução enviado à LLM' },
120
+ responseReceived: { type: 'string', description: 'Resposta bruta recebida da LLM' }
121
+ },
122
+ required: ['modelName', 'responseReceived']
123
+ }
124
+ },
125
+ {
126
+ name: 'agent_generate_ide_plugins',
127
+ description: 'Gera arquivos de configuração e manifestos nativos para IDEs (.vscode e .idea) integrando o servidor MCP e atalhos de prompts.',
128
+ inputSchema: {
129
+ type: 'object',
130
+ properties: {
131
+ target: { type: 'string', enum: ['all', 'vscode', 'jetbrains'], description: 'IDE alvo da geração' },
132
+ targetDir: { type: 'string', description: 'Diretório raiz do projeto' }
133
+ }
134
+ }
135
+ },
136
+ {
137
+ name: 'agent_review_pr',
138
+ description: 'Executa a auditoria autônoma do Revisor Independente (AGENT_QA.md) contra um diff de código ou número de PR, emitindo veredito canônico e testes de quebra.',
139
+ inputSchema: {
140
+ type: 'object',
141
+ properties: {
142
+ diff: { type: 'string', description: 'Diff de código a ser auditado' },
143
+ files: { type: 'array', items: { type: 'string' }, description: 'Lista de caminhos de arquivos modificados' }
144
+ },
145
+ required: ['diff']
146
+ }
147
+ },
148
+ {
149
+ name: 'agent_compress_context',
150
+ description: 'Destila as instruções e regras do Agent Master em uma versão compacta de alta densidade semântica para modelos locais (Ollama 8B/14B) sob orçamento de 1.500 tokens.',
151
+ inputSchema: {
152
+ type: 'object',
153
+ properties: {
154
+ text: { type: 'string', description: 'Texto opcional customizado a ser compactado' },
155
+ maxTokens: { type: 'number', description: 'Orçamento máximo de tokens (padrão: 1500)' }
156
+ }
157
+ }
158
+ },
159
+ {
160
+ name: 'agent_sync_atlassian',
161
+ description: 'Registra um Remote Link de commit, branch ou Pull Request do GitHub diretamente em um card do Jira (ex: AGDEV-23).',
162
+ inputSchema: {
163
+ type: 'object',
164
+ properties: {
165
+ issueKey: { type: 'string', description: 'Chave do ticket Jira (ex: AGDEV-23, PROJ-53)' },
166
+ url: { type: 'string', description: 'URL no GitHub (commit, branch ou PR)' },
167
+ title: { type: 'string', description: 'Título descritivo do link' },
168
+ type: { type: 'string', enum: ['commit', 'branch', 'pr'], description: 'Tipo do vínculo remoto' }
169
+ },
170
+ required: ['issueKey', 'url', 'title']
171
+ }
172
+ },
173
+ {
174
+ name: 'agent_otel_trace',
175
+ description: 'Executa instrumentação de tracing distribuído compatível com OpenTelemetry e W3C TraceContext, gerando flamegraph ASCII e análise de gargalos.',
176
+ inputSchema: {
177
+ type: 'object',
178
+ properties: {
179
+ serviceName: { type: 'string', description: 'Nome do serviço instrumentado' },
180
+ spans: {
181
+ type: 'array',
182
+ items: {
183
+ type: 'object',
184
+ properties: {
185
+ name: { type: 'string' },
186
+ durationMs: { type: 'number' },
187
+ attributes: { type: 'object' }
188
+ },
189
+ required: ['name', 'durationMs']
190
+ },
191
+ description: 'Lista de spans a serem traçados'
192
+ },
193
+ thresholdMs: { type: 'number', description: 'Limiar em milissegundos para alertar gargalos de latência' }
194
+ }
195
+ }
196
+ },
197
+ {
198
+ name: 'agent_perf_benchmark',
199
+ description: 'Executa micro-benchmark de CPU/Throughput e memória Heap, comparando contra o baseline para detecção de regressões de performance (> 10%).',
200
+ inputSchema: {
201
+ type: 'object',
202
+ properties: {
203
+ iterations: { type: 'number', description: 'Número de repetições do benchmark (padrão: 100)' },
204
+ maxDegradationPct: { type: 'number', description: 'Porcentagem máxima tolerada de degradação (padrão: 10)' }
205
+ }
206
+ }
207
+ },
208
+ {
209
+ name: 'agent_circuit_breaker',
210
+ description: 'Gerencia o Circuit Breaker inteligente e comutação automática de provedores de IA (Anthropic, OpenAI, Groq, Ollama) com auto-cura e mitigação de HTTP 429/5xx.',
211
+ inputSchema: {
212
+ type: 'object',
213
+ properties: {
214
+ action: { type: 'string', enum: ['status', 'simulate_failover', 'reset'], description: 'Ação a ser executada' },
215
+ failureThreshold: { type: 'number', description: 'Limiar de falhas para rompimento do circuito (padrão: 3)' }
216
+ }
217
+ }
218
+ },
219
+ {
220
+ name: 'agent_orchestrate_event',
221
+ description: 'Despacha um evento no barramento multi-agente determinístico (EVENT_CODE_COMPLETE, EVENT_REVIEW_FAILED, EVENT_METRIC_ANOMALY, EVENT_REFACTOR_PROPOSAL, EVENT_AGENT_SELF_IMPROVE).',
222
+ inputSchema: {
223
+ type: 'object',
224
+ properties: {
225
+ eventType: {
226
+ type: 'string',
227
+ enum: [
228
+ 'EVENT_CODE_COMPLETE',
229
+ 'EVENT_REVIEW_FAILED',
230
+ 'EVENT_REVIEW_PASSED',
231
+ 'EVENT_METRIC_ANOMALY',
232
+ 'EVENT_REFACTOR_PROPOSAL',
233
+ 'EVENT_AGENT_SELF_IMPROVE'
234
+ ],
235
+ description: 'Tipo do evento canônico'
236
+ },
237
+ payload: {
238
+ type: 'object',
239
+ description: 'Dados contextuais do evento (diff, code, metric, finding, etc.)'
240
+ }
241
+ },
242
+ required: ['eventType']
243
+ }
244
+ },
245
+ {
246
+ name: 'agent_sast_scan',
247
+ description: 'Executa scanner estático SAST e detecção profunda de segredos (CWE-78, CWE-89, CWE-79, CWE-116, CWE-1333 ReDoS, CWE-798 Hardcoded Secrets). Suporta formato SARIF v2.1.0 e Semgrep CLI.',
248
+ inputSchema: {
249
+ type: 'object',
250
+ properties: {
251
+ code: { type: 'string', description: 'Código fonte ou diff para auditoria de segurança' },
252
+ filename: { type: 'string', description: 'Nome do arquivo analisado (opcional)' },
253
+ format: { type: 'string', enum: ['json', 'sarif'], description: 'Formato do relatório (json ou sarif v2.1.0)' }
254
+ },
255
+ required: ['code']
256
+ }
257
+ },
258
+ {
259
+ name: 'agent_remediate_code',
260
+ description: 'Motor Autônomo de Autocura DevSecOps em ciclo OODA: analisa vulnerabilidade SARIF, formula e aplica patch cirúrgico, valida suíte de testes do host e executa rollback automático se houver regressão.',
261
+ inputSchema: {
262
+ type: 'object',
263
+ properties: {
264
+ targetFile: { type: 'string', description: 'Caminho do arquivo a ser remediado' },
265
+ testCommand: { type: 'string', description: 'Comando de teste do host para verificação de não-regressão (ex: node --test, npm test)' },
266
+ projectRoot: { type: 'string', description: 'Diretório raiz do projeto alvo (opcional)' }
267
+ },
268
+ required: ['targetFile']
269
+ }
270
+ },
271
+ {
272
+ name: 'agent_audit_quality',
273
+ description: 'Audita a qualidade de código, complexidade ciclomática, profundidade de aninhamento e detecta anti-patterns como catch vazio e TODOs pendentes.',
274
+ inputSchema: {
275
+ type: 'object',
276
+ properties: {
277
+ code: { type: 'string', description: 'Código fonte para auditoria de qualidade' },
278
+ filename: { type: 'string', description: 'Nome do arquivo analisado (opcional)' },
279
+ maxComplexity: { type: 'number', description: 'Complexidade ciclomática máxima tolerada (padrão: 15)' }
280
+ },
281
+ required: ['code']
282
+ }
283
+ },
284
+ {
285
+ name: 'agent_sre_telemetry',
286
+ description: 'Coleta métricas canônicas de saúde e runtime no padrão Prometheus 0.0.4 (CPU, RSS, Heap V8) e avalia limiares de saturação.',
287
+ inputSchema: {
288
+ type: 'object',
289
+ properties: {
290
+ format: { type: 'string', enum: ['prometheus', 'json'], description: 'Formato da saída de métricas (padrão: json)' },
291
+ evaluateAlerts: { type: 'boolean', description: 'Se verdadeiro, executa avaliação de limiares de alerta' }
292
+ }
293
+ }
294
+ },
295
+ {
296
+ name: 'agent_sre_remediate',
297
+ description: 'Executa playbook de auto-remediação operacional SRE (purge_buffers, trigger_gc, reset_circuits, prune_cache) para mitigar saturação.',
298
+ inputSchema: {
299
+ type: 'object',
300
+ properties: {
301
+ action: {
302
+ type: 'string',
303
+ enum: ['purge_buffers', 'trigger_gc', 'reset_circuits', 'prune_cache'],
304
+ description: 'Ação de auto-cura a ser executada'
305
+ },
306
+ context: { type: 'object', description: 'Metadados contextuais do incidente' }
307
+ },
308
+ required: ['action']
309
+ }
310
+ },
311
+ {
312
+ name: 'agent_export_universal_bundle',
313
+ description: 'Exporta perfis, regras e configurações pré-moldadas do Agent Master para Cursor (.cursorrules), Windsurf (.windsurfrules), Claude Desktop, ChatGPT Custom GPTs ou Ollama local.',
314
+ inputSchema: {
315
+ type: 'object',
316
+ properties: {
317
+ platform: {
318
+ type: 'string',
319
+ enum: ['cursor', 'windsurf', 'claude_desktop', 'chatgpt', 'ollama', 'all'],
320
+ description: 'Plataforma alvo para exportação (ou "all" para todas)'
321
+ },
322
+ targetDir: { type: 'string', description: 'Diretório de destino para exportação' },
323
+ dryRun: { type: 'boolean', description: 'Simula a geração sem gravar arquivos físicos no disco' }
324
+ },
325
+ required: ['platform']
326
+ }
327
+ },
328
+ {
329
+ name: 'agent_bootstrap_environment',
330
+ description: 'Executa o auto-bootstrap do Agent Master DevSecOps: detecta IDEs e ferramentas instaladas (Cursor, Windsurf, VS Code, Claude Desktop, Ollama) e injeta regras e manifestos MCP com zero configuração em < 2 segundos.',
331
+ inputSchema: {
332
+ type: 'object',
333
+ properties: {
334
+ targetDir: { type: 'string', description: 'Diretório alvo do projeto (padrão: raiz do projeto)' },
335
+ dryRun: { type: 'boolean', description: 'Simula a detecção e geração sem escrever em disco' },
336
+ platforms: {
337
+ type: 'array',
338
+ items: { type: 'string' },
339
+ description: 'Lista explícita opcional de plataformas a configurar (caso queira forçar em vez de auto-detectar)'
340
+ }
341
+ }
342
+ }
343
+ },
344
+ {
345
+ name: 'agent_generate_magic_prompt',
346
+ description: 'Gera o Magic Prompt autocontido (< 900 tokens) e o Web Bookmarklet para ativação instantânea em 1 clique em interfaces web de LLMs (ChatGPT, Claude.ai, Gemini, DeepSeek).',
347
+ inputSchema: {
348
+ type: 'object',
349
+ properties: {
350
+ targetDir: { type: 'string', description: 'Diretório de exportação dos arquivos HTML e Markdown' },
351
+ dryRun: { type: 'boolean', description: 'Simula a geração sem gravar arquivos físicos no disco' }
352
+ }
353
+ }
354
+ },
355
+ {
356
+ name: 'agent_inspector_info',
357
+ description: 'Consulta informações, rotas de API e telemetria do Web Dashboard & Playground do Agent Master (servido via scripts/web_inspector.js na porta 4040).',
358
+ inputSchema: {
359
+ type: 'object',
360
+ properties: {
361
+ port: { type: 'number', description: 'Porta HTTP configurada (padrão: 4040)' }
362
+ }
363
+ }
364
+ },
365
+ {
366
+ name: 'agent_check_credentials',
367
+ description: 'Audita e executa healthcheck de autenticação no GitHub CLI e Atlassian (Jira e Confluence), orientando o setup de credenciais para garantir o Tríplice Registro contínuo.',
368
+ inputSchema: {
369
+ type: 'object',
370
+ properties: {
371
+ targetDir: { type: 'string', description: 'Diretório raiz do projeto (opcional)' }
372
+ }
373
+ }
374
+ },
375
+ {
376
+ name: 'agent_configure_credentials',
377
+ description: 'Configura credenciais de autenticação da Atlassian no arquivo .env local com garantia de proteção estrita no .gitignore.',
378
+ inputSchema: {
379
+ type: 'object',
380
+ properties: {
381
+ domain: { type: 'string', description: 'Domínio Atlassian (ex: sua-empresa.atlassian.net)' },
382
+ email: { type: 'string', description: 'Email da conta Atlassian' },
383
+ token: { type: 'string', description: 'API Token da Atlassian' },
384
+ jiraKey: { type: 'string', description: 'Chave do projeto Jira (ex: PROJ)' },
385
+ confluenceSpace: { type: 'string', description: 'Espaço do Confluence (ex: DOC)' },
386
+ targetDir: { type: 'string', description: 'Diretório raiz do projeto (opcional)' }
387
+ },
388
+ required: ['domain', 'email', 'token']
389
+ }
390
+ },
391
+ {
392
+ name: 'agent_standardize_kanban',
393
+ description: 'Padroniza qualquer quadro Jira para as 3 colunas canônicas ("A fazer", "Em andamento", "Concluído") e gera as consultas JQL e mapeamento unificado.',
394
+ inputSchema: {
395
+ type: 'object',
396
+ properties: {
397
+ projectKey: { type: 'string', description: 'Chave do projeto Jira (ex: AGDEV)' },
398
+ boardConfig: { type: 'object', description: 'Configuração opcional do quadro retornada pela API do Jira' }
399
+ },
400
+ required: ['projectKey']
401
+ }
402
+ },
403
+ {
404
+ name: 'agent_full_dev_pipeline',
405
+ description: 'Orquestra o ciclo do Modo Full Developer: lê "A fazer", aplica filtro de sanidade (Regra 14), planeja transição para "Em andamento", homologa e move para "Concluído" em loop recursivo.',
406
+ inputSchema: {
407
+ type: 'object',
408
+ properties: {
409
+ tasks: {
410
+ type: 'array',
411
+ items: { type: 'object' },
412
+ description: 'Lista de tarefas obtidas do Jira'
413
+ },
414
+ projectContext: {
415
+ type: 'object',
416
+ description: 'Contexto real do projeto (stack, domain, architecture)'
417
+ }
418
+ },
419
+ required: ['tasks']
420
+ }
421
+ },
422
+ {
423
+ name: 'agent_validate_rule15',
424
+ description: 'Valida compulsória e ativamente o cumprimento da Regra 15 (Imutabilidade de Requisitos e Pré-Validação de Segredos Atlassian e GitHub). Bloqueia falhas silenciosas.',
425
+ inputSchema: {
426
+ type: 'object',
427
+ properties: {
428
+ failFast: { type: 'boolean', description: 'Se true, levanta erro impeditivo caso faltem requisitos. Padrão: false' },
429
+ requireGitHub: { type: 'boolean', description: 'Exige autenticação válida do GitHub CLI. Padrão: true' },
430
+ requireAtlassian: { type: 'boolean', description: 'Exige credenciais válidas do ecossistema Atlassian. Padrão: true' }
431
+ }
432
+ }
433
+ },
434
+ {
435
+ name: 'agent_audit_a11y',
436
+ description: 'Audita código HTML, JSX e TSX contra diretrizes de acessibilidade WCAG 2.1 AA (AGENT_UIUX & AGENT_QA), verificando contraste, semântica ARIA, imagens sem alt e foco visível.',
437
+ inputSchema: {
438
+ type: 'object',
439
+ properties: {
440
+ code: { type: 'string', description: 'Código-fonte HTML, JSX ou TSX a ser auditado.' },
441
+ filename: { type: 'string', description: 'Nome do arquivo de origem (ex: Header.tsx).' }
442
+ },
443
+ required: ['code']
444
+ }
445
+ },
446
+ {
447
+ name: 'agent_lint_git_hygiene',
448
+ description: 'Audita mensagens de commit e nomes de branch contra a Regra 11 de Engenharia ([<TICKET>] - <Ação em português> e veto a Conventional Commits e prefixos legados).',
449
+ inputSchema: {
450
+ type: 'object',
451
+ properties: {
452
+ commitMessage: { type: 'string', description: 'Mensagem do commit a ser auditada' },
453
+ branchName: { type: 'string', description: 'Nome da branch a ser auditada' },
454
+ auditState: { type: 'boolean', description: 'Se true, audita o repositório Git local ativo' }
455
+ }
456
+ }
457
+ },
458
+ {
459
+ name: 'agent_audit_dependencies_sca',
460
+ description: 'Executa Software Composition Analysis (SCA) offline no manifesto package.json, detectando CVEs conhecidas e licenças restritivas (GPL/AGPL).',
461
+ inputSchema: {
462
+ type: 'object',
463
+ properties: {
464
+ packageJson: { type: 'string', description: 'Conteúdo JSON ou caminho do package.json a auditar' }
465
+ }
466
+ }
467
+ },
468
+ {
469
+ name: 'agent_validate_api_contract',
470
+ description: 'Valida contratos OpenAPI 3.x / Swagger 2.0 (Loop 2) e detecta Drifts arquiteturais entre contrato e rotas implementadas no código (Shadow APIs e rotas ausentes).',
471
+ inputSchema: {
472
+ type: 'object',
473
+ properties: {
474
+ spec: { type: 'string', description: 'Conteúdo JSON ou caminho do arquivo OpenAPI/Swagger' },
475
+ implementedRoutes: {
476
+ type: 'array',
477
+ items: {
478
+ type: 'object',
479
+ properties: {
480
+ method: { type: 'string' },
481
+ path: { type: 'string' }
482
+ },
483
+ required: ['method', 'path']
484
+ },
485
+ description: 'Lista de rotas implementadas no código para detecção de Drift'
486
+ }
487
+ },
488
+ required: ['spec']
489
+ }
490
+ },
491
+ {
492
+ name: 'agent_smart_onboarding',
493
+ description: 'Executa a Regra 16: detecta modo Greenfield vs Brownfield, mapeia a stack via engenharia reversa e orquestra o auto-provisionamento de Jira e Confluence sem páginas vazias.',
494
+ inputSchema: {
495
+ type: 'object',
496
+ properties: {
497
+ targetDir: {
498
+ type: 'string',
499
+ description: 'Caminho do projeto para auditoria/onboarding'
500
+ }
501
+ }
502
+ }
503
+ },
504
+ {
505
+ name: 'agent_verify_triad_gate',
506
+ description: 'Valida o Gate de Governança da Regra 16: bloqueia prompts de desenvolvimento de software caso a Tríade (Git + Jira + Confluence) não esteja 100% configurada, verificada e operacional.',
507
+ inputSchema: {
508
+ type: 'object',
509
+ properties: {
510
+ targetDir: {
511
+ type: 'string',
512
+ description: 'Caminho raiz do projeto a ser validado pelo Gate'
513
+ }
514
+ }
515
+ }
516
+ },
517
+ {
518
+ name: 'agent_extract_code_skeleton',
519
+ description: 'Extrai o esqueleto semântico de código (Rule 9), eliminando corpos de métodos para reduzir em até 90% o consumo de tokens de contexto entre módulos.',
520
+ inputSchema: {
521
+ type: 'object',
522
+ properties: {
523
+ code: { type: 'string', description: 'Código fonte a ser esqueletizado' },
524
+ language: { type: 'string', description: 'Linguagem do código (javascript, typescript, java, python)' }
525
+ },
526
+ required: ['code']
527
+ }
528
+ },
529
+ {
530
+ name: 'agent_scaffold_feature',
531
+ description: 'Gera atomicamente em 1 único turno (< 25ms) todos os arquivos de uma funcionalidade completa (Model, Repository, Service, Controller REST e Teste TDD), eliminando múltiplos roundtrips.',
532
+ inputSchema: {
533
+ type: 'object',
534
+ properties: {
535
+ name: { type: 'string', description: 'Nome da entidade/funcionalidade (ex: Filme)' },
536
+ domain: { type: 'string', description: 'Domínio funcional (ex: filmes)' },
537
+ package: { type: 'string', description: 'Pacote base (ex: br.com.empresa.filmes)' },
538
+ stack: { type: 'string', description: 'Stack ou linguagem tecnológica desejada (ex: typescript, nodejs, python, spring-boot, go, rust, html, csharp, elixir, etc.). Agnóstico e universal.' },
539
+ profile: { type: 'string', description: 'Intenção ou perfil arquitetural (ex: lightweight/educational, standard/clean-ddd, enterprise/banking, cli, microservice, prototype). Aberto e adaptativo.' },
540
+ persona: { type: 'string', description: 'Alias flexível para o perfil arquitetural/cognitivo' },
541
+ riskLevel: { type: 'string', enum: ['low', 'medium', 'high', 'critical'], description: 'Nível de risco regulatório e auditoria contábil' },
542
+ fields: {
543
+ type: 'array',
544
+ items: {
545
+ type: 'object',
546
+ properties: {
547
+ name: { type: 'string' },
548
+ type: { type: 'string' },
549
+ required: { type: 'boolean' },
550
+ isId: { type: 'boolean' }
551
+ },
552
+ required: ['name', 'type']
553
+ },
554
+ description: 'Lista de atributos da entidade'
555
+ },
556
+ writeToDisk: { type: 'boolean', description: 'Se true, grava os arquivos diretamente nas pastas' }
557
+ },
558
+ required: ['name']
559
+ }
560
+ },
561
+ {
562
+ name: 'agent_set_mcp_profile',
563
+ description: 'Altera o perfil de ferramentas ativas do MCP (Late-Binding de Ferramentas) para economizar tokens de contexto: "all", "fast_dev", "core", "qa_devsecops", "atlassian", "sre".',
564
+ inputSchema: {
565
+ type: 'object',
566
+ properties: {
567
+ profile: {
568
+ type: 'string',
569
+ enum: ['all', 'fast_dev', 'core', 'qa_devsecops', 'atlassian', 'sre'],
570
+ description: 'Perfil de ferramentas desejado'
571
+ }
572
+ },
573
+ required: ['profile']
574
+ }
575
+ },
576
+ {
577
+ name: 'agent_mine_domain_ideas',
578
+ description: 'Varredura inteligente de código-fonte de aplicação para identificar oportunidades reais de performance, resiliência, arquitetura e contratos, adicionando ao IDEAS.md.',
579
+ inputSchema: {
580
+ type: 'object',
581
+ properties: {
582
+ targetDir: {
583
+ type: 'string',
584
+ description: 'Diretório raiz do projeto para varredura (opcional, padrão: diretório atual).'
585
+ },
586
+ autoApply: {
587
+ type: 'boolean',
588
+ description: 'Se true, sincroniza as oportunidades descobertas diretamente em docs/IDEAS.md.'
589
+ },
590
+ dryRun: {
591
+ type: 'boolean',
592
+ description: 'Se true, apenas simula a sincronização sem alterar arquivos em disco.'
593
+ }
594
+ }
595
+ }
596
+ }
597
+ ];
598
+
599
+ const META_TOOLS = [
600
+ {
601
+ name: 'agent_governance',
602
+ description: 'Meta-ferramenta canônica de governança arquitetural, regras de engenharia, credenciais e validação da tríade (sub-ações: get_rule, validate_idea, validate_rule15, smart_onboarding, verify_triad_gate, check_credentials, configure_credentials, set_profile, eval_harness, mine_domain_ideas, recommend_architecture). Economiza tokens de schema ao consolidar o ciclo de governança.',
603
+ inputSchema: {
604
+ type: 'object',
605
+ properties: {
606
+ action: {
607
+ type: 'string',
608
+ description: 'Sub-ação de governança a executar',
609
+ enum: [
610
+ 'get_rule',
611
+ 'validate_idea',
612
+ 'validate_rule15',
613
+ 'smart_onboarding',
614
+ 'verify_triad_gate',
615
+ 'check_credentials',
616
+ 'configure_credentials',
617
+ 'set_profile',
618
+ 'eval_harness',
619
+ 'mine_domain_ideas',
620
+ 'recommend_architecture',
621
+ 'ground_knowledge'
622
+ ]
623
+ },
624
+ ruleNumber: { type: 'integer', description: 'Número do princípio canônico (1 a 10) ou regra legada (1 a 27)' },
625
+ ideaTitle: { type: 'string', description: 'Título da ideia' },
626
+ ideaDescription: { type: 'string', description: 'Descrição da proposta' },
627
+ projectStack: { type: 'string', description: 'Stack tecnológica do projeto real' },
628
+ projectDomain: { type: 'string', description: 'Propósito/domínio do projeto' },
629
+ targetDir: { type: 'string', description: 'Diretório alvo do onboarding ou mineração' },
630
+ mode: { type: 'string', description: 'Modo de onboarding (greenfield, brownfield)' },
631
+ dryRun: { type: 'boolean', description: 'Execução simulada sem escrita em disco' },
632
+ strict: { type: 'boolean', description: 'Modo estrito para verificação de tríade' },
633
+ bypassOffline: { type: 'boolean', description: 'Permitir prosseguir offline' },
634
+ credentials: { type: 'object', description: 'Objeto com credenciais a configurar' },
635
+ profile: { type: 'string', description: 'Perfil MCP a ativar' },
636
+ modelName: { type: 'string', description: 'Nome do modelo avaliado no eval harness' },
637
+ promptSent: { type: 'string', description: 'Prompt de instrução enviado à LLM' },
638
+ responseReceived: { type: 'string', description: 'Resposta bruta recebida da LLM' },
639
+ payload: { type: 'object', description: 'Payload genérico opcional com argumentos da sub-ação' }
640
+ },
641
+ required: ['action']
642
+ }
643
+ },
644
+ {
645
+ name: 'agent_audit',
646
+ description: 'Meta-ferramenta canônica de auditoria técnica de segurança, qualidade, contratos, conformidade e autocura autônoma (sub-ações: audit_code, sast_scan, audit_quality, audit_dependencies_sca, validate_api_contract, lint_git_hygiene, audit_a11y, remediate_code).',
647
+ inputSchema: {
648
+ type: 'object',
649
+ properties: {
650
+ action: {
651
+ type: 'string',
652
+ description: 'Sub-ação de auditoria a executar',
653
+ enum: [
654
+ 'audit_code',
655
+ 'sast_scan',
656
+ 'audit_quality',
657
+ 'audit_dependencies_sca',
658
+ 'validate_api_contract',
659
+ 'lint_git_hygiene',
660
+ 'audit_a11y',
661
+ 'remediate_code'
662
+ ]
663
+ },
664
+ targetFile: { type: 'string', description: 'Caminho do arquivo a ser remediado na sub-ação remediate_code' },
665
+ testCommand: { type: 'string', description: 'Comando de teste do host para validação na sub-ação remediate_code' },
666
+ format: { type: 'string', enum: ['json', 'sarif'], description: 'Formato de relatório para sast_scan e audit_dependencies_sca' },
667
+ codeDiff: { type: 'string', description: 'Diff ou código a ser auditado' },
668
+ filePath: { type: 'string', description: 'Caminho do arquivo a ser auditado' },
669
+ codeContent: { type: 'string', description: 'Conteúdo textual do código a analisar' },
670
+ packageJsonPath: { type: 'string', description: 'Caminho do package.json para SCA' },
671
+ dependencies: { type: 'object', description: 'Dicionário de dependências para SCA' },
672
+ specPath: { type: 'string', description: 'Caminho do manifesto OpenAPI/Swagger' },
673
+ specContent: { type: 'string', description: 'Conteúdo da especificação OpenAPI' },
674
+ branchName: { type: 'string', description: 'Nome da branch para validação de higiene git' },
675
+ commitMessage: { type: 'string', description: 'Mensagem de commit para validação' },
676
+ htmlContent: { type: 'string', description: 'Markup HTML ou JSX para auditoria a11y' },
677
+ context: { type: 'string', description: 'Contexto técnico adicional' },
678
+ payload: { type: 'object', description: 'Payload genérico opcional com argumentos da sub-ação' }
679
+ },
680
+ required: ['action']
681
+ }
682
+ },
683
+ {
684
+ name: 'agent_review',
685
+ description: 'Meta-ferramenta canônica de revisão adversarial e governança de Pull Requests com cálculo de Blast Radius (sub-ações: review_pr, qa_gate).',
686
+ inputSchema: {
687
+ type: 'object',
688
+ properties: {
689
+ action: {
690
+ type: 'string',
691
+ description: 'Sub-ação de revisão (padrão: review_pr)',
692
+ enum: ['review_pr', 'qa_gate']
693
+ },
694
+ prNumber: { type: 'integer', description: 'Número do Pull Request no GitHub' },
695
+ targetRepo: { type: 'string', description: 'Repositório GitHub (ex: owner/repo)' },
696
+ token: { type: 'string', description: 'Token de autenticação do GitHub' },
697
+ codeDiff: { type: 'string', description: 'Diff estático do PR quando avaliado offline' },
698
+ context: { type: 'string', description: 'Contexto técnico do PR ou ticket' },
699
+ payload: { type: 'object', description: 'Payload genérico opcional com argumentos da sub-ação' }
700
+ },
701
+ required: ['action']
702
+ }
703
+ },
704
+ {
705
+ name: 'agent_pipeline',
706
+ description: 'Meta-ferramenta canônica de automação de esteiras, ciclo de vida Full-Dev, integrações Atlassian/Git e scaffolding (sub-ações: sync_atlassian, standardize_kanban, full_dev_pipeline, full_dev_status, scaffold_feature, extract_code_skeleton, export_universal_bundle, compress_context, generate_ide_plugins, bootstrap_environment, generate_magic_prompt).',
707
+ inputSchema: {
708
+ type: 'object',
709
+ properties: {
710
+ action: {
711
+ type: 'string',
712
+ description: 'Sub-ação da pipeline a executar',
713
+ enum: [
714
+ 'sync_atlassian',
715
+ 'standardize_kanban',
716
+ 'full_dev_pipeline',
717
+ 'full_dev_status',
718
+ 'scaffold_feature',
719
+ 'extract_code_skeleton',
720
+ 'export_universal_bundle',
721
+ 'compress_context',
722
+ 'generate_ide_plugins',
723
+ 'bootstrap_environment',
724
+ 'generate_magic_prompt'
725
+ ]
726
+ },
727
+ issueKey: { type: 'string', description: 'Chave da issue Jira (ex: AGDEV-23)' },
728
+ url: { type: 'string', description: 'URL do commit ou PR para vinculação remota' },
729
+ title: { type: 'string', description: 'Título do link ou da funcionalidade' },
730
+ type: { type: 'string', description: 'Tipo do artefato (commit, pr, adr)' },
731
+ projectKey: { type: 'string', description: 'Chave do projeto Jira' },
732
+ featureName: { type: 'string', description: 'Nome da feature para scaffolding' },
733
+ platform: { type: 'string', description: 'Plataforma alvo para exportação (cursor, ollama, etc.)' },
734
+ targetDir: { type: 'string', description: 'Diretório raiz do projeto' },
735
+ maxTokens: { type: 'integer', description: 'Orçamento máximo de tokens para compressão' },
736
+ dryRun: { type: 'boolean', description: 'Modo de simulação sem alteração em disco' },
737
+ payload: { type: 'object', description: 'Payload genérico opcional com argumentos da sub-ação' }
738
+ },
739
+ required: ['action']
740
+ }
741
+ },
742
+ {
743
+ name: 'agent_telemetry',
744
+ description: 'Meta-ferramenta canônica de observabilidade, telemetria Prometheus/OTLP, circuit breaker e resiliência SRE (sub-ações: sre_telemetry, sre_remediate, otel_trace, perf_benchmark, circuit_breaker, orchestrate_event, inspector_info).',
745
+ inputSchema: {
746
+ type: 'object',
747
+ properties: {
748
+ action: {
749
+ type: 'string',
750
+ description: 'Sub-ação de telemetria a executar',
751
+ enum: [
752
+ 'sre_telemetry',
753
+ 'sre_remediate',
754
+ 'otel_trace',
755
+ 'perf_benchmark',
756
+ 'circuit_breaker',
757
+ 'orchestrate_event',
758
+ 'inspector_info'
759
+ ]
760
+ },
761
+ operation: { type: 'string', description: 'Operação de telemetria ou benchmark' },
762
+ serviceName: { type: 'string', description: 'Nome do serviço rastreado' },
763
+ traceId: { type: 'string', description: 'ID de rastreio W3C' },
764
+ scenario: { type: 'string', description: 'Cenário de teste de benchmark' },
765
+ iterations: { type: 'integer', description: 'Número de iterações do benchmark' },
766
+ state: { type: 'string', description: 'Estado do circuit breaker ou filtro' },
767
+ eventName: { type: 'string', description: 'Nome do evento no barramento' },
768
+ eventPayload: { type: 'object', description: 'Dados do evento a ser despachado' },
769
+ simulate: { type: 'string', description: 'Simulação de falha ou failover' },
770
+ payload: { type: 'object', description: 'Payload genérico opcional com argumentos da sub-ação' }
771
+ },
772
+ required: ['action']
773
+ }
774
+ }
775
+ ];
776
+
777
+ const ALL_TOOLS = Object.freeze([...TOOLS, ...META_TOOLS]);
778
+
779
+ const CONSOLIDATED_TOOLS = Object.freeze([
780
+ 'agent_governance',
781
+ 'agent_audit',
782
+ 'agent_review',
783
+ 'agent_pipeline',
784
+ 'agent_telemetry'
785
+ ]);
786
+
787
+ const TOOL_PROFILES = Object.freeze({
788
+ all: TOOLS.map(t => t.name),
789
+ consolidated: CONSOLIDATED_TOOLS,
790
+ lean: CONSOLIDATED_TOOLS,
791
+ fast_dev: Object.freeze([
792
+ 'agent_recommend_architecture',
793
+ 'agent_scaffold_feature',
794
+ 'agent_audit_code',
795
+ 'agent_verify_triad_gate',
796
+ 'agent_set_mcp_profile'
797
+ ]),
798
+ core: Object.freeze([
799
+ 'agent_get_rule',
800
+ 'agent_recommend_architecture',
801
+ 'agent_validate_idea',
802
+ 'agent_orchestrate_event',
803
+ 'agent_check_credentials',
804
+ 'agent_bootstrap_environment',
805
+ 'agent_compress_context',
806
+ 'agent_full_dev_status',
807
+ 'agent_set_mcp_profile',
808
+ 'agent_smart_onboarding',
809
+ 'agent_verify_triad_gate',
810
+ 'agent_extract_code_skeleton',
811
+ 'agent_scaffold_feature'
812
+ ]),
813
+ qa_devsecops: Object.freeze([
814
+ 'agent_audit_code',
815
+ 'agent_review_pr',
816
+ 'agent_sast_scan',
817
+ 'agent_audit_quality',
818
+ 'agent_audit_dependencies_sca',
819
+ 'agent_validate_api_contract',
820
+ 'agent_lint_git_hygiene',
821
+ 'agent_audit_a11y',
822
+ 'agent_remediate_code',
823
+ 'agent_set_mcp_profile'
824
+ ]),
825
+ atlassian: Object.freeze([
826
+ 'agent_sync_atlassian',
827
+ 'agent_standardize_kanban',
828
+ 'agent_full_dev_pipeline',
829
+ 'agent_validate_rule15',
830
+ 'agent_configure_credentials',
831
+ 'agent_check_credentials',
832
+ 'agent_set_mcp_profile'
833
+ ]),
834
+ sre: Object.freeze([
835
+ 'agent_sre_telemetry',
836
+ 'agent_sre_remediate',
837
+ 'agent_otel_trace',
838
+ 'agent_perf_benchmark',
839
+ 'agent_circuit_breaker',
840
+ 'agent_set_mcp_profile'
841
+ ]),
842
+ infra: Object.freeze([
843
+ 'agent_otel_trace',
844
+ 'agent_perf_benchmark',
845
+ 'agent_circuit_breaker',
846
+ 'agent_inspector_info',
847
+ 'agent_check_credentials',
848
+ 'agent_set_mcp_profile'
849
+ ])
850
+ });
851
+
852
+ /**
853
+ * Classe Canônica ToolsRegistry — Catálogo, Validação de Schemas e Gestor de Perfis MCP
854
+ */
855
+ class ToolsRegistry {
856
+ constructor(initialProfile = null) {
857
+ this.activeProfile = initialProfile || process.env.MCP_PROFILE || 'consolidated';
858
+ this.customTools = new Map();
859
+ this.customProfiles = new Map();
860
+ }
861
+
862
+ static get TOOLS() {
863
+ return TOOLS;
864
+ }
865
+
866
+ static get META_TOOLS() {
867
+ return META_TOOLS;
868
+ }
869
+
870
+ static get ALL_TOOLS() {
871
+ return ALL_TOOLS;
872
+ }
873
+
874
+ static get TOOL_PROFILES() {
875
+ return TOOL_PROFILES;
876
+ }
877
+
878
+ static get CONSOLIDATED_TOOLS() {
879
+ return CONSOLIDATED_TOOLS;
880
+ }
881
+
882
+ getActiveProfile() {
883
+ return this.activeProfile;
884
+ }
885
+
886
+ getActiveTools() {
887
+ const profileName = String(this.activeProfile).toLowerCase();
888
+
889
+ // 1. Perfis customizados registrados dinamicamente
890
+ if (this.customProfiles.has(profileName)) {
891
+ const allowed = this.customProfiles.get(profileName);
892
+ return this.getAllTools().filter(t => allowed.includes(t.name));
893
+ }
894
+
895
+ // 2. Proteção contra prototype pollution
896
+ if (!Object.prototype.hasOwnProperty.call(TOOL_PROFILES, profileName)) {
897
+ return TOOLS;
898
+ }
899
+
900
+ const allowed = TOOL_PROFILES[profileName];
901
+ return this.getAllTools().filter(t => allowed.includes(t.name));
902
+ }
903
+
904
+ getAllTools() {
905
+ if (this.customTools.size === 0) {
906
+ return ALL_TOOLS;
907
+ }
908
+ return [...ALL_TOOLS, ...Array.from(this.customTools.values())];
909
+ }
910
+
911
+ setMcpProfile(profile) {
912
+ if (typeof profile !== 'string' || !profile.trim()) {
913
+ return {
914
+ success: false,
915
+ error: `Perfil inválido: ${profile}. Opções válidas: ${this.listAvailableProfiles().join(', ')}`
916
+ };
917
+ }
918
+
919
+ const target = profile.trim().toLowerCase();
920
+ const hasBuiltin = Object.prototype.hasOwnProperty.call(TOOL_PROFILES, target);
921
+ const hasCustom = this.customProfiles.has(target);
922
+
923
+ if (hasBuiltin || hasCustom) {
924
+ this.activeProfile = target;
925
+ return {
926
+ success: true,
927
+ profile: target,
928
+ activeToolsCount: this.getActiveTools().length
929
+ };
930
+ }
931
+
932
+ return {
933
+ success: false,
934
+ error: `Perfil inválido: ${profile}. Opções válidas: ${this.listAvailableProfiles().join(', ')}`
935
+ };
936
+ }
937
+
938
+ listAvailableProfiles() {
939
+ return [...Object.keys(TOOL_PROFILES), ...Array.from(this.customProfiles.keys())];
940
+ }
941
+
942
+ registerTool(toolDefinition, { profile = null } = {}) {
943
+ if (!toolDefinition || typeof toolDefinition !== 'object') {
944
+ throw new Error('Definição da ferramenta deve ser um objeto válido');
945
+ }
946
+ if (!toolDefinition.name || typeof toolDefinition.name !== 'string') {
947
+ throw new Error('A ferramenta deve conter a propriedade "name"');
948
+ }
949
+ this.customTools.set(toolDefinition.name, Object.freeze({ ...toolDefinition }));
950
+ if (profile) {
951
+ const target = String(profile).toLowerCase();
952
+ const currentList = this.customProfiles.get(target) || [];
953
+ if (!currentList.includes(toolDefinition.name)) {
954
+ this.customProfiles.set(target, [...currentList, toolDefinition.name]);
955
+ }
956
+ }
957
+ }
958
+
959
+ registerProfile(profileName, toolNames) {
960
+ if (!profileName || typeof profileName !== 'string') {
961
+ throw new Error('Nome do perfil deve ser uma string válida');
962
+ }
963
+ if (!Array.isArray(toolNames)) {
964
+ throw new Error('A lista de ferramentas do perfil deve ser um array');
965
+ }
966
+ this.customProfiles.set(profileName.toLowerCase(), [...toolNames]);
967
+ }
968
+
969
+ getTool(name) {
970
+ if (!name || typeof name !== 'string') return null;
971
+ if (this.customTools.has(name)) {
972
+ return this.customTools.get(name);
973
+ }
974
+ return ALL_TOOLS.find(t => t.name === name) || null;
975
+ }
976
+
977
+ hasTool(name) {
978
+ return this.getTool(name) !== null;
979
+ }
980
+
981
+ auditToSarif() {
982
+ const findings = [];
983
+ const allTools = this.getAllTools();
984
+
985
+ for (const tool of allTools) {
986
+ if (!tool.name || typeof tool.name !== 'string') {
987
+ findings.push({
988
+ ruleId: 'RULE-TOOL-001',
989
+ severity: 'CRITICAL',
990
+ filename: 'scripts/mcp/tools_registry.js',
991
+ line: 1,
992
+ column: 1,
993
+ snippet: JSON.stringify(tool).slice(0, 80),
994
+ message: 'Ferramenta MCP sem propriedade "name" obrigatória.',
995
+ remediation: 'Definir nome canônico da ferramenta conforme convenção MCP.'
996
+ });
997
+ }
998
+ if (!tool.inputSchema || typeof tool.inputSchema !== 'object' || tool.inputSchema.type !== 'object') {
999
+ findings.push({
1000
+ ruleId: 'RULE-TOOL-002',
1001
+ severity: 'HIGH',
1002
+ filename: 'scripts/mcp/tools_registry.js',
1003
+ line: 1,
1004
+ column: 1,
1005
+ snippet: `tool: ${tool.name}`,
1006
+ message: `Ferramenta MCP '${tool.name}' possui inputSchema inválido (deve ser type: 'object').`,
1007
+ remediation: 'Corrigir inputSchema para conformidade com JSON Schema.'
1008
+ });
1009
+ }
1010
+ }
1011
+
1012
+ // Validação de integridade dos perfis
1013
+ for (const [pName, pTools] of Object.entries(TOOL_PROFILES)) {
1014
+ for (const tName of pTools) {
1015
+ if (!allTools.some(t => t.name === tName)) {
1016
+ findings.push({
1017
+ ruleId: 'RULE-REG-001',
1018
+ severity: 'HIGH',
1019
+ filename: 'scripts/mcp/tools_registry.js',
1020
+ line: 1,
1021
+ column: 1,
1022
+ snippet: `profile: ${pName} -> ${tName}`,
1023
+ message: `Perfil '${pName}' referencia ferramenta '${tName}' inexistente em ALL_TOOLS.`,
1024
+ remediation: 'Remover a referência órfã ou registrar a ferramenta no catálogo.'
1025
+ });
1026
+ }
1027
+ }
1028
+ }
1029
+
1030
+ return createSarifReport({
1031
+ toolName: 'agent-master-tools-registry',
1032
+ toolVersion: '5.1.0',
1033
+ findings,
1034
+ properties: {
1035
+ activeProfile: this.activeProfile,
1036
+ totalTools: allTools.length,
1037
+ canonicalToolsCount: TOOLS.length,
1038
+ metaToolsCount: META_TOOLS.length,
1039
+ profilesCount: Object.keys(TOOL_PROFILES).length
1040
+ }
1041
+ });
1042
+ }
1043
+
1044
+ formatReport() {
1045
+ const activeTools = this.getActiveTools();
1046
+ const profiles = this.listAvailableProfiles();
1047
+
1048
+ const lines = [
1049
+ '# Relatório Executivo: Catálogo de Ferramentas MCP (tools_registry.js)',
1050
+ '',
1051
+ `- **Perfil Ativo:** \`${this.activeProfile}\``,
1052
+ `- **Ferramentas Ativas no Perfil:** ${activeTools.length}`,
1053
+ `- **Total de Ferramentas Canônicas:** ${TOOLS.length}`,
1054
+ `- **Total de Meta-Ferramentas:** ${META_TOOLS.length}`,
1055
+ `- **Perfis Disponíveis:** ${profiles.join(', ')}`,
1056
+ '',
1057
+ '| Perfil | Quantidade de Ferramentas | Descrição |',
1058
+ '|---|---|---|',
1059
+ `| \`all\` | ${TOOL_PROFILES.all.length} | Todas as ferramentas individuais |`,
1060
+ `| \`consolidated\` | ${TOOL_PROFILES.consolidated.length} | 5 Meta-Ferramentas para economia de tokens |`,
1061
+ `| \`lean\` | ${TOOL_PROFILES.lean.length} | Modo enxuto idêntico a consolidated |`,
1062
+ `| \`fast_dev\` | ${TOOL_PROFILES.fast_dev.length} | Fast-path Dev (arquitetura, scaffold, audit, triad) |`,
1063
+ `| \`core\` | ${TOOL_PROFILES.core.length} | Ferramentas essenciais de arquitetura e governança |`,
1064
+ `| \`qa_devsecops\` | ${TOOL_PROFILES.qa_devsecops.length} | Foco em QA, SAST, SCA e Git Hygiene |`,
1065
+ `| \`atlassian\` | ${TOOL_PROFILES.atlassian.length} | Tríade Jira e Confluence |`,
1066
+ `| \`sre\` | ${TOOL_PROFILES.sre.length} | Telemetria, OTLP e Circuit Breaker |`,
1067
+ `| \`infra\` | ${TOOL_PROFILES.infra.length} | Infraestrutura e networking |`,
1068
+ ''
1069
+ ];
1070
+
1071
+ return lines.join('\n');
1072
+ }
1073
+
1074
+ static getActiveTools() {
1075
+ return defaultToolsRegistryInstance.getActiveTools();
1076
+ }
1077
+
1078
+ static setMcpProfile(profile) {
1079
+ return defaultToolsRegistryInstance.setMcpProfile(profile);
1080
+ }
1081
+
1082
+ static getActiveProfile() {
1083
+ return defaultToolsRegistryInstance.getActiveProfile();
1084
+ }
1085
+
1086
+ static auditToSarif() {
1087
+ return defaultToolsRegistryInstance.auditToSarif();
1088
+ }
1089
+
1090
+ static formatReport() {
1091
+ return defaultToolsRegistryInstance.formatReport();
1092
+ }
1093
+ }
1094
+
1095
+ // Instância singleton padrão para retrocompatibilidade
1096
+ const defaultToolsRegistryInstance = new ToolsRegistry();
1097
+
1098
+ function getActiveTools() {
1099
+ return defaultToolsRegistryInstance.getActiveTools();
1100
+ }
1101
+
1102
+ function setMcpProfile(profile) {
1103
+ return defaultToolsRegistryInstance.setMcpProfile(profile);
1104
+ }
1105
+
1106
+ function getActiveProfile() {
1107
+ return defaultToolsRegistryInstance.getActiveProfile();
1108
+ }
1109
+
1110
+ module.exports = {
1111
+ ToolsRegistry,
1112
+ defaultToolsRegistryInstance,
1113
+ TOOLS,
1114
+ META_TOOLS,
1115
+ ALL_TOOLS,
1116
+ TOOL_PROFILES,
1117
+ CONSOLIDATED_TOOLS,
1118
+ getActiveTools,
1119
+ setMcpProfile,
1120
+ getActiveProfile,
1121
+ auditToSarif: () => defaultToolsRegistryInstance.auditToSarif(),
1122
+ formatReport: () => defaultToolsRegistryInstance.formatReport()
1123
+ };