@shiftleftpt/sbd-toe-mcp 0.20.0 → 0.21.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.
Files changed (53) hide show
  1. package/README.md +2 -2
  2. package/dist/index.js +107 -266
  3. package/dist/index.js.map +1 -1
  4. package/dist/resources/sbd-toe-resources.js +1 -1
  5. package/dist/resources/sbd-toe-resources.js.map +1 -1
  6. package/dist/serving/adjacency.d.ts +68 -0
  7. package/dist/serving/adjacency.js +127 -0
  8. package/dist/serving/adjacency.js.map +1 -0
  9. package/dist/serving/affordances.js +4 -5
  10. package/dist/serving/affordances.js.map +1 -1
  11. package/dist/serving/agent-guide.js +5 -3
  12. package/dist/serving/agent-guide.js.map +1 -1
  13. package/dist/serving/behaviour-notes.d.ts +2 -2
  14. package/dist/serving/behaviour-notes.js +2 -8
  15. package/dist/serving/behaviour-notes.js.map +1 -1
  16. package/dist/serving/notes.d.ts +42 -0
  17. package/dist/serving/notes.js +44 -0
  18. package/dist/serving/notes.js.map +1 -0
  19. package/dist/serving/payload-ceilings.d.ts +73 -11
  20. package/dist/serving/payload-ceilings.js +85 -24
  21. package/dist/serving/payload-ceilings.js.map +1 -1
  22. package/dist/serving/response-shaping.d.ts +10 -0
  23. package/dist/serving/response-shaping.js +26 -0
  24. package/dist/serving/response-shaping.js.map +1 -1
  25. package/dist/serving/server-surface.d.ts +10 -0
  26. package/dist/serving/server-surface.js +14 -2
  27. package/dist/serving/server-surface.js.map +1 -1
  28. package/dist/serving/surface-history.d.ts +118 -0
  29. package/dist/serving/surface-history.js +119 -0
  30. package/dist/serving/surface-history.js.map +1 -0
  31. package/dist/tools/assess-implementation.d.ts +9 -0
  32. package/dist/tools/assess-implementation.js +7 -1
  33. package/dist/tools/assess-implementation.js.map +1 -1
  34. package/dist/tools/get-guide-by-role.d.ts +40 -0
  35. package/dist/tools/get-guide-by-role.js +158 -4
  36. package/dist/tools/get-guide-by-role.js.map +1 -1
  37. package/dist/tools/get-macro-processes.js +18 -8
  38. package/dist/tools/get-macro-processes.js.map +1 -1
  39. package/dist/tools/get-threat-landscape.js +11 -5
  40. package/dist/tools/get-threat-landscape.js.map +1 -1
  41. package/dist/tools/ontology-loader.d.ts +7 -0
  42. package/dist/tools/ontology-loader.js +2 -0
  43. package/dist/tools/ontology-loader.js.map +1 -1
  44. package/dist/tools/prepare-codegen-context.d.ts +373 -276
  45. package/dist/tools/prepare-codegen-context.js +523 -532
  46. package/dist/tools/prepare-codegen-context.js.map +1 -1
  47. package/dist/tools/resolve-entities.js +8 -4
  48. package/dist/tools/resolve-entities.js.map +1 -1
  49. package/dist/tools/select-requirements.d.ts +2 -1
  50. package/dist/tools/select-requirements.js +23 -8
  51. package/dist/tools/select-requirements.js.map +1 -1
  52. package/package.json +1 -1
  53. package/prompts/sbd-toe-grounded-codegen.md +11 -11
