gft-pharos-mcp 0.3.0 → 0.3.4
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.
- package/index.js +593 -188
- package/package.json +1 -1
- package/test/busca-paginas.test.js +216 -0
- package/test/index.test.js +45 -37
- package/test/mastercard.test.js +290 -0
- package/test/modo-teste.test.js +60 -0
- package/test/runbook.test.js +452 -0
- package/test/um-cliente.test.js +208 -0
package/package.json
CHANGED
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Busca com as páginas do runbook (include=pages). As chamadas passam pelo callApi de verdade, com
|
|
3
|
+
* o fetch trocado por um stub que responde como o Pharos e guarda os parâmetros de cada busca.
|
|
4
|
+
*/
|
|
5
|
+
import { describe, it, afterEach } from "node:test";
|
|
6
|
+
import assert from "node:assert/strict";
|
|
7
|
+
|
|
8
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
9
|
+
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
10
|
+
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
|
|
11
|
+
|
|
12
|
+
import { registerPharosTools, ClientSession, CLIENT_HEADER, isPageHit, searchWithPages } from "../index.js";
|
|
13
|
+
|
|
14
|
+
const RASTRO_VISA = /\bvisa\b|VISA_|verifi/i;
|
|
15
|
+
|
|
16
|
+
const ENTRADA = {
|
|
17
|
+
chunkId: "c1",
|
|
18
|
+
entryId: "11111111-1111-4111-8111-111111111111",
|
|
19
|
+
title: "Erro 401 no sandbox",
|
|
20
|
+
product: "MDES",
|
|
21
|
+
source: "AGENT",
|
|
22
|
+
tags: ["sandbox"],
|
|
23
|
+
text: "trecho da entrada",
|
|
24
|
+
cosineSimilarity: 0.812,
|
|
25
|
+
type: "entry",
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
const PAGINA = {
|
|
29
|
+
chunkId: "c2",
|
|
30
|
+
entryId: null,
|
|
31
|
+
title: "Go-live",
|
|
32
|
+
product: null,
|
|
33
|
+
source: "RUNBOOK",
|
|
34
|
+
tags: [],
|
|
35
|
+
text: "trecho da página",
|
|
36
|
+
cosineSimilarity: 0.774,
|
|
37
|
+
type: "page",
|
|
38
|
+
pageId: "22222222-2222-4222-8222-222222222222",
|
|
39
|
+
pageSlug: "go-live",
|
|
40
|
+
anchor: "checklist-final",
|
|
41
|
+
heading: "Checklist final",
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
/** Entrada como o Pharos anterior ao runbook devolve: sem `type`. */
|
|
45
|
+
const ENTRADA_ANTIGA = { ...ENTRADA, type: undefined };
|
|
46
|
+
|
|
47
|
+
const INCLUDE_DESCONHECIDO = {
|
|
48
|
+
status: 400,
|
|
49
|
+
body: { title: "Requisicao invalida", detail: "include aceita apenas: pages" },
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
const originalFetch = globalThis.fetch;
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Troca o fetch: `responder(params)` devolve { status, body } para cada GET /search. Guarda os
|
|
56
|
+
* parâmetros e os headers de cada chamada.
|
|
57
|
+
*/
|
|
58
|
+
function stubBusca(responder) {
|
|
59
|
+
const chamadas = [];
|
|
60
|
+
globalThis.fetch = async (url, init) => {
|
|
61
|
+
const { pathname, searchParams } = new URL(url);
|
|
62
|
+
chamadas.push({ path: pathname.replace(/^\/api\/v1/, ""), params: searchParams, headers: init.headers });
|
|
63
|
+
const { status, body } = responder(searchParams);
|
|
64
|
+
return new Response(JSON.stringify(body), { status });
|
|
65
|
+
};
|
|
66
|
+
return chamadas;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
afterEach(() => {
|
|
70
|
+
globalThis.fetch = originalFetch;
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
const sessaoFixa = (client) =>
|
|
74
|
+
new ClientSession(client, async () => {
|
|
75
|
+
throw new Error("não deveria descobrir");
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
async function conectar(client) {
|
|
79
|
+
const server = new McpServer({ name: "pharos-teste", version: "0.0.0" });
|
|
80
|
+
registerPharosTools(server, { client, clientSession: sessaoFixa(client) });
|
|
81
|
+
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
|
|
82
|
+
await server.connect(serverTransport);
|
|
83
|
+
const mcp = new Client({ name: "teste", version: "0.0.0" });
|
|
84
|
+
await mcp.connect(clientTransport);
|
|
85
|
+
return mcp;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
async function buscar(mcp, args) {
|
|
89
|
+
try {
|
|
90
|
+
const r = await mcp.callTool({ name: "search_knowledge", arguments: args });
|
|
91
|
+
return { isError: Boolean(r.isError), text: r.content.map((c) => c.text).join("\n") };
|
|
92
|
+
} catch (err) {
|
|
93
|
+
return { isError: true, text: err.message };
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
describe("search_knowledge com as páginas do runbook", () => {
|
|
98
|
+
it("pede include=pages e separa os trechos de página dos de entrada", async () => {
|
|
99
|
+
const chamadas = stubBusca(() => ({ status: 200, body: { total: 2, hits: [PAGINA, ENTRADA] } }));
|
|
100
|
+
const mcp = await conectar("mastercard");
|
|
101
|
+
const r = await buscar(mcp, { query: "checklist de go-live", topK: 4 });
|
|
102
|
+
|
|
103
|
+
assert.equal(r.isError, false, r.text);
|
|
104
|
+
assert.equal(chamadas.length, 1);
|
|
105
|
+
assert.equal(chamadas[0].path, "/search");
|
|
106
|
+
assert.equal(chamadas[0].params.get("include"), "pages");
|
|
107
|
+
assert.equal(chamadas[0].params.get("q"), "checklist de go-live");
|
|
108
|
+
assert.equal(chamadas[0].params.get("client"), "mastercard");
|
|
109
|
+
assert.equal(chamadas[0].params.get("topK"), "4");
|
|
110
|
+
assert.equal(chamadas[0].headers[CLIENT_HEADER], "mastercard");
|
|
111
|
+
|
|
112
|
+
assert.match(r.text, /^2 trecho\(s\) da base do Pharos/);
|
|
113
|
+
assert.match(
|
|
114
|
+
r.text,
|
|
115
|
+
/## \[1\] Erro 401 no sandbox\nCliente: mastercard \| Produto: MDES \| Fonte: entrada 11111111-1111-4111-8111-111111111111 \(registrada por um dev\) \| Similaridade: 0\.812\nTags: sandbox\n\ntrecho da entrada/
|
|
116
|
+
);
|
|
117
|
+
assert.match(r.text, /Do runbook do time \(páginas publicadas\):/);
|
|
118
|
+
assert.match(r.text, /## \[2\] Do runbook: Go-live \(página go-live#checklist-final\)/);
|
|
119
|
+
assert.match(r.text, /Cliente: mastercard \| Fonte: runbook \| Seção: Checklist final \| Similaridade: 0\.774/);
|
|
120
|
+
assert.match(r.text, /trecho da página/);
|
|
121
|
+
assert.match(r.text, /use read_runbook_page com o slug "go-live"/);
|
|
122
|
+
assert.ok(r.text.indexOf("Erro 401 no sandbox") < r.text.indexOf("Do runbook:"), "entradas antes das páginas");
|
|
123
|
+
assert.doesNotMatch(r.text, /entrada null|\(sem id\)/);
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
it("só entradas: mesmo formato de antes, sem bloco do runbook", async () => {
|
|
127
|
+
stubBusca(() => ({ status: 200, body: { total: 1, hits: [ENTRADA] } }));
|
|
128
|
+
const mcp = await conectar("mastercard");
|
|
129
|
+
const r = await buscar(mcp, { query: "401" });
|
|
130
|
+
|
|
131
|
+
assert.equal(r.isError, false, r.text);
|
|
132
|
+
assert.match(r.text, /## \[1\] Erro 401 no sandbox\nCliente: mastercard \| Produto: MDES/);
|
|
133
|
+
assert.doesNotMatch(r.text, /runbook/i);
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
it("só páginas: lista o bloco do runbook sem bloco de entradas vazio", async () => {
|
|
137
|
+
stubBusca(() => ({ status: 200, body: { total: 1, hits: [{ ...PAGINA, anchor: null, heading: null }] } }));
|
|
138
|
+
const mcp = await conectar("visa");
|
|
139
|
+
const r = await buscar(mcp, { query: "go-live" });
|
|
140
|
+
|
|
141
|
+
assert.equal(r.isError, false, r.text);
|
|
142
|
+
assert.match(r.text, /:\n\nDo runbook do time \(páginas publicadas\):\n\n## \[1\] Do runbook: Go-live \(página go-live\)\n/);
|
|
143
|
+
assert.match(r.text, /Cliente: visa \| Fonte: runbook \| Similaridade: 0\.774/);
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
it("Pharos antigo (400 por include desconhecido): refaz a busca sem include", async () => {
|
|
147
|
+
const chamadas = stubBusca((params) =>
|
|
148
|
+
params.has("include") ? INCLUDE_DESCONHECIDO : { status: 200, body: { total: 1, hits: [ENTRADA_ANTIGA] } }
|
|
149
|
+
);
|
|
150
|
+
const mcp = await conectar("mastercard");
|
|
151
|
+
const r = await buscar(mcp, { query: "401", product: "MDES" });
|
|
152
|
+
|
|
153
|
+
assert.equal(r.isError, false, r.text);
|
|
154
|
+
assert.equal(chamadas.length, 2);
|
|
155
|
+
assert.equal(chamadas[0].params.get("include"), "pages");
|
|
156
|
+
assert.equal(chamadas[1].params.has("include"), false);
|
|
157
|
+
assert.equal(chamadas[1].params.get("q"), "401");
|
|
158
|
+
assert.equal(chamadas[1].params.get("product"), "MDES");
|
|
159
|
+
assert.equal(chamadas[1].headers[CLIENT_HEADER], "mastercard");
|
|
160
|
+
assert.match(r.text, /## \[1\] Erro 401 no sandbox/);
|
|
161
|
+
assert.doesNotMatch(r.text, /include aceita|Pharos respondeu 400/);
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
it("400 que não é do include segue como erro, sem refazer a busca", async () => {
|
|
165
|
+
const chamadas = stubBusca(() => ({ status: 400, body: { detail: "q é obrigatório" } }));
|
|
166
|
+
const mcp = await conectar("mastercard");
|
|
167
|
+
const r = await buscar(mcp, { query: "x" });
|
|
168
|
+
|
|
169
|
+
assert.equal(r.isError, true);
|
|
170
|
+
assert.match(r.text, /Pharos respondeu 400: q é obrigatório/);
|
|
171
|
+
assert.equal(chamadas.length, 1);
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
it("módulo desligado: o Pharos só devolve entradas e a busca sai como hoje", async () => {
|
|
175
|
+
const chamadas = stubBusca(() => ({ status: 200, body: { total: 1, hits: [ENTRADA] } }));
|
|
176
|
+
const mcp = await conectar("visa");
|
|
177
|
+
const r = await buscar(mcp, { query: "payout" });
|
|
178
|
+
|
|
179
|
+
assert.equal(r.isError, false, r.text);
|
|
180
|
+
assert.equal(chamadas.length, 1);
|
|
181
|
+
assert.equal(chamadas[0].params.get("include"), "pages");
|
|
182
|
+
assert.doesNotMatch(r.text, /Do runbook/);
|
|
183
|
+
});
|
|
184
|
+
|
|
185
|
+
it("sem trechos: mantém a sugestão de registrar a solução", async () => {
|
|
186
|
+
stubBusca(() => ({ status: 200, body: { total: 0, hits: [] } }));
|
|
187
|
+
const mcp = await conectar("visa");
|
|
188
|
+
const r = await buscar(mcp, { query: "nada" });
|
|
189
|
+
assert.match(r.text, /Nenhum trecho encontrado/);
|
|
190
|
+
});
|
|
191
|
+
|
|
192
|
+
it("sessão Mastercard: hit de página sem rastro de outro cliente", async () => {
|
|
193
|
+
stubBusca(() => ({ status: 200, body: { total: 2, hits: [ENTRADA, PAGINA] } }));
|
|
194
|
+
const mcp = await conectar("mastercard");
|
|
195
|
+
const r = await buscar(mcp, { query: "go-live" });
|
|
196
|
+
assert.doesNotMatch(r.text, RASTRO_VISA);
|
|
197
|
+
assert.doesNotMatch(r.text, /outro cliente/i);
|
|
198
|
+
});
|
|
199
|
+
|
|
200
|
+
it("isPageHit: só type page; hit sem type é entrada", () => {
|
|
201
|
+
assert.equal(isPageHit(PAGINA), true);
|
|
202
|
+
assert.equal(isPageHit(ENTRADA), false);
|
|
203
|
+
assert.equal(isPageHit(ENTRADA_ANTIGA), false);
|
|
204
|
+
assert.equal(isPageHit(null), false);
|
|
205
|
+
});
|
|
206
|
+
|
|
207
|
+
it("searchWithPages não refaz a busca em erro que não é 400", async () => {
|
|
208
|
+
let chamadas = 0;
|
|
209
|
+
const call = async () => {
|
|
210
|
+
chamadas += 1;
|
|
211
|
+
throw Object.assign(new Error("Pharos respondeu 500: include"), { status: 500 });
|
|
212
|
+
};
|
|
213
|
+
await assert.rejects(searchWithPages(call, new URLSearchParams({ q: "x" }), {}), /500/);
|
|
214
|
+
assert.equal(chamadas, 1);
|
|
215
|
+
});
|
|
216
|
+
});
|
package/test/index.test.js
CHANGED
|
@@ -11,12 +11,11 @@ import {
|
|
|
11
11
|
parseApiKey,
|
|
12
12
|
parseTimeout,
|
|
13
13
|
parseClient,
|
|
14
|
-
PRODUCTS,
|
|
15
14
|
PRODUCTS_BY_CLIENT,
|
|
16
15
|
CLIENTS,
|
|
17
16
|
assertProductForClient,
|
|
18
|
-
|
|
19
|
-
|
|
17
|
+
productEnumFor,
|
|
18
|
+
clientEnumFor,
|
|
20
19
|
server,
|
|
21
20
|
officialToolName,
|
|
22
21
|
registerOfficialTools,
|
|
@@ -136,24 +135,27 @@ describe("gft-pharos-mcp 0.2.0 - Validações e Correções de Bugs", () => {
|
|
|
136
135
|
]);
|
|
137
136
|
});
|
|
138
137
|
|
|
139
|
-
it("
|
|
140
|
-
|
|
141
|
-
assert.equal(
|
|
142
|
-
assert.
|
|
143
|
-
assert.
|
|
138
|
+
it("productEnumFor deve aceitar só o catálogo do cliente e rejeitar typos como CLICK_TO_PAI", () => {
|
|
139
|
+
const mastercard = productEnumFor("mastercard");
|
|
140
|
+
assert.equal(mastercard.parse("CLICK_TO_PAY"), "CLICK_TO_PAY");
|
|
141
|
+
assert.equal(mastercard.parse("MASTERCARD_SEND"), "MASTERCARD_SEND");
|
|
142
|
+
assert.throws(() => mastercard.parse("VISA_TOKEN_SERVICE"));
|
|
143
|
+
assert.throws(() => mastercard.parse("CLICK_TO_PAI"));
|
|
144
|
+
const visa = productEnumFor("visa");
|
|
145
|
+
assert.equal(visa.parse("VISA_TOKEN_SERVICE"), "VISA_TOKEN_SERVICE");
|
|
146
|
+
assert.throws(() => visa.parse("MDES"));
|
|
144
147
|
});
|
|
145
148
|
|
|
146
|
-
it("
|
|
147
|
-
assert.
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
assert.throws(() => assertProductForClient("mastercard", "VISA_DIRECT"), /VISA_DIRECT/);
|
|
149
|
+
it("assertProductForClient deve barrar produto fora do catálogo sem citar o outro cliente", () => {
|
|
150
|
+
assert.throws(() => assertProductForClient("visa", "MDES"), (err) => {
|
|
151
|
+
assert.match(err.message, /não faz parte do catálogo deste projeto/);
|
|
152
|
+
assert.doesNotMatch(err.message, /mastercard|MDES|ethoca/i);
|
|
153
|
+
return true;
|
|
154
|
+
});
|
|
155
|
+
assert.throws(() => assertProductForClient("mastercard", "VISA_DIRECT"), (err) => {
|
|
156
|
+
assert.doesNotMatch(err.message, /\bvisa\b|VISA_|verifi/i);
|
|
157
|
+
return true;
|
|
158
|
+
});
|
|
157
159
|
});
|
|
158
160
|
|
|
159
161
|
it("assertProductForClient deve aceitar produto comum e não julgar sem client", () => {
|
|
@@ -163,10 +165,10 @@ describe("gft-pharos-mcp 0.2.0 - Validações e Correções de Bugs", () => {
|
|
|
163
165
|
assert.doesNotThrow(() => assertProductForClient("visa", undefined));
|
|
164
166
|
});
|
|
165
167
|
|
|
166
|
-
it("
|
|
167
|
-
assert.equal(
|
|
168
|
-
assert.
|
|
169
|
-
assert.throws(() =>
|
|
168
|
+
it("clientEnumFor deve aceitar só o cliente da sessão", () => {
|
|
169
|
+
assert.equal(clientEnumFor("visa").parse("visa"), "visa");
|
|
170
|
+
assert.throws(() => clientEnumFor("visa").parse("mastercard"));
|
|
171
|
+
assert.throws(() => clientEnumFor("mastercard").parse("elo"));
|
|
170
172
|
});
|
|
171
173
|
});
|
|
172
174
|
|
|
@@ -184,10 +186,15 @@ describe("gft-pharos-mcp 0.2.0 - Validações e Correções de Bugs", () => {
|
|
|
184
186
|
assert.equal(parseClient(" VISA "), "visa");
|
|
185
187
|
});
|
|
186
188
|
|
|
187
|
-
it("parseClient deve devolver null quando omitido e falhar
|
|
189
|
+
it("parseClient deve devolver null quando omitido, aceitar id bem formado e falhar no mal formado", () => {
|
|
188
190
|
assert.equal(parseClient(undefined), null);
|
|
189
191
|
assert.equal(parseClient(""), null);
|
|
190
|
-
|
|
192
|
+
// Quem recusa cliente inexistente e o Pharos: a lista de clientes nao fica no MCP.
|
|
193
|
+
assert.equal(parseClient("elo"), "elo");
|
|
194
|
+
assert.equal(parseClient("cliente-2"), "cliente-2");
|
|
195
|
+
assert.throws(() => parseClient("elo verde"), /PHAROS_CLIENT invalido/);
|
|
196
|
+
assert.throws(() => parseClient("-elo"), /PHAROS_CLIENT invalido/);
|
|
197
|
+
assert.throws(() => parseClient("elo_x"), /PHAROS_CLIENT invalido/);
|
|
191
198
|
// Sem apelido: "master" virou "mastercard" e a mensagem diz o que fazer.
|
|
192
199
|
assert.throws(() => parseClient("master"), /nao existe mais/);
|
|
193
200
|
});
|
|
@@ -289,7 +296,7 @@ describe("gft-pharos-mcp 0.2.0 - Validações e Correções de Bugs", () => {
|
|
|
289
296
|
);
|
|
290
297
|
await assert.rejects(
|
|
291
298
|
() => discoverAccountClient(async () => ({ activeTenant: null, availableTenants: [] })),
|
|
292
|
-
/não tem acesso
|
|
299
|
+
/ainda não tem acesso ao Pharos/
|
|
293
300
|
);
|
|
294
301
|
});
|
|
295
302
|
|
|
@@ -331,21 +338,22 @@ describe("gft-pharos-mcp 0.2.0 - Validações e Correções de Bugs", () => {
|
|
|
331
338
|
it("PHAROS_CLIENT diferente do cliente da chave: 403 vira instrução de gerar a chave certa", async () => {
|
|
332
339
|
const original = globalThis.fetch;
|
|
333
340
|
let headers;
|
|
341
|
+
let detail;
|
|
334
342
|
globalThis.fetch = async (_url, init) => {
|
|
335
343
|
headers = init.headers;
|
|
336
|
-
return new Response(
|
|
337
|
-
JSON.stringify({
|
|
338
|
-
detail:
|
|
339
|
-
"Esta chave de API é de outro cliente. Gere na tela Conectar do Pharos a chave do cliente deste projeto.",
|
|
340
|
-
}),
|
|
341
|
-
{ status: 403 }
|
|
342
|
-
);
|
|
344
|
+
return new Response(JSON.stringify({ detail }), { status: 403 });
|
|
343
345
|
};
|
|
344
346
|
try {
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
347
|
+
// Texto atual do Pharos e o anterior a regra N3 (servidor ainda nao atualizado).
|
|
348
|
+
for (detail of [
|
|
349
|
+
"Esta chave de API não vale para este acesso. Gere na tela Conectar do Pharos a chave deste projeto.",
|
|
350
|
+
"Esta chave de API é de outro cliente. Gere na tela Conectar do Pharos a chave do cliente deste projeto.",
|
|
351
|
+
]) {
|
|
352
|
+
await assert.rejects(
|
|
353
|
+
() => callApi("/search?q=x", { headers: clientHeaders("mastercard") }),
|
|
354
|
+
(err) => err.message === keyOfOtherClientMessage("mastercard")
|
|
355
|
+
);
|
|
356
|
+
}
|
|
349
357
|
assert.equal(headers[CLIENT_HEADER], "mastercard");
|
|
350
358
|
assert.match(keyOfOtherClientMessage("mastercard"), /tela Conectar/);
|
|
351
359
|
assert.match(keyOfOtherClientMessage("mastercard"), /"mastercard"/);
|
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Sessão Mastercard do gft-pharos-mcp de ponta a ponta: sobe o `index.js` como processo filho (como o
|
|
3
|
+
* editor faz), fala com ele pelo cliente stdio do SDK e troca a API do Pharos por um stub HTTP
|
|
4
|
+
* local que guarda cada chamada. Assim o PHAROS_CLIENT, a descoberta do cliente pela chave e o
|
|
5
|
+
* registro das tools `mastercard_*` são exercitados como na máquina do dev, sem rede.
|
|
6
|
+
*/
|
|
7
|
+
import { after, before, describe, it } from "node:test";
|
|
8
|
+
import assert from "node:assert/strict";
|
|
9
|
+
import http from "node:http";
|
|
10
|
+
import { fileURLToPath } from "node:url";
|
|
11
|
+
|
|
12
|
+
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
13
|
+
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
|
|
14
|
+
|
|
15
|
+
const INDEX = fileURLToPath(new URL("../index.js", import.meta.url));
|
|
16
|
+
const CHAVE = "pharos_sk_teste_mastercard";
|
|
17
|
+
|
|
18
|
+
/** Stub da API do Pharos: responde por rota e guarda método, caminho, headers e corpo. */
|
|
19
|
+
function stubPharos({ tenantView, status = {} }) {
|
|
20
|
+
const calls = [];
|
|
21
|
+
const server = http.createServer((req, res) => {
|
|
22
|
+
let body = "";
|
|
23
|
+
req.on("data", (c) => (body += c));
|
|
24
|
+
req.on("end", () => {
|
|
25
|
+
const url = new URL(req.url, "http://stub");
|
|
26
|
+
calls.push({ method: req.method, path: url.pathname, params: url.searchParams, headers: req.headers, body });
|
|
27
|
+
const send = (code, payload) => {
|
|
28
|
+
res.writeHead(code, { "content-type": "application/json" });
|
|
29
|
+
res.end(JSON.stringify(payload));
|
|
30
|
+
};
|
|
31
|
+
const forced = status[url.pathname];
|
|
32
|
+
if (forced) return send(forced.code, forced.body);
|
|
33
|
+
if (url.pathname === "/api/v1/tenant") return send(200, tenantView);
|
|
34
|
+
if (url.pathname === "/api/v1/search") {
|
|
35
|
+
return send(200, {
|
|
36
|
+
hits: [
|
|
37
|
+
{
|
|
38
|
+
entryId: "11111111-1111-1111-1111-111111111111",
|
|
39
|
+
title: "Tokenização no MDES",
|
|
40
|
+
product: "MDES",
|
|
41
|
+
text: "trecho da base da Mastercard",
|
|
42
|
+
cosineSimilarity: 0.91,
|
|
43
|
+
tags: ["mdes"],
|
|
44
|
+
},
|
|
45
|
+
],
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
if (url.pathname === "/api/v1/entries" && req.method === "POST") {
|
|
49
|
+
return send(201, { id: "22222222-2222-2222-2222-222222222222", status: "PENDING" });
|
|
50
|
+
}
|
|
51
|
+
return send(404, { detail: "rota desconhecida no stub" });
|
|
52
|
+
});
|
|
53
|
+
});
|
|
54
|
+
return new Promise((resolve) => {
|
|
55
|
+
server.listen(0, "127.0.0.1", () => {
|
|
56
|
+
resolve({ calls, url: `http://127.0.0.1:${server.address().port}`, close: () => server.close() });
|
|
57
|
+
});
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Sobe o servidor MCP como o editor sobe, com o env do .mcp.json do projeto. */
|
|
62
|
+
async function subirMcp(env) {
|
|
63
|
+
const childEnv = { PATH: process.env.PATH, HOME: process.env.HOME, PHAROS_TIMEOUT_MS: "3000", ...env };
|
|
64
|
+
// O `npm test` exporta NODE_ENV=test; herdado, o filho não conectaria o stdio.
|
|
65
|
+
delete childEnv.NODE_ENV;
|
|
66
|
+
const transport = new StdioClientTransport({ command: process.execPath, args: [INDEX], env: childEnv, stderr: "pipe" });
|
|
67
|
+
const client = new Client({ name: "teste-mastercard", version: "0.0.0" });
|
|
68
|
+
await client.connect(transport);
|
|
69
|
+
return client;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function texto(result) {
|
|
73
|
+
return result.content.map((c) => c.text).join("\n");
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const chamadasPara = (calls, path) => calls.filter((c) => c.path === path);
|
|
77
|
+
|
|
78
|
+
describe("gft-pharos-mcp: sessão Mastercard de ponta a ponta", { timeout: 60_000 }, () => {
|
|
79
|
+
describe("com PHAROS_CLIENT=mastercard", () => {
|
|
80
|
+
let stub;
|
|
81
|
+
let mcp;
|
|
82
|
+
|
|
83
|
+
before(async () => {
|
|
84
|
+
stub = await stubPharos({ tenantView: { activeTenant: "mastercard", availableTenants: ["mastercard"] } });
|
|
85
|
+
mcp = await subirMcp({ PHAROS_API_URL: stub.url, PHAROS_API_KEY: CHAVE, PHAROS_CLIENT: "mastercard" });
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
after(async () => {
|
|
89
|
+
await mcp?.close();
|
|
90
|
+
stub?.close();
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
it("oferece as tools da base e as oficiais mastercard_* no mesmo servidor", async () => {
|
|
94
|
+
const { tools } = await mcp.listTools();
|
|
95
|
+
const nomes = tools.map((t) => t.name);
|
|
96
|
+
assert.ok(nomes.includes("search_knowledge"));
|
|
97
|
+
assert.ok(nomes.includes("register_solution"));
|
|
98
|
+
const oficiais = nomes.filter((n) => n.startsWith("mastercard_"));
|
|
99
|
+
assert.ok(oficiais.length >= 9, `esperava ao menos 9 tools oficiais, veio ${oficiais.length}`);
|
|
100
|
+
assert.ok(oficiais.includes("mastercard_get_services_list"));
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
it("search_knowledge vai à Mastercard com a chave, o client e o seletor, sem descobrir o cliente", async () => {
|
|
104
|
+
const antes = stub.calls.length;
|
|
105
|
+
const result = await mcp.callTool({ name: "search_knowledge", arguments: { query: "tokenizar no MDES" } });
|
|
106
|
+
|
|
107
|
+
assert.ok(!result.isError, texto(result));
|
|
108
|
+
const novas = stub.calls.slice(antes);
|
|
109
|
+
const busca = chamadasPara(novas, "/api/v1/search");
|
|
110
|
+
assert.equal(busca.length, 1);
|
|
111
|
+
assert.equal(busca[0].params.get("q"), "tokenizar no MDES");
|
|
112
|
+
assert.equal(busca[0].params.get("client"), "mastercard");
|
|
113
|
+
assert.equal(busca[0].headers["x-pharos-client"], "mastercard");
|
|
114
|
+
assert.equal(busca[0].headers["x-api-key"], CHAVE);
|
|
115
|
+
assert.equal(chamadasPara(stub.calls, "/api/v1/tenant").length, 0, "PHAROS_CLIENT fixo não consulta /tenant");
|
|
116
|
+
assert.match(texto(result), /Cliente: mastercard \| Produto: MDES/);
|
|
117
|
+
assert.match(texto(result), /trecho da base da Mastercard/);
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
it("search_knowledge com client visa é recusado sem chamar a API", async () => {
|
|
121
|
+
const antes = stub.calls.length;
|
|
122
|
+
const result = await mcp.callTool({ name: "search_knowledge", arguments: { query: "x", client: "visa" } });
|
|
123
|
+
|
|
124
|
+
assert.equal(result.isError, true);
|
|
125
|
+
// Desde a 0.3.1 o schema da sessao so aceita o cliente dela: a recusa vem da validacao.
|
|
126
|
+
assert.match(texto(result), /Invalid enum value/);
|
|
127
|
+
assert.equal(stub.calls.length, antes);
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
it("produto da Visa numa sessão Mastercard é recusado sem chamar a API", async () => {
|
|
131
|
+
const antes = stub.calls.length;
|
|
132
|
+
const result = await mcp.callTool({
|
|
133
|
+
name: "search_knowledge",
|
|
134
|
+
arguments: { query: "x", product: "VISA_DIRECT" },
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
assert.equal(result.isError, true);
|
|
138
|
+
// Desde a 0.3.1 o enum de produto e so o catalogo da sessao: a recusa vem da validacao.
|
|
139
|
+
assert.match(texto(result), /Invalid enum value/);
|
|
140
|
+
assert.doesNotMatch(texto(result), /VISA_TOKEN|VERIFI/);
|
|
141
|
+
assert.equal(stub.calls.length, antes);
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
it("register_solution grava PENDING na Mastercard com source AGENT e avisa que aguarda revisão", async () => {
|
|
145
|
+
const antes = stub.calls.length;
|
|
146
|
+
const result = await mcp.callTool({
|
|
147
|
+
name: "register_solution",
|
|
148
|
+
arguments: { title: "Erro de JWE", problem: "falha ao decifrar", solution: "usar RSA-OAEP-256", product: "MDES" },
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
assert.ok(!result.isError, texto(result));
|
|
152
|
+
const post = chamadasPara(stub.calls.slice(antes), "/api/v1/entries");
|
|
153
|
+
assert.equal(post.length, 1);
|
|
154
|
+
assert.equal(post[0].method, "POST");
|
|
155
|
+
assert.equal(post[0].headers["x-pharos-client"], "mastercard");
|
|
156
|
+
const corpo = JSON.parse(post[0].body);
|
|
157
|
+
assert.equal(corpo.client, "mastercard");
|
|
158
|
+
assert.equal(corpo.product, "MDES");
|
|
159
|
+
assert.equal(corpo.source, "AGENT");
|
|
160
|
+
assert.match(texto(result), /status PENDING/);
|
|
161
|
+
assert.match(texto(result), /AGUARDANDO REVISÃO/);
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
it("register_solution com produto da Visa é recusado sem gravar nada", async () => {
|
|
165
|
+
const antes = stub.calls.length;
|
|
166
|
+
const result = await mcp.callTool({
|
|
167
|
+
name: "register_solution",
|
|
168
|
+
arguments: { title: "t", problem: "p", solution: "s", product: "VERIFI_RDR" },
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
assert.equal(result.isError, true);
|
|
172
|
+
assert.equal(stub.calls.length, antes);
|
|
173
|
+
});
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
describe("sem PHAROS_CLIENT, com a chave presa à Mastercard", () => {
|
|
177
|
+
let stub;
|
|
178
|
+
let mcp;
|
|
179
|
+
|
|
180
|
+
before(async () => {
|
|
181
|
+
stub = await stubPharos({ tenantView: { activeTenant: "mastercard", availableTenants: ["mastercard"] } });
|
|
182
|
+
mcp = await subirMcp({ PHAROS_API_URL: stub.url, PHAROS_API_KEY: CHAVE });
|
|
183
|
+
});
|
|
184
|
+
|
|
185
|
+
after(async () => {
|
|
186
|
+
await mcp?.close();
|
|
187
|
+
stub?.close();
|
|
188
|
+
});
|
|
189
|
+
|
|
190
|
+
it("descobre a Mastercard uma vez na subida, registra as oficiais e trava a sessão nela", async () => {
|
|
191
|
+
const { tools } = await mcp.listTools();
|
|
192
|
+
assert.ok(tools.some((t) => t.name.startsWith("mastercard_")));
|
|
193
|
+
|
|
194
|
+
const ok = await mcp.callTool({ name: "search_knowledge", arguments: { query: "mdes" } });
|
|
195
|
+
const recusada = await mcp.callTool({ name: "search_knowledge", arguments: { query: "x", client: "visa" } });
|
|
196
|
+
|
|
197
|
+
assert.ok(!ok.isError, texto(ok));
|
|
198
|
+
assert.equal(recusada.isError, true);
|
|
199
|
+
const busca = chamadasPara(stub.calls, "/api/v1/search");
|
|
200
|
+
assert.equal(busca.length, 1);
|
|
201
|
+
assert.equal(busca[0].headers["x-pharos-client"], "mastercard");
|
|
202
|
+
assert.equal(chamadasPara(stub.calls, "/api/v1/tenant").length, 1, "o cliente é descoberto uma vez só");
|
|
203
|
+
});
|
|
204
|
+
});
|
|
205
|
+
|
|
206
|
+
describe("sem PHAROS_CLIENT, com conta de dois clientes (Admin GFT com chave antiga)", () => {
|
|
207
|
+
let stub;
|
|
208
|
+
let mcp;
|
|
209
|
+
|
|
210
|
+
before(async () => {
|
|
211
|
+
stub = await stubPharos({ tenantView: { activeTenant: null, availableTenants: ["mastercard", "visa"] } });
|
|
212
|
+
mcp = await subirMcp({ PHAROS_API_URL: stub.url, PHAROS_API_KEY: CHAVE });
|
|
213
|
+
});
|
|
214
|
+
|
|
215
|
+
after(async () => {
|
|
216
|
+
await mcp?.close();
|
|
217
|
+
stub?.close();
|
|
218
|
+
});
|
|
219
|
+
|
|
220
|
+
it("não registra as tools oficiais e pede o PHAROS_CLIENT em vez de escolher sozinho", async () => {
|
|
221
|
+
const { tools } = await mcp.listTools();
|
|
222
|
+
assert.equal(tools.filter((t) => t.name.startsWith("mastercard_")).length, 0);
|
|
223
|
+
|
|
224
|
+
const result = await mcp.callTool({ name: "search_knowledge", arguments: { query: "x", client: "mastercard" } });
|
|
225
|
+
|
|
226
|
+
assert.equal(result.isError, true);
|
|
227
|
+
assert.match(texto(result), /Configure PHAROS_CLIENT/);
|
|
228
|
+
assert.equal(chamadasPara(stub.calls, "/api/v1/search").length, 0);
|
|
229
|
+
});
|
|
230
|
+
});
|
|
231
|
+
|
|
232
|
+
describe("erros da API numa sessão Mastercard", () => {
|
|
233
|
+
it("API fora do ar: a tool explica que não conectou, sem derrubar o servidor", async () => {
|
|
234
|
+
const stub = await stubPharos({ tenantView: {} });
|
|
235
|
+
const urlFechada = stub.url;
|
|
236
|
+
stub.close();
|
|
237
|
+
const mcp = await subirMcp({ PHAROS_API_URL: urlFechada, PHAROS_API_KEY: CHAVE, PHAROS_CLIENT: "mastercard" });
|
|
238
|
+
try {
|
|
239
|
+
const result = await mcp.callTool({ name: "search_knowledge", arguments: { query: "x" } });
|
|
240
|
+
assert.equal(result.isError, true);
|
|
241
|
+
assert.match(texto(result), /Não consegui conectar ao Pharos/);
|
|
242
|
+
const { tools } = await mcp.listTools();
|
|
243
|
+
assert.ok(tools.some((t) => t.name === "search_knowledge"), "o servidor segue de pé");
|
|
244
|
+
} finally {
|
|
245
|
+
await mcp.close();
|
|
246
|
+
}
|
|
247
|
+
});
|
|
248
|
+
|
|
249
|
+
it("chave revogada (401): a tool manda conferir a chave, sem mostrá-la", async () => {
|
|
250
|
+
const stub = await stubPharos({
|
|
251
|
+
tenantView: {},
|
|
252
|
+
status: { "/api/v1/search": { code: 401, body: { detail: "API Key invalida ou nao configurada" } } },
|
|
253
|
+
});
|
|
254
|
+
const mcp = await subirMcp({ PHAROS_API_URL: stub.url, PHAROS_API_KEY: CHAVE, PHAROS_CLIENT: "mastercard" });
|
|
255
|
+
try {
|
|
256
|
+
const result = await mcp.callTool({ name: "search_knowledge", arguments: { query: "x" } });
|
|
257
|
+
assert.equal(result.isError, true);
|
|
258
|
+
assert.match(texto(result), /chave configurada em PHAROS_API_KEY foi rejeitada/);
|
|
259
|
+
assert.doesNotMatch(texto(result), new RegExp(CHAVE));
|
|
260
|
+
} finally {
|
|
261
|
+
await mcp.close();
|
|
262
|
+
stub.close();
|
|
263
|
+
}
|
|
264
|
+
});
|
|
265
|
+
|
|
266
|
+
it("chave de outro cliente (403): a tool manda gerar a chave da Mastercard", async () => {
|
|
267
|
+
const stub = await stubPharos({
|
|
268
|
+
tenantView: {},
|
|
269
|
+
status: {
|
|
270
|
+
"/api/v1/search": {
|
|
271
|
+
code: 403,
|
|
272
|
+
body: {
|
|
273
|
+
detail:
|
|
274
|
+
"Esta chave de API é de outro cliente. Gere na tela Conectar do Pharos a chave do cliente deste projeto.",
|
|
275
|
+
},
|
|
276
|
+
},
|
|
277
|
+
},
|
|
278
|
+
});
|
|
279
|
+
const mcp = await subirMcp({ PHAROS_API_URL: stub.url, PHAROS_API_KEY: CHAVE, PHAROS_CLIENT: "mastercard" });
|
|
280
|
+
try {
|
|
281
|
+
const result = await mcp.callTool({ name: "search_knowledge", arguments: { query: "x" } });
|
|
282
|
+
assert.equal(result.isError, true);
|
|
283
|
+
assert.match(texto(result), /Gere na tela Conectar do portal a chave do cliente "mastercard"/);
|
|
284
|
+
} finally {
|
|
285
|
+
await mcp.close();
|
|
286
|
+
stub.close();
|
|
287
|
+
}
|
|
288
|
+
});
|
|
289
|
+
});
|
|
290
|
+
});
|