package/dist/index.js CHANGED
@@ -39,6 +39,9 @@ const CONCERNS_VOCABULARY_NOTE = `Conjunto FECHADO de ${DECLARED_CONCERNS.length
39
39
  import { buildCodegenInstructionsResourceContent, handlePrepareCodegenContext } from "./tools/prepare-codegen-context.js";
40
40
  import { buildChapterApplicabilityJson, buildGroundedCodegenPrompt, buildSetupAgentPrompt, readGroundedCodegenGuide } from "./resources/sbd-toe-resources.js";
41
41
  import { RESOURCE_CATALOG, PROMPT_CATALOG } from "./serving/server-surface.js";
42
+ import { buildNotesResource } from "./serving/notes.js";
43
+ import { SURFACE_HISTORY } from "./serving/surface-history.js";
44
+ import { withDeclaredSize } from "./serving/response-shaping.js";
42
45
  import { loadMetrics } from "./tools/assess-implementation.js";
43
46
  import { getOntologyData } from "./tools/ontology-loader.js";
44
47
  import { buildAgentGuide } from "./serving/agent-guide.js";
@@ -48,7 +51,6 @@ import { handleGetPlaybook } from "./tools/get-playbook.js";
48
51
  import { handleGetChapterCapability } from "./tools/get-chapter-capability.js";
49
52
  import { handleExplainTopic } from "./tools/explain-topic.js";
50
53
  import { handleGetMacroProcesses } from "./tools/get-macro-processes.js";
51
- import { threatDomainConcerns } from "./tools/get-threat-landscape.js";
52
54
  import { reconcileNextWithBands } from "./serving/next-band-reconciliation.js";
53
55
  const PROTOCOL_VERSION = "2025-03-26";
54
56
  let cachedPackageMetadata;
@@ -100,6 +102,19 @@ async function materializeResource(uri) {
100
102
  const data = buildChapterApplicabilityJson(riskLevel);
101
103
  return { mimeType: "application/json", text: JSON.stringify(data, null, 2) };
102
104
  }
105
+ // 0.21 §6-c — notas por referência: índice e nota individual.
106
+ if (uri === "sbd://toe/notes") {
107
+ return { mimeType: "application/json", text: JSON.stringify(buildNotesResource(), null, 2) };
108
+ }
109
+ const notesMatch = /^\/\/toe\/notes\/([^/]+)$/.exec(path);
110
+ if (notesMatch !== null) {
111
+ try {
112
+ return { mimeType: "application/json", text: JSON.stringify(buildNotesResource(decodeURIComponent(notesMatch[1] ?? "")), null, 2) };
113
+ }
114
+ catch (error) {
115
+ throw new ResourceReadError(-32602, error instanceof Error ? error.message : "Unknown note id.");
116
+ }
117
+ }
103
118
  const codegenInstructionsMatch = /^\/\/toe\/codegen-instructions\/([^/]+)$/.exec(path);
104
119
  if (codegenInstructionsMatch !== null) {
105
120
  const mode = codegenInstructionsMatch[1] ?? "";
@@ -174,6 +189,9 @@ async function materializeResource(uri) {
174
189
  // 0.20.0-beta.21 — a SEMÂNTICA de serviço mudou nesta linha, não só a versão:
175
190
  // para um produto que vende reprodutibilidade, mudar isto em silêncio seria a
176
191
  // pior violação da própria promessa.
192
+ // 0.21 §6-d — o CHANGELOG saiu das descrições das tools (≤600 chars, uma língua): o que
193
+ // lá estava vive aqui, verbatim, para que nada se perca — só muda de sítio.
194
+ surface_history: SURFACE_HISTORY,
177
195
  serving_contract: {
178
196
  version: "v1.18-beta",
179
197
  /*
@@ -348,6 +366,19 @@ class McpRuntime {
348
366
  message: String(error)
349
367
  };
350
368
  }
369
+ /**
370
+ * 0.21 §6 — `size_estimate` em TODAS as tools de resultado JSON (o prepare já o declara com
371
+ * envelope; aqui não se toca). Duas passagens, para o número anunciado ser o do payload que
372
+ * o cliente recebe. Resultados de texto (search/answer/inspect) não têm onde o carregar.
373
+ */
374
+ /**
375
+ * 0.21 §6 — `size_estimate` em TODAS as tools de resultado JSON, medido sobre o payload
376
+ * entregue (withDeclaredSize é a única régua — o guia anuncia tamanhos com a mesma).
377
+ * Resultados de texto (search/answer/inspect) não têm onde o carregar.
378
+ */
379
+ toolText(result) {
380
+ return JSON.stringify(withDeclaredSize(result));
381
+ }
351
382
  sendResponse(id, result) {
352
383
  /*
353
384
  * 0.20.0-beta.39 — a reconciliação do `next` com as bandas da própria resposta corre
@@ -614,7 +645,7 @@ class McpRuntime {
614
645
  {
615
646
  name: "search_sbd_toe_manual",
616
647
  title: "Search SbD-ToE Manual",
617
- description: "NÃO-NORMATIVO — leitura e orientação, NUNCA caminho para um conjunto de requisitos. Pesquisa semântica sobre os chunks publicados do manual: serve para LER e localizar passagens (e para tu, LLM, formares a tua leitura), não para decidir âmbito. O conjunto de requisitos vem de select_sbd_toe_requirements com activadores DECLARADOS (vocabulário em sbd://toe/activation-vocabulary) — o que aqui sai não selecciona nada e não deve ser citado como se fosse selecção.",
648
+ description: "NON-NORMATIVE reading aid — never a path to a requirement set. Semantic search over the published manual chunks, to read and locate passages and form your own reading. The requirement set for a task comes from select_sbd_toe_requirements with DECLARED activators (vocabulary: sbd://toe/activation-vocabulary); nothing returned here selects anything and must not be cited as a selection.",
618
649
  inputSchema: {
619
650
  type: "object",
620
651
  properties: {
@@ -647,12 +678,7 @@ class McpRuntime {
647
678
  {
648
679
  name: "answer_sbd_toe_manual",
649
680
  title: "Answer SbD-ToE Manual",
650
- description: "SERVE CONTEXTO PARA O TEU MODELO RESPONDER — não responde: a resposta é do modelo do cliente, via " +
651
- "sampling, e o juízo é de quem pergunta. Recupera contexto do Manual e pede a resposta final ao " +
652
- "modelo do cliente via MCP sampling. " +
653
- "Requires sampling support from the MCP client. " +
654
- "Without sampling, falls back to formatted retrieval output (same as search_sbd_toe_manual). " +
655
- "Prefer search_sbd_toe_manual for clients without sampling support.",
681
+ description: "DOES NOT ANSWER — serves manual context for the CLIENT model to answer via MCP sampling; the judgement stays with the asker. Requires sampling support; without it, falls back to formatted retrieval output (same as search_sbd_toe_manual), the better choice on clients without sampling.",
656
682
  inputSchema: {
657
683
  type: "object",
658
684
  properties: {
@@ -685,7 +711,7 @@ class McpRuntime {
685
711
  {
686
712
  name: "inspect_sbd_toe_retrieval",
687
713
  title: "Inspect SbD-ToE Retrieval",
688
- description: "Inspects retrieval, context selection and final prompt without requesting an answer from the client model.",
714
+ description: "Inspects retrieval, context selection and the final prompt without requesting an answer from the client model.",
689
715
  inputSchema: {
690
716
  type: "object",
691
717
  properties: {
@@ -714,7 +740,7 @@ class McpRuntime {
714
740
  {
715
741
  name: "list_sbd_toe_chapters",
716
742
  title: "List SbD-ToE Chapters",
717
- description: "Lists SbD-ToE manual chapters with id, canonical title, a clean readableTitle, graduated applicability (all levels true) and derived demand_by_level (0.14.0 — the binary minLevel theory is retired).",
743
+ description: "Lists the manual chapters: id, canonical title, clean readableTitle, graduated applicability (every chapter applies at every level) and derived demand_by_level.",
718
744
  inputSchema: {
719
745
  type: "object",
720
746
  properties: {
@@ -749,7 +775,7 @@ class McpRuntime {
749
775
  {
750
776
  name: "get_sbd_toe_chapter_brief",
751
777
  title: "Get SbD-ToE Chapter Brief",
752
- description: "Returns an operational summary of a chapter: title, objective, role, phases, artefacts (fields are present when the substrate carries them).",
778
+ description: "Operational summary of a chapter: title, objective, role, phases, artefacts (fields are present when the substrate carries them).",
753
779
  inputSchema: {
754
780
  type: "object",
755
781
  properties: {
@@ -763,12 +789,7 @@ class McpRuntime {
763
789
  {
764
790
  name: "plan_sbd_toe_repo_governance",
765
791
  title: "List SbD-ToE Manual Artefacts",
766
- description: "PROJECÇÃO DOS ARTEFACTOS PUBLICADOS — não governa o teu repositório: serve o que o Manual identifica, " +
767
- "por capítulo, para tu decidires o que instalas. Lista de artefactos/documentos do SbD-ToE, " +
768
- "grouped by chapter, with risk level applicability. " +
769
- "Optionally filter by riskLevel (L1/L2/L3). " +
770
- "All data comes from the manual indices — nothing is invented. " +
771
- "The manual does not provide templates; ask the LLM to generate one if needed.",
792
+ description: "PROJECTION of the published artefacts — it does not govern your repository. Lists the artefacts/documents the manual identifies, grouped by chapter, with risk-level applicability (optional riskLevel filter L1/L2/L3), so you decide what to install. All data from the manual indices; nothing invented. The manual provides no templates — ask your model to draft one if needed.",
772
793
  inputSchema: {
773
794
  type: "object",
774
795
  properties: {
@@ -796,15 +817,7 @@ class McpRuntime {
796
817
  {
797
818
  name: "generate_sbd_toe_skill",
798
819
  title: "Generate SbD-ToE Skill Content",
799
- description: "GERA A PARTIR DO PUBLICADO, SEM VALIDAR O TEU AMBIENTE — não instala, não configura e não verifica " +
800
- "nada do teu lado: devolve o texto para TU instalares onde souberes. " +
801
- "Use this tool when asked to 'create a skill for SbD-ToE', 'set up instructions', " +
802
- "'configure this client/agent to use SbD-ToE', 'configure yourself for role X', or 'integrate SbD-ToE'. " +
803
- "Without arguments returns the canonical skill content from sbd://toe/agent-guide. " +
804
- "With role= returns a role-specialised skill (format=skill) or an installable sub-agent " +
805
- "definition (format=subagent) grounded on the role's manual slice — flavour=harnessed grants " +
806
- "the mcp__sbd-toe__* tools (queries live); flavour=skilled embeds the frozen slice with no MCP tools. " +
807
- "Save the returned content to suggested_path (or the client equivalent).",
820
+ description: "Generates from the published guide without validating your environment: it installs, configures and verifies nothing — it returns text for YOU to install. Use for 'create a skill for SbD-ToE', 'set up instructions', 'configure this agent for role X'. No arguments: the canonical skill (sbd://toe/agent-guide). With role: a role-specialised skill (format=skill) or an installable sub-agent (format=subagent); flavour=harnessed grants the mcp__sbd-toe__* tools, flavour=skilled embeds the frozen slice. Save the content to suggested_path.",
808
821
  inputSchema: {
809
822
  type: "object",
810
823
  properties: {
@@ -890,10 +903,7 @@ class McpRuntime {
890
903
  {
891
904
  name: "get_sbd_toe_chapter_implementation_checklist",
892
905
  title: "Get SbD-ToE Chapter Implementation Checklist",
893
- description: "The canon/20 'how to implement chapter NN' checklist — retrieval-grounded prose from the " +
894
- "implementation profile (the operational 'Aplicação no Ciclo de Vida' guidance). Use to answer " +
895
- "'how do I implement chapter NN / this area?'. Coverage-preserving; cites chunk ids; nothing invented. " +
896
- "For the level-sharp structured Definition-of-Done use get_guide_by_role(include_detail=true).",
906
+ description: "The 'how to implement chapter NN' checklist: retrieval-grounded prose from the implementation profile (the operational lifecycle guidance). Coverage-preserving, cites chunk ids, nothing invented. For the level-sharp structured Definition-of-Done use get_guide_by_role(include_detail=true).",
897
907
  inputSchema: {
898
908
  type: "object",
899
909
  properties: {
@@ -910,9 +920,7 @@ class McpRuntime {
910
920
  {
911
921
  name: "get_sbd_toe_operating_model",
912
922
  title: "Get SbD-ToE Operating Model",
913
- description: "The operating model — RACI, decision-rights, governance cadences, org-model — from the rollout " +
914
- "playbook (implementation profile). Retrieval-grounded prose; coverage-preserving; nothing invented. " +
915
- "Use to answer 'who is responsible / how do we govern the SbD rollout?'.",
923
+ description: "The operating model — RACI, decision rights, governance cadences, org model — from the rollout playbook (implementation profile). Retrieval-grounded prose; coverage-preserving; nothing invented. Answers 'who is responsible / how do we govern the SbD rollout?'.",
916
924
  inputSchema: {
917
925
  type: "object",
918
926
  properties: {
@@ -928,10 +936,7 @@ class McpRuntime {
928
936
  {
929
937
  name: "get_sbd_toe_verification_matrix",
930
938
  title: "Get SbD-ToE Verification Matrix",
931
- description: "The EXPECTED side of verification: per requirement/control at a risk level, the validation method " +
932
- "+ expected evidence + EvidencePattern reference (the published patterns — totals declared per response). The deterministic " +
933
- "complement of the auditor's expectation and the test-plan. Cited per row; coverage-preserving — " +
934
- "declares the requirements with no EvidencePattern. Use to answer 'how do I prove chapter/level X?' — or 'how do I prove THESE requirements?' via requirement_ids (o fecho requisito→prova a partir do select).",
939
+ description: "The EXPECTED side of verification: per requirement/control at a risk level, the validation method, expected evidence and EvidencePattern reference from the published patterns (totals declared). Cited per row; coverage-preserving — declares requirements with no pattern. Answers 'how do I prove chapter/level X?' or, with requirement_ids (max 50 per call), 'how do I prove THESE requirements?' — the requirement→proof closure from a selection.",
935
940
  inputSchema: {
936
941
  type: "object",
937
942
  properties: {
@@ -948,12 +953,7 @@ class McpRuntime {
948
953
  {
949
954
  name: "assess_sbd_toe_implementation",
950
955
  title: "Assess SbD-ToE Implementation",
951
- description: "SERVE OS LIMIARES PUBLICADOS APLICADOS AOS VALORES QUE DECLARASTE — a leitura é tua: não mede, não " +
952
- "verifica os teus valores e não emite juízo de suficiência. Aritmética sobre dado publicado. " +
953
- "Progresso auto-declarado: compara os KPI submetidos com os limiares publicados por nível " +
954
- "thresholds (metrics.json) → posture (below/at/above) + gaps per KPI. Stateless self-report — values " +
955
- "in, posture out, nothing stored; thresholds never invented; an applicable KPI with no value is " +
956
- "not_reported (never a pass). Use to answer 'am I compliant at L2 / where are my gaps?'.",
956
+ description: "Applies the PUBLISHED thresholds to the KPI values YOU declare — it measures nothing, verifies nothing and issues no sufficiency judgement. Compares submitted kpi_values with the per-level thresholds (metrics.json) → posture (below/at/above) and gaps per KPI. Stateless self-report: values in, posture out, nothing stored; thresholds never invented; an applicable KPI without a value is not_reported (never a pass). Answers 'where are my gaps at L2?'.",
957
957
  inputSchema: {
958
958
  type: "object",
959
959
  properties: {
@@ -981,10 +981,7 @@ class McpRuntime {
981
981
  {
982
982
  name: "plan_sbd_toe_rollout",
983
983
  title: "Plan SbD-ToE Rollout (MVP)",
984
- description: "CONSULTA À SEQUÊNCIA PUBLICADA — não planeia por ti: serve a ordem das fases que o Manual publica, " +
985
- "mapeada aos capítulos que cada uma atravessa. O roteiro é teu; isto é o que existe para o fazeres. " +
986
- "MVP — phase-ordered, the dependency DAG is deferred (declared, not faked). Grounded in the published " +
987
- "runtime; nothing invented. Use to answer 'in what order do we roll out SbD?'.",
984
+ description: "Serves the PUBLISHED phase sequence — it does not plan for you: the order of phases the manual publishes, mapped to the chapters each traverses; the roadmap is yours. Phase-ordered; the dependency DAG is deferred (declared, not faked). Grounded in the published runtime; nothing invented. Answers 'in what order do we roll out SbD?'.",
988
985
  inputSchema: {
989
986
  type: "object",
990
987
  properties: {
@@ -1001,10 +998,7 @@ class McpRuntime {
1001
998
  {
1002
999
  name: "get_sbd_toe_macro_processes",
1003
1000
  title: "Get SbD-ToE Macro-Processes (PROGRAMA)",
1004
- description: "LEITURA PROGRAMA (0.20.0-beta.37) — «por onde começamos e com que SEQUÊNCIA?». Serve os cinco macro-processos MP-01..05 que o Manual publica (pergunta, continuidade, invariante, dono, participantes, percurso de capítulos, indicadores, pontos de controlo, evidência esperada, proporcionalidade L1-L3) e a **ORDEM DE ADOPÇÃO publicada**. " +
1005
- "A ordem deriva EXCLUSIVAMENTE das arestas `dependency`: as `feedback` são realimentação e ficam FORA dela — se entrassem, os cinco macro-processos ciclariam. " +
1006
- "NÃO é a leitura GUIDE (que requisitos se aplicam a uma tarefa) nem a IMPL (a capacidade de um capítulo): devolver os 273 requisitos, ou um capítulo isolado, seria responder a outra pergunta. " +
1007
- "Limites DECLARADOS na resposta: não existe entidade «programa» (recusa de curadoria, ratificada); a travessia MP↔fase do SDLC é lacuna publicada e não se deriva; e MacroProcess, capítulo e fase são três segmentações paralelas — `traverses_bundles` é percurso, nunca contenção.",
1001
+ description: "PROGRAMME reading — 'where do we start, and in what SEQUENCE?'. The five macro-processes (MP-01..05) the manual publishes (question, continuity, invariant, owner, participants, chapter path, indicators, control points, expected evidence, L1–L3 proportionality) and the published ADOPTION ORDER, derived only from dependency edges. Not the GUIDE reading (requirements for a task) nor IMPL (a chapter's capability). Declared limits: no 'programme' entity; MP↔SDLC-phase traversal is a published gap; traverses_bundles is a path, never containment.",
1008
1002
  inputSchema: {
1009
1003
  type: "object",
1010
1004
  properties: {
@@ -1017,9 +1011,7 @@ class McpRuntime {
1017
1011
  {
1018
1012
  name: "explain_sbd_toe_topic",
1019
1013
  title: "Explain SbD-ToE Topic (CONSULT)",
1020
- description: "LEITURA CONSULT (0.20.0-beta.35) — «o que é que o Manual DIZ sobre X?», pergunta de CONHECIMENTO, sem tarefa e sem projecto. Atravessa o Manual: requisitos (com `applies_at`), ORIENTAÇÃO (práticas), PROVAS, AMEAÇAS, **ANTIPADRÕES** («o que NÃO fazer» — a metade que não tinha caminho próprio) e onde no ciclo. Distingue requisito de orientação e marca a proveniência manual-grounded. " +
1021
- "**`risk_level` é OPCIONAL aqui e ANOTA, nunca filtra** — uma pergunta de conhecimento não tem nível. Fronteira deliberada: o nível continua OBRIGATÓRIO na selecção (`select_sbd_toe_requirements`), no `prepare_sbd_toe_codegen_context` e na vista de capacidade, onde a pergunta é «o que se aplica ao MEU caso». " +
1022
- "Pede por conceito (`concern`) ou por estrutura (`category` / `chapter`).",
1014
+ description: "CONSULT reading — 'what does the manual SAY about X?': a knowledge question with no task and no project. Traverses requirements (with applies_at), guidance (practices), proofs, threats, ANTIPATTERNS (what NOT to do) and where in the lifecycle; distinguishes requirement from guidance and marks provenance. risk_level is OPTIONAL and ANNOTATES, never filters — a knowledge question has no level (it stays mandatory in select, prepare and the capability view). Ask by concept (concern) or by structure (category / chapter).",
1023
1015
  inputSchema: {
1024
1016
  type: "object",
1025
1017
  properties: {
@@ -1037,9 +1029,7 @@ class McpRuntime {
1037
1029
  {
1038
1030
  name: "get_sbd_toe_chapter_capability",
1039
1031
  title: "Get SbD-ToE Chapter Capability (IMPL)",
1040
- description: "LEITURA IMPL (0.20.0-beta.34) — «a organização quer implementar o cap. N: que capacidade precisa de ter, como sabe que está capaz, e COMO MEDE?». Publica os KPIs que o MANUAL define para o capítulo, com os `thresholds_by_level` (L1/L2/L3) como dado — é isso que distingue MEDIR de listar — mais os ARTEFACTOS que a capacidade tem de produzir. " +
1041
- "NÃO é a leitura GUIDE: se a pergunta é «que requisitos se aplicam a ESTA tarefa», isso é `select_sbd_toe_requirements`. A resposta declara qual das duas recebeste no campo `reading`. " +
1042
- "Alcançável por capítulo (`chapter`), por KPI (`metric_id`) ou por dimensão (`dimension`); `risk_level` acrescenta o alvo desse nível. Fecha o ciclo com `assess_sbd_toe_implementation`, que avalia os valores que TU medires contra estes mesmos KPIs.",
1032
+ description: "IMPL reading — 'to implement chapter N, what capability do we need, how do we know we have it, and how do we MEASURE?'. The KPIs the manual defines for the chapter, with thresholds_by_level (L1/L2/L3) as data — measuring, not listing — plus the artefacts the capability must produce. Not the GUIDE reading ('which requirements apply to THIS task' is select_sbd_toe_requirements); the response names the reading it gave you. Reachable by chapter, metric_id or dimension; risk_level adds that level's target. Closes the loop with assess_sbd_toe_implementation.",
1043
1033
  inputSchema: {
1044
1034
  type: "object",
1045
1035
  properties: {
@@ -1048,7 +1038,7 @@ class McpRuntime {
1048
1038
  dimension: { type: "string", description: "Filtra por dimensão (ex.: `T-01`)." },
1049
1039
  risk_level: { type: "string", enum: ["L1", "L2", "L3"], description: "Acrescenta `target_at_level`: o threshold que ESTE nível exige." },
1050
1040
  offset: { type: "number", description: "Paginação sobre os KPIs." },
1051
- limit: { type: "number", description: "KPIs por página (default 25; 99 publicados no total)." }
1041
+ limit: { type: "number", description: `KPIs por página (default 25; ${loadMetrics().length} publicados no total).` }
1052
1042
  },
1053
1043
  additionalProperties: false
1054
1044
  },
@@ -1057,10 +1047,7 @@ class McpRuntime {
1057
1047
  {
1058
1048
  name: "get_sbd_toe_playbook",
1059
1049
  title: "Get SbD-ToE Cross-Check / Playbook",
1060
- description: "CAMINHO NORMATIVO para cross-checks e playbooks (0.20.0-beta.33). Responde a «somos sujeitos ao DORA/NIS2/CRA/RGPD/AI-Act — como é que o SbD-ToE nos serve?» com o PLAYBOOK publicado pelo Manual: mapa artigo→capítulo→acção, fases com marcos e checklist de leitura, servidos com a AUTORIDADE declarada. Ao contrário do `search_sbd_toe_manual` (NÃO-NORMATIVO, leitura), esta superfície é normativa. " +
1061
- "Sem argumentos devolve o ÍNDICE (barato); `framework=\"DORA\"` os playbooks desse diploma; `playbook_id=…` as secções paginadas. Os EXEMPLOS ILUSTRATIVOS vêm em banda SEPARADA e nunca com o estatuto dos cross-checks. " +
1062
- "Framework sem cross-check publicado (ISO 27001, HIPAA, PCI-DSS, SOC2, FedRAMP, CSA STAR) devolve `status: \"no_cross_check\"` com o roadmap do próprio Manual — declarado, nunca improvisado. " +
1063
- "Toda a resposta traz a DELIMITAÇÃO: o SbD-ToE não é uma norma, e implementá-lo não é conformidade.",
1050
+ description: "NORMATIVE path for cross-checks and playbooks: 'we are subject to DORA/NIS2/CRA/GDPR/AI Act — how does SbD-ToE serve us?', answered with the manual's published playbook (article→chapter→action map, phases with milestones, reading checklist) under its declared authority — unlike search_sbd_toe_manual (non-normative). No arguments: the cheap INDEX; framework: its playbooks; playbook_id: paginated sections. Illustrative examples come in a SEPARATE band; frameworks without a cross-check return no_cross_check. SbD-ToE is not a standard; implementing it is not compliance.",
1064
1051
  inputSchema: {
1065
1052
  type: "object",
1066
1053
  properties: {
@@ -1077,10 +1064,7 @@ class McpRuntime {
1077
1064
  {
1078
1065
  name: "map_sbd_toe_regulatory_activation",
1079
1066
  title: "Map SbD-ToE Regulatory Activation",
1080
- description: "Regulatory lens (reverse of provenance): given a framework (DORA, NIS2, CRA, RGPD), " +
1081
- "returns which SbD-ToE manual areas/chapters it activates, grouped with mapping + obligation " +
1082
- "counts per chapter (coverage-preserving — never a blind dump). Data from the published overlay " +
1083
- "mappings; nothing invented. Use to answer 'framework X → what do I need to implement?'.",
1067
+ description: "Regulatory lens (reverse of provenance): given a framework (DORA, NIS2, CRA, GDPR), returns which manual areas/chapters it activates, grouped with mapping and obligation counts per chapter (coverage-preserving — never a blind dump). Data from the published overlay mappings; nothing invented. Answers 'framework X → what do I need to implement?'.",
1084
1068
  inputSchema: {
1085
1069
  type: "object",
1086
1070
  properties: {
@@ -1099,7 +1083,7 @@ class McpRuntime {
1099
1083
  {
1100
1084
  name: "map_sbd_toe_applicability",
1101
1085
  title: "Map SbD-ToE Applicability",
1102
- description: "GRADUATED applicability (0.14.0): every chapter applies at every level — returns per-chapter authored demand (obrigatório/recomendado/opcional/specific) derived from the bundle, anchored on the chapter-01 canonical matrix; plus context-conditional bundles for the given technologies. projectRole adds a per-role view. Nothing is excluded by level.",
1086
+ description: "GRADUATED applicability: every chapter applies at every level — returns per-chapter authored demand (mandatory/recommended/optional/specific) derived from the bundle and anchored on the chapter-01 canonical matrix, plus context-conditional bundles for the given technologies. projectRole adds a per-role view. Nothing is excluded by level.",
1103
1087
  inputSchema: {
1104
1088
  type: "object",
1105
1089
  properties: {
@@ -1155,12 +1139,7 @@ class McpRuntime {
1155
1139
  {
1156
1140
  name: "read_sbd_toe_resource",
1157
1141
  title: "Read SbD-ToE Resource (mirror)",
1158
- description: "Mirror of resources/read for clients without MCP resource support (e.g. Claude Desktop): " +
1159
- "returns the content of any server resource by URI — including templated ones with the value " +
1160
- "in the URI (e.g. sbd://toe/codegen-instructions/codegen). Makes the codegen_instructions_ref " +
1161
- "of dieted prepare payloads resolvable on ANY client, and sbd://toe/version readable as a tool. " +
1162
- `Valid URIs: ${validResourceUris()}. ` +
1163
- "Unknown URI returns a declared error listing the valid set (never silent).",
1142
+ description: "Mirror of resources/read for clients without MCP resource support (e.g. Claude Desktop): returns any server resource by URI, including templated ones with the value in the URI (e.g. sbd://toe/codegen-instructions/codegen, sbd://toe/notes/{id}). Makes the codegen-instructions reference copy, the notes registry and sbd://toe/version readable as a tool. Unknown URI returns a declared error listing the valid set (never silent); resources/list enumerates them.",
1164
1143
  inputSchema: {
1165
1144
  type: "object",
1166
1145
  properties: {
@@ -1177,10 +1156,7 @@ class McpRuntime {
1177
1156
  {
1178
1157
  name: "trace_sbd_toe_requirement_sources",
1179
1158
  title: "Trace SbD-ToE Requirement Sources (estação 3)",
1180
- description: "Onde está a FONTE de cada requisito: fontes DIRECTAS (source_anchors — autoria do Manual, marcador «Fontes») " +
1181
- "e cadeia COMPENSADA REQ→CTRL→ACO→fontes com tipo/confiança por salto (rótulo coverage_compensated — " +
1182
- "COBERTURA por correspondência entre modelos, NÃO autoria; related não cobre). Servida verbatim da superfície " +
1183
- "publicada (contrato v1.17 §1.24); os sem-fonte-declarada vêm DECLARADOS; ids desconhecidos idem.",
1159
+ description: "Where each requirement's SOURCE is: DIRECT sources (source_anchors — the manual's own 'Fontes' marker) and the COMPENSATED chain REQ→CTRL→ACO→sources with type and confidence per hop (label coverage_compensated: coverage by cross-model correspondence, NOT authorship; 'related' does not cover). Served verbatim from the published surface; requirements without a declared source, and unknown ids, are declared.",
1184
1160
  inputSchema: {
1185
1161
  type: "object",
1186
1162
  properties: {
@@ -1197,18 +1173,7 @@ class McpRuntime {
1197
1173
  {
1198
1174
  name: "select_sbd_toe_requirements",
1199
1175
  title: "Select SbD-ToE Requirements (MP1)",
1200
- description: "START HERE — para qualquer tarefa concreta esta é a 1ª tool. Arranque: lê sbd://toe/agent-guide (read_sbd_toe_resource); setup_sbd_toe_agent é um PROMPT MCP — clientes sem prompts (p.ex. Desktop) não o expõem: segue directo por aqui. DECLARATIVO PRIMEIRO (contrato v1.18-beta, linha 0.20): TU tens o contexto — lê o pedido, o código e a conversa e DECLARA o que interpretaste (risk_level, concerns, exposure, data_sensitivity, technologies, changed_files). EU NÃO INTERPRETO PROSA: respondo com o que o KG sabe sobre o declarado, mais as adjacências do grafo, de forma reproduzível. Vocabulário fechado em sbd://toe/activation-vocabulary. O `task` fica REGISTADO para auditoria e NÃO influencia o resultado; sem nenhuma declaração devolvo needs_input com o vocabulário e candidatos A CONFIRMAR (nunca adivinho, nunca devolvo zero em silêncio); a baseline do nível pede-se explicitamente (mode='baseline'); o motor inferencial antigo fica em mode='discover' (exploratório). The MP1 selection operation (Classificar → Seleccionar): which requirements apply to THIS task in THIS " +
1201
- "context. Composes the reference semantics the published ontology declares — baseline (cap. 02 base " +
1202
- "catalogue, by risk level) ∪ domain chapters activated by the DECLARED activators (concerns, exposure, " +
1203
- "data_sensitivity, technologies, changed_files) ∪ the categories the published vocabulary promises " +
1204
- "⊕ regulatory overlay (extend) — then narrows deterministically by those same declarations. The task " +
1205
- "text is NEVER an activator in declarative mode (it is recorded context; it is only an engine in " +
1206
- "mode='discover'). Returns the bands: selected[] (each with its selection_trace: source/trigger/score), " +
1207
- "narrowed_out[] (eligible-without-signal, grouped by category, with reason), excluded_by_level[] and " +
1208
- "out_of_scope_chapters (what no declaration activated, by chapter and count, with how to bring it in) — " +
1209
- "never silent, and the SCOPE of that promise is the universe, not just the baseline. Paginated. " +
1210
- SELECT_PAGINATION + " " +
1211
- "All data from the published deterministic runtime bundle — nothing is invented.",
1176
+ description: "START HERE. DECLARATIVE FIRST: DECLARE what you read — risk_level, concerns, exposure, data_sensitivity, technologies, changed_files, or structure (chapters, categories); the server never interprets prose (vocabulary: sbd://toe/activation-vocabulary). `task` is recorded, not selecting; no declaration ⇒ needs_input. Bands: selected, narrowed_out, excluded_by_level, out_of_scope_chapters. " + SELECT_PAGINATION,
1212
1177
  inputSchema: {
1213
1178
  type: "object",
1214
1179
  properties: {
@@ -1225,8 +1190,8 @@ class McpRuntime {
1225
1190
  },
1226
1191
  detail: {
1227
1192
  type: "string",
1228
- enum: ["full", "standard", "minimal"],
1229
- description: "Nível de SERIALIZAÇÃO da resposta (0.20.0-beta.26; default `full` = comportamento anterior, byte-idêntico). `standard` e `minimal` movem as justificações DISTINTAS do `selection_trace` para `selection_trace_legend` e deixam cada item a referi-las em `trace` — medido: −40% e −48% de payload numa selecção de 115 requisitos (12 justificações distintas para 115 entradas), com o MESMO conjunto de ids. Dieta de serialização, nunca de conteúdo: nenhum id e nenhuma justificação se perdem. `minimal` elide ainda `type` e `source_chapter` (deriváveis)."
1193
+ enum: ["lista", "standard", "full"],
1194
+ description: "Serialization level — the same axis as prepare (inline vs by reference). full (default): each item carries its full selection_trace. standard: the DISTINCT justifications move to selection_trace_legend and each item references them in `trace` (measured −40%). lista: standard minus the derivable `type` and `source_chapter` (recoverable via trace_sbd_toe_requirement_sources; −48%). Same id set at every level — a serialization diet, never a content one. 'minimal' was renamed 'lista'; the error says so."
1230
1195
  },
1231
1196
  task_context: { type: "string", description: "CONTEXTO REGISTADO (auditoria): o enunciado da tarefa. NOME CANÓNICO desde 0.20.0-beta.24 — um campo chamado `task` convidava a ser o motor, e não é: NÃO influencia a selecção no modo declarativo. Alias `task` continua aceite (aditivo, nunca renomeámos nada); em mode='discover' o texto é motor e `task` é o nome a usar." },
1232
1197
  task: { type: "string", description: "ALIAS de `task_context` (compatibilidade). Em mode='discover' é o MOTOR (casamento lexical, exploratório); no modo declarativo é apenas contexto registado." },
@@ -1254,12 +1219,7 @@ class McpRuntime {
1254
1219
  {
1255
1220
  name: "consult_security_requirements",
1256
1221
  title: "Consult SbD-ToE Security Requirements",
1257
- description: "Deterministic resolution of security requirements, controls and artifacts for a given application context. " +
1258
- "Filters requirements by risk level, optionally narrows by concern domains (auth, logging, api, etc.), " +
1259
- "then resolves controls via the published runtime bundle, complementing with ontology domain_mapping when needed. " +
1260
- "Requirements with no published control link are served and declared in coverage_gaps (never omitted). " +
1261
- "Os corpos devolvidos são PROJECÇÕES (id/name/category/type) — detalhe completo via resolve_entities; ≤3 concerns por chamada (âmbito recomendado; maxItems no schema). " +
1262
- "All data comes from the published SbD-ToE deterministic runtime bundle — nothing is invented.",
1222
+ description: "Deterministic resolution of requirements, controls and artifacts for an application context: filters requirements by risk level, optionally narrows by concern domains (at most 3 per call recommended), then resolves controls via the published runtime bundle, complementing with ontology domain_mapping when needed. Requirements with no published control link are served and declared in coverage_gaps. Bodies are PROJECTIONS (id/name/category/type) — full detail via resolve_entities. All data from the published bundle; nothing invented.",
1263
1223
  inputSchema: {
1264
1224
  type: "object",
1265
1225
  properties: {
@@ -1306,31 +1266,14 @@ class McpRuntime {
1306
1266
  {
1307
1267
  name: "get_threat_landscape",
1308
1268
  title: "Get SbD-ToE Threat Landscape",
1309
- description: `ROTEAMENTO ≠ COBERTURA (0.20.0-beta.29): aceita os ${DECLARED_CONCERNS.length} concerns do vocabulário sem erro, mas só ` +
1310
- `${threatDomainConcerns().length} têm capítulo de ameaças PRÓPRIO — ${threatDomainConcerns().join(", ")}. ` +
1311
- `Para os outros ${DECLARED_CONCERNS.length - threatDomainConcerns().length} as ameaças chegam pelos capítulos onde se DEFINEM os controlos que o concern activa: ` +
1312
- "são reais e do âmbito activado, mas NÃO são «as ameaças deste domínio». A resposta declara-o em `routing_basis` " +
1313
- "(`domain_chapter` | `activated_controls`) — e a tabela acima diz-to ANTES de gastares a chamada. " +
1314
- "Em detail='standard'/'minimal' os nomes e ids dos controlos vêm por REFERÊNCIA à `associated_control_legend` — a promessa de campos completos é do detail='full'. " +
1315
- // 0.20.0-beta.31: a frase da ORDEM vem da mesma constante que a nota da resposta
1316
- // usa. Enquanto foram dois textos, divergiram duas versões (o `meta.note` ficou a
1317
- // dar o conselho oposto ao correcto). A guarda em behaviour-notes.test.ts vigia-o.
1318
- THREAT_ORDERING + " " +
1319
- "Qualquer outro concern é VÁLIDO e tem requisitos, mas não é roteável AQUI: vem declarado em `unsupported_concerns`, e se TODOS os declarados forem não-roteáveis a resposta é `needs_input` em vez de um payload cheio de ameaças de governação sem relação com o pedido. " +
1320
- "Deterministic threat resolution for an application context using the SbD-ToE ontology threats pipeline. " +
1321
- "Returns threats from the published runtime bundle relevant to the active requirement/chapter scope " +
1322
- "(the defining chapters of activated controls count as in-scope), with structural mitigation confidence, " +
1323
- "antipattern enrichment, per-threat associated_control_ids (structural CTRL-* ids with declared " +
1324
- "derivation) and associated_control_names (readable control names, 233/233 since contract v1.16). " +
1325
- "Optionally narrowed by concern domains. " +
1326
- "All data comes from the published SbD-ToE deterministic runtime bundle — nothing is invented.",
1269
+ description: "Threats for a declared context. ROUTING ≠ COVERAGE: all 24 concerns are accepted, but only 11 have a threat chapter of their OWN (architecture, build, deployment, distribution, iac, logging, monitoring, release, supply_chain, testing, threat_modeling); for the others, threats arrive via the chapters that define the activated controls (routing_basis says which); non-routable ones go to unsupported_concerns. " + THREAT_ORDERING,
1327
1270
  inputSchema: {
1328
1271
  type: "object",
1329
1272
  properties: {
1330
1273
  detail: {
1331
1274
  type: "string",
1332
- enum: ["full", "standard", "minimal"],
1333
- description: "Nível de SERIALIZAÇÃO (0.20.0-beta.28; default `full` = byte-idêntico ao anterior, mantém `associated_control_ids`/`associated_control_names` como o contrato v1.14 §1.21 os publica). `standard`/`minimal` trocam-nos por referências + `associated_control_legend` — medido −50% do payload (os mesmos 13 nomes vinham repetidos verbatim em cada ameaça). Dedup de serialização: nada se perde."
1275
+ enum: ["lista", "standard", "full"],
1276
+ description: "Serialization level — the same axis as prepare and select (inline vs by reference). full (default): associated_control_ids / associated_control_names inline on every threat, as the contract publishes them. standard and lista: the controls are referenced through associated_control_legend (measured −50%: the same names were repeated verbatim per threat); for this tool the two are identical — nothing else is served by reference. Same threat set at every level. 'minimal' was renamed 'lista'; the error says so."
1334
1277
  },
1335
1278
  risk_level: {
1336
1279
  type: "string",
@@ -1356,10 +1299,7 @@ class McpRuntime {
1356
1299
  {
1357
1300
  name: "get_guide_by_role",
1358
1301
  title: "Get SbD-ToE Guide by Role",
1359
- description: "Returns runtime-grounded practices, assignments and user stories for a given risk level, " +
1360
- "optionally filtered by role and/or lifecycle phase. " +
1361
- "Each assignment carries its required ARTIFACTS (the requirement→evidence link, served from the bundle since contract v1.16). Roles are resolved via canonical aliases (e.g. 'appsec' → 'appsec-engineer', 'sre' → 'devops-sre', 'security-engineer' → 'appsec-engineer'). " +
1362
- "Results grouped by role and phase. All data from the published SbD-ToE deterministic runtime bundle — nothing is invented.",
1302
+ description: "Runtime-grounded practices, assignments and user stories for a risk level, optionally filtered by role and/or lifecycle phase. Each assignment carries its required ARTIFACTS (the requirement→evidence link, served from the bundle). Roles resolve via canonical aliases (e.g. 'appsec' → 'appsec-engineer', 'sre' → 'devops-sre'). Results grouped by role and phase. All data from the published bundle — nothing invented.",
1363
1303
  inputSchema: {
1364
1304
  type: "object",
1365
1305
  properties: {
@@ -1389,66 +1329,13 @@ class McpRuntime {
1389
1329
  {
1390
1330
  name: "resolve_entities",
1391
1331
  title: "Resolve SbD-ToE Entities",
1392
- description: "Low-level entity resolver over the published SbD-ToE deterministic artefacts. " +
1393
- "Three sources are routed by record_type, each with its own provenance: " +
1394
- "(1) runtime v0 (data/publish/runtime/*.json) for requirement / control / threat / artifact " +
1395
- "and related links; " +
1396
- "(2) AppSec Core v1 (data/publish/runtime/v1/*) for appsec_slice, control_objective, mechanism, " +
1397
- "appsec_practice, appsec_artifact and appsec_relation; " +
1398
- "(3) regulatory overlay (data/publish/overlay/*) for regulatory_framework, regulatory_obligation, " +
1399
- "regulatory_mapping and regulatory_playbook. " +
1400
- "Query any entity type by record_type with optional field filters. " +
1401
- "Supports dot-notation for nested fields (e.g. 'applicable_levels.L2'), " +
1402
- "comparison operators ({gte, lte} for numbers, {in: [...]} for set membership), " +
1403
- "and array membership checks. " +
1404
- "If the regulatory overlay is not published in this deployment, regulatory record types " +
1405
- "return total: 0 with an absent-reason note instead of throwing. " +
1406
- "Use this when the high-level tools (consult_security_requirements, get_threat_landscape, " +
1407
- "get_guide_by_role) do not cover your specific query. " +
1408
- "All data from the published SbD-ToE deterministic artefacts — nothing is invented.",
1332
+ description: "Low-level entity resolver over the published artefacts, routed by record_type: runtime v0 (requirement, control, threat, artifact, evidence_pattern, links), AppSec Core v1 (appsec_slice, control_objective, mechanism, appsec_practice, appsec_artifact, appsec_relation) and the regulatory overlay (regulatory_framework/_obligation/_mapping/_playbook). Filters: dot-notation ('applicable_levels.L2'), {gte, lte}, {in: [...]}, array membership. Unpublished overlay ⇒ total 0 with a declared reason. Use when the high-level tools do not cover the query. Nothing invented.",
1409
1333
  inputSchema: {
1410
1334
  type: "object",
1411
1335
  properties: {
1412
1336
  record_type: {
1413
1337
  type: "string",
1414
- description: "Entity type to query. " +
1415
- "Runtime v0 (data/publish/runtime/*.json): requirement, control, practice, threat, " +
1416
- "user_story, assignment, role, phase, artifact, evidence_pattern, signal, antipattern, " +
1417
- "requirement_control_link, signal_evidence_link, antipattern_requirement_link, " +
1418
- "antipattern_threat_link. " +
1419
- "AppSec Core v1 (data/publish/runtime/v1/*): appsec_slice, control_objective, mechanism, " +
1420
- "appsec_practice, appsec_artifact, appsec_relation. " +
1421
- "Regulatory overlay (data/publish/overlay/*): regulatory_framework, regulatory_obligation, " +
1422
- "regulatory_mapping, regulatory_playbook. " +
1423
- "Read sbd://toe/ontology to see the schemas.",
1424
- enum: [
1425
- "requirement",
1426
- "control",
1427
- "practice",
1428
- "threat",
1429
- "user_story",
1430
- "assignment",
1431
- "role",
1432
- "phase",
1433
- "artifact",
1434
- "evidence_pattern",
1435
- "signal",
1436
- "antipattern",
1437
- "requirement_control_link",
1438
- "signal_evidence_link",
1439
- "antipattern_requirement_link",
1440
- "antipattern_threat_link",
1441
- "appsec_slice",
1442
- "control_objective",
1443
- "mechanism",
1444
- "appsec_practice",
1445
- "appsec_artifact",
1446
- "appsec_relation",
1447
- "regulatory_framework",
1448
- "regulatory_obligation",
1449
- "regulatory_mapping",
1450
- "regulatory_playbook"
1451
- ]
1338
+ description: "Record type to resolve. Runtime v0: requirement, control, threat, artifact, evidence_pattern, requirement_control_link (and related links). AppSec Core v1: appsec_slice, control_objective, mechanism, appsec_practice, appsec_artifact, appsec_relation. Regulatory overlay: regulatory_framework, regulatory_obligation, regulatory_mapping, regulatory_playbook. An unknown value returns a declared error listing the valid record types."
1452
1339
  },
1453
1340
  filters: {
1454
1341
  type: "object",
@@ -1471,16 +1358,7 @@ class McpRuntime {
1471
1358
  {
1472
1359
  name: "trace_sbd_toe_graph",
1473
1360
  title: "Trace SbD-ToE Ontology Graph",
1474
- description: "Curated multi-hop traversal over the AppSec Core v1 relation graph (slices, control " +
1475
- "objectives, mechanisms, practices). Answers traceability questions the high-level tools " +
1476
- "do not expose directly. Pick a `lens`: " +
1477
- "'slice_implementation' (a slice -> its control objectives -> the mechanisms that implement " +
1478
- "and practices that realize them); " +
1479
- "'objective_realization' (a control objective -> its mechanisms + practices); " +
1480
- "'mechanism_provenance' (a mechanism/practice -> the objectives it serves -> their slices). " +
1481
- "Optionally scope with `anchor` (an entity id). Results are deterministic and paginated " +
1482
- "(total + cursor; never silently truncated). All edges from the published deterministic " +
1483
- "runtime — nothing is invented.",
1361
+ description: "Curated multi-hop traversal over the AppSec Core v1 relation graph (slices, control objectives, mechanisms, practices) for traceability questions the high-level tools do not expose. Pick a lens: slice_implementation (slice → objectives → implementing mechanisms and realizing practices); objective_realization (objective → mechanisms + practices); mechanism_provenance (mechanism/practice → the objectives it serves → their slices). Optionally scope with anchor (an entity id). Deterministic and paginated (total + cursor; never silently truncated). All edges from the published runtime.",
1484
1362
  inputSchema: {
1485
1363
  type: "object",
1486
1364
  properties: {
@@ -1508,27 +1386,7 @@ class McpRuntime {
1508
1386
  {
1509
1387
  name: "prepare_sbd_toe_codegen_context",
1510
1388
  title: "Prepare SbD-ToE Grounded Codegen Context",
1511
- description: "MONTA CONTEXTO, NÃO AGE — não escreve, não altera e não valida o teu código: reúne o contexto " +
1512
- "determinístico e citável para TU gerares. Contexto grounded, em porções, para um LLM a jusante gerar, " +
1513
- "review or plan tests for code. This tool DOES NOT generate code and DOES NOT edit files. " +
1514
- "It runs a scope gate (rejecting vague or overly broad asks), an auditable semantic " +
1515
- "activation step (explicit concerns, single-token lexicon, compound phrases such as " +
1516
- "'endpoint seguro', PT/EN alias expansion via the semantic gateway, and a whole-word intent " +
1517
- "classifier — every activation carries a deterministic score in [0,1]), and deterministic " +
1518
- "resolution against runtime v0, runtime v1 and the regulatory overlay. " +
1519
- "Returns one of four statuses: ready_for_codegen, needs_clarification, needs_decomposition, " +
1520
- "unsupported_scope. On ready_for_codegen the output carries activation_trace (with score, " +
1521
- "source and reason), activated_scope, g2_context, manual_grounding, regulatory_overlay, " +
1522
- "citation_map, completeness_report (incl. as métricas do cap de evidence_patterns — o cap é por PERTENÇA ao âmbito, não por relevância), " +
1523
- "llm_codegen_instructions and security_rationale_template — with provenance for each section. " +
1524
- "Evidence patterns are ordered by MEMBERSHIP of the activated scope — first those whose "
1525
- + "`maps_to_requirement_id` is a requirement of the activated scope, then those of a direct "
1526
- + "control, then of a derived control; WITHIN each tier the order is by id, which is NOT a "
1527
- + "ranking: two patterns of the same tier are equally in scope and the id only makes the cut "
1528
- + "deterministic. Capped (default 25) so " +
1529
- "the LLM context stays manageable; the dropped patterns are listed in debug.rejected_candidates " +
1530
- "when debug=true. No canonical IDs are ever invented; names are surfaced only when " +
1531
- "manual_rastreabilidade publishes them.",
1389
+ description: "ASSEMBLES CONTEXT, DOES NOT ACT: writes, changes and validates no code — it gathers deterministic, citable context for YOU to generate, review or plan tests. Declare the context (risk_level, concerns, exposure, data_sensitivity, technologies, changed_files, or chapters/categories); the task is recorded, not interpreted. Statuses: ready_for_codegen, needs_clarification, needs_decomposition (batches that sum to the whole), needs_input, unsupported_scope. Ready: one FUSED object per requirement (id, name, type, description, verify, evidence), citations, adjacency, instructions, size_estimate.",
1532
1390
  inputSchema: {
1533
1391
  type: "object",
1534
1392
  properties: {
@@ -1580,6 +1438,16 @@ class McpRuntime {
1580
1438
  type: "boolean",
1581
1439
  description: "When true (and overlay is published), enriches the response with regulatory_overlay context."
1582
1440
  },
1441
+ chapters: {
1442
+ type: "array",
1443
+ items: { type: "string" },
1444
+ description: "0.21 §6 — FORMA B (como no select): capítulos declarados (source_bundle, p.ex. \"11-deploy-seguro\"), verificados contra o catálogo. Só no caminho declarativo."
1445
+ },
1446
+ categories: {
1447
+ type: "array",
1448
+ items: { type: "string" },
1449
+ description: "0.21 §6 — FORMA B: categorias declaradas (p.ex. \"AUT\", \"SES\"). É a receita dos lotes de needs_decomposition: cada lote é a partição exacta das categorias que a tua declaração activou (technologies/changed_files preservados), e a união dos lotes é o conjunto inteiro (m_recall 1). Só no caminho declarativo."
1450
+ },
1583
1451
  technologies: {
1584
1452
  type: "array",
1585
1453
  items: { type: "string" },
@@ -1592,49 +1460,22 @@ class McpRuntime {
1592
1460
  },
1593
1461
  detail: {
1594
1462
  type: "string",
1595
- enum: ["ultrathin", "minimal", "standard", "full"],
1596
- description: "Response encoding level (v2 token diet). 'full' (default) returns the classic payload, " +
1597
- "Níveis dieted têm TECTO de requisitos por chamada — minimal 78, standard 81, " +
1598
- "ultrathin 86 (derivados da medição ~68/~68/~29 tk/req vs promessas " +
1599
- "8450/9200/4840 tk); acima ⇒ needs_decomposition c/ requirement_ceiling e divisão " +
1600
- "ensinada; 'full' sem tecto (promessa = completude). " +
1601
- "byte-identical to previous releases. 'standard'/'minimal' return the SAME citable ID set " +
1602
- "with a deduplicated encoding: inverted `citations` (run-length source_data + ids_from " +
1603
- "payload paths) replaces `citation_map`, `manual_grounding` is grouped, per-item `source` " +
1604
- "and other derivable fields (requirement category, entity_type/slice_family, " +
1605
- "relevance_score) are elided per the `provenance_legend`/resource legend, and " +
1606
- "`g2_context.relations` is replaced by `g2_context.relations_ref` — executable " +
1607
- "trace_sbd_toe_graph {lens, anchor} calls (set include_relations=true to keep relations " +
1608
- "inline instead). Additionally at 'standard'/'minimal': evidence_patterns are capped " +
1609
- "(deterministic prefix; counts + rest-reference in completeness_report), " +
1610
- "llm_codegen_instructions + security_rationale_template move to the MCP resource " +
1611
- "sbd://toe/codegen-instructions/{mode} (see codegen_instructions_ref), activation_trace is " +
1612
- "included only with debug=true (activation_trace_ref keeps the count), and requirements + " +
1613
- "direct controls carry the verbatim published `description`. Nothing is silently dropped. " +
1614
- "'minimal' keeps the SAME complete activated scope as 'standard' (no ranking/subsetting) " +
1615
- "and trims only traceability serialization: evidence_patterns cap 5 (vs 10) and " +
1616
- "manual_grounding as counts + shared manual_commit_sha + executable groups_ref " +
1617
- "(same input, detail='standard'). 'ultrathin' goes one level below 'minimal' with the same " +
1618
- "rules (complete activated set, nothing id-only, never silent): requirements/controls keep " +
1619
- "id+name(+type/domain/control_type/confidence) but drop the published description " +
1620
- "(executable activated_scope.descriptions_ref, detail='minimal'), evidence_patterns are 0 " +
1621
- "inline (counts + rest-ref to detail='minimal'), manual_grounding is " +
1622
- "{total_entries, manual_commit_sha, groups_ref} and completeness_report diagnostics become " +
1623
- "exact counts (+ executable ref)."
1463
+ enum: ["lista", "standard", "full"],
1464
+ description: "Response level. lista: every activated requirement complete and verbatim (id, name, type, description, verify, evidence) + citations + inline instructions/template; grounding by reference; relations out (relations_summary); adjacency summary with detail_ref. standard: lista + the adjacency detail inline. full (default): standard + manual_grounding inline, relations_ref, activation_trace, no ceiling, price in size_estimate. Ceilings by declared count: lista 52, standard 55 \u2014 above them needs_decomposition with batches that sum to the whole. 'ultrathin'/'minimal' are retired."
1624
1465
  },
1625
1466
  include_relations: {
1626
1467
  type: "boolean",
1627
- description: "Escape hatch for clients that cannot make a second call (v2 token diet). When true at " +
1628
- "detail='standard'/'minimal', keeps g2_context.relations inline (dieted: no per-item source) " +
1629
- "instead of the relations_ref reference. Default false. Ignored at detail='full' (full always " +
1630
- "carries relations inline, byte-identical to previous releases)."
1468
+ description: "Escape hatch for clients that cannot make a second call. When true at " +
1469
+ "detail='lista'/'standard', keeps g2_context.relations inline (dieted: no per-item source) " +
1470
+ "instead of the relations_ref reference. Default false. Ignored at detail='full' (relations " +
1471
+ "always inline there)."
1631
1472
  },
1632
1473
  debug: {
1633
1474
  type: "boolean",
1634
1475
  description: "When true, includes rejected_candidates and trace notes in the output."
1635
1476
  }
1636
1477
  },
1637
- required: ["task"],
1478
+ required: [], // 0.21 §6: em declarativo o task é contexto REGISTADO (opcional); em discover é o motor e a sua ausência responde needs_clarification
1638
1479
  additionalProperties: false
1639
1480
  },
1640
1481
  annotations: { readOnlyHint: true }
@@ -1703,7 +1544,7 @@ class McpRuntime {
1703
1544
  return;
1704
1545
  }
1705
1546
  this.sendResponse(request.id, {
1706
- description: "Bundled SbD-ToE grounded codegen prompt — instructs the agent to call prepare_sbd_toe_codegen_context first, branch on status, cite citation_map and avoid compliance claims.",
1547
+ description: "Bundled SbD-ToE grounded codegen prompt — instructs the agent to call prepare_sbd_toe_codegen_context first, branch on status, cite ids from `citations` and avoid compliance claims.",
1707
1548
  messages: [
1708
1549
  {
1709
1550
  role: "user",
@@ -1981,7 +1822,7 @@ class McpRuntime {
1981
1822
  case "list_sbd_toe_chapters": {
1982
1823
  const result = handleListSbdToeChapters(args);
1983
1824
  this.sendResponse(request.id, {
1984
- content: [{ type: "text", text: JSON.stringify(result) }]
1825
+ content: [{ type: "text", text: this.toolText(result) }]
1985
1826
  });
1986
1827
  await this.log("info", {
1987
1828
  event_type: "tool.call",
@@ -1995,7 +1836,7 @@ class McpRuntime {
1995
1836
  case "query_sbd_toe_entities": {
1996
1837
  const result = await handleQuerySbdToeEntities(args);
1997
1838
  this.sendResponse(request.id, {
1998
- content: [{ type: "text", text: JSON.stringify(result) }]
1839
+ content: [{ type: "text", text: this.toolText(result) }]
1999
1840
  });
2000
1841
  await this.log("info", {
2001
1842
  event_type: "tool.call",
@@ -2009,7 +1850,7 @@ class McpRuntime {
2009
1850
  case "get_sbd_toe_chapter_brief": {
2010
1851
  const result = handleGetSbdToeChapterBrief(args);
2011
1852
  this.sendResponse(request.id, {
2012
- content: [{ type: "text", text: JSON.stringify(result) }]
1853
+ content: [{ type: "text", text: this.toolText(result) }]
2013
1854
  });
2014
1855
  await this.log("info", {
2015
1856
  event_type: "tool.call",
@@ -2023,7 +1864,7 @@ class McpRuntime {
2023
1864
  case "plan_sbd_toe_repo_governance": {
2024
1865
  const result = handlePlanRepoGovernance(args);
2025
1866
  this.sendResponse(request.id, {
2026
- content: [{ type: "text", text: JSON.stringify(result) }]
1867
+ content: [{ type: "text", text: this.toolText(result) }]
2027
1868
  });
2028
1869
  await this.log("info", {
2029
1870
  event_type: "tool.call",
@@ -2037,7 +1878,7 @@ class McpRuntime {
2037
1878
  case "generate_sbd_toe_skill": {
2038
1879
  const result = handleGenerateSbdToeSkill(args);
2039
1880
  this.sendResponse(request.id, {
2040
- content: [{ type: "text", text: JSON.stringify(result) }]
1881
+ content: [{ type: "text", text: this.toolText(result) }]
2041
1882
  });
2042
1883
  await this.log("info", {
2043
1884
  event_type: "tool.call",
@@ -2051,7 +1892,7 @@ class McpRuntime {
2051
1892
  case "map_sbd_toe_review_scope": {
2052
1893
  const result = handleMapSbdToeReviewScope(args);
2053
1894
  this.sendResponse(request.id, {
2054
- content: [{ type: "text", text: JSON.stringify(result) }]
1895
+ content: [{ type: "text", text: this.toolText(result) }]
2055
1896
  });
2056
1897
  await this.log("info", {
2057
1898
  event_type: "tool.call",
@@ -2065,7 +1906,7 @@ class McpRuntime {
2065
1906
  case "get_sbd_toe_chapter_implementation_checklist": {
2066
1907
  const result = handleGetChapterImplementationChecklist(args);
2067
1908
  this.sendResponse(request.id, {
2068
- content: [{ type: "text", text: JSON.stringify(result) }]
1909
+ content: [{ type: "text", text: this.toolText(result) }]
2069
1910
  });
2070
1911
  await this.log("info", {
2071
1912
  event_type: "tool.call",
@@ -2079,7 +1920,7 @@ class McpRuntime {
2079
1920
  case "get_sbd_toe_operating_model": {
2080
1921
  const result = handleGetOperatingModel(args);
2081
1922
  this.sendResponse(request.id, {
2082
- content: [{ type: "text", text: JSON.stringify(result) }]
1923
+ content: [{ type: "text", text: this.toolText(result) }]
2083
1924
  });
2084
1925
  await this.log("info", {
2085
1926
  event_type: "tool.call",
@@ -2093,7 +1934,7 @@ class McpRuntime {
2093
1934
  case "get_sbd_toe_verification_matrix": {
2094
1935
  const result = handleGetVerificationMatrix(args);
2095
1936
  this.sendResponse(request.id, {
2096
- content: [{ type: "text", text: JSON.stringify(result) }]
1937
+ content: [{ type: "text", text: this.toolText(result) }]
2097
1938
  });
2098
1939
  await this.log("info", {
2099
1940
  event_type: "tool.call",
@@ -2107,7 +1948,7 @@ class McpRuntime {
2107
1948
  case "assess_sbd_toe_implementation": {
2108
1949
  const result = handleAssessImplementation(args);
2109
1950
  this.sendResponse(request.id, {
2110
- content: [{ type: "text", text: JSON.stringify(result) }]
1951
+ content: [{ type: "text", text: this.toolText(result) }]
2111
1952
  });
2112
1953
  await this.log("info", {
2113
1954
  event_type: "tool.call",
@@ -2121,7 +1962,7 @@ class McpRuntime {
2121
1962
  case "plan_sbd_toe_rollout": {
2122
1963
  const result = handlePlanRollout(args);
2123
1964
  this.sendResponse(request.id, {
2124
- content: [{ type: "text", text: JSON.stringify(result) }]
1965
+ content: [{ type: "text", text: this.toolText(result) }]
2125
1966
  });
2126
1967
  await this.log("info", {
2127
1968
  event_type: "tool.call",
@@ -2135,35 +1976,35 @@ class McpRuntime {
2135
1976
  case "get_sbd_toe_macro_processes": {
2136
1977
  const result = handleGetMacroProcesses(args);
2137
1978
  this.sendResponse(request.id, {
2138
- content: [{ type: "text", text: JSON.stringify(result) }]
1979
+ content: [{ type: "text", text: this.toolText(result) }]
2139
1980
  });
2140
1981
  return;
2141
1982
  }
2142
1983
  case "explain_sbd_toe_topic": {
2143
1984
  const result = handleExplainTopic(args);
2144
1985
  this.sendResponse(request.id, {
2145
- content: [{ type: "text", text: JSON.stringify(result) }]
1986
+ content: [{ type: "text", text: this.toolText(result) }]
2146
1987
  });
2147
1988
  return;
2148
1989
  }
2149
1990
  case "get_sbd_toe_chapter_capability": {
2150
1991
  const result = handleGetChapterCapability(args);
2151
1992
  this.sendResponse(request.id, {
2152
- content: [{ type: "text", text: JSON.stringify(result) }]
1993
+ content: [{ type: "text", text: this.toolText(result) }]
2153
1994
  });
2154
1995
  return;
2155
1996
  }
2156
1997
  case "get_sbd_toe_playbook": {
2157
1998
  const result = handleGetPlaybook(args);
2158
1999
  this.sendResponse(request.id, {
2159
- content: [{ type: "text", text: JSON.stringify(result) }]
2000
+ content: [{ type: "text", text: this.toolText(result) }]
2160
2001
  });
2161
2002
  return;
2162
2003
  }
2163
2004
  case "map_sbd_toe_regulatory_activation": {
2164
2005
  const result = handleMapRegulatoryActivation(args);
2165
2006
  this.sendResponse(request.id, {
2166
- content: [{ type: "text", text: JSON.stringify(result) }]
2007
+ content: [{ type: "text", text: this.toolText(result) }]
2167
2008
  });
2168
2009
  await this.log("info", {
2169
2010
  event_type: "tool.call",
@@ -2177,7 +2018,7 @@ class McpRuntime {
2177
2018
  case "map_sbd_toe_applicability": {
2178
2019
  const result = handleMapSbdToeApplicability(args);
2179
2020
  this.sendResponse(request.id, {
2180
- content: [{ type: "text", text: JSON.stringify(result) }]
2021
+ content: [{ type: "text", text: this.toolText(result) }]
2181
2022
  });
2182
2023
  await this.log("info", {
2183
2024
  event_type: "tool.call",
@@ -2271,7 +2112,7 @@ class McpRuntime {
2271
2112
  case "select_sbd_toe_requirements": {
2272
2113
  const result = handleSelectRequirements(args);
2273
2114
  this.sendResponse(request.id, {
2274
- content: [{ type: "text", text: JSON.stringify(result) }]
2115
+ content: [{ type: "text", text: this.toolText(result) }]
2275
2116
  });
2276
2117
  await this.log("info", {
2277
2118
  event_type: "tool.call",
@@ -2285,7 +2126,7 @@ class McpRuntime {
2285
2126
  case "consult_security_requirements": {
2286
2127
  const result = handleConsultSecurityRequirements(args);
2287
2128
  this.sendResponse(request.id, {
2288
- content: [{ type: "text", text: JSON.stringify(result) }]
2129
+ content: [{ type: "text", text: this.toolText(result) }]
2289
2130
  });
2290
2131
  await this.log("info", {
2291
2132
  event_type: "tool.call",
@@ -2299,7 +2140,7 @@ class McpRuntime {
2299
2140
  case "get_threat_landscape": {
2300
2141
  const result = handleGetThreatLandscape(args);
2301
2142
  this.sendResponse(request.id, {
2302
- content: [{ type: "text", text: JSON.stringify(result) }]
2143
+ content: [{ type: "text", text: this.toolText(result) }]
2303
2144
  });
2304
2145
  await this.log("info", {
2305
2146
  event_type: "tool.call",
@@ -2313,7 +2154,7 @@ class McpRuntime {
2313
2154
  case "get_guide_by_role": {
2314
2155
  const result = handleGetGuideByRole(args);
2315
2156
  this.sendResponse(request.id, {
2316
- content: [{ type: "text", text: JSON.stringify(result) }]
2157
+ content: [{ type: "text", text: this.toolText(result) }]
2317
2158
  });
2318
2159
  await this.log("info", {
2319
2160
  event_type: "tool.call",
@@ -2327,7 +2168,7 @@ class McpRuntime {
2327
2168
  case "resolve_entities": {
2328
2169
  const result = handleResolveEntities(args);
2329
2170
  this.sendResponse(request.id, {
2330
- content: [{ type: "text", text: JSON.stringify(result) }]
2171
+ content: [{ type: "text", text: this.toolText(result) }]
2331
2172
  });
2332
2173
  await this.log("info", {
2333
2174
  event_type: "tool.call",
@@ -2341,7 +2182,7 @@ class McpRuntime {
2341
2182
  case "trace_sbd_toe_graph": {
2342
2183
  const result = handleTraceGraph(args);
2343
2184
  this.sendResponse(request.id, {
2344
- content: [{ type: "text", text: JSON.stringify(result) }]
2185
+ content: [{ type: "text", text: this.toolText(result) }]
2345
2186
  });
2346
2187
  await this.log("info", {
2347
2188
  event_type: "tool.call",
@@ -2355,7 +2196,7 @@ class McpRuntime {
2355
2196
  case "prepare_sbd_toe_codegen_context": {
2356
2197
  const result = handlePrepareCodegenContext(args);
2357
2198
  this.sendResponse(request.id, {
2358
- content: [{ type: "text", text: JSON.stringify(result) }]
2199
+ content: [{ type: "text", text: this.toolText(result) }]
2359
2200
  });
2360
2201
  await this.log("info", {
2361
2202
  event_type: "tool.call",