gft-pharos-mcp 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/index.js +196 -0
  2. package/mcp.example.json +20 -0
  3. package/package.json +22 -0
package/index.js ADDED
@@ -0,0 +1,196 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * MCP server do Pharos — proxy fino sobre a API do portal.
4
+ *
5
+ * Decisao central: `search_knowledge` faz APENAS retrieval e devolve os trechos
6
+ * brutos com a fonte. Nao chama modelo nenhum. Quem sintetiza a resposta final e o
7
+ * modelo da sessao do Claude Code, que ja tem o contexto do projeto do dev — chamar
8
+ * Claude aqui seria pagar duas vezes por uma resposta pior, porque este processo nao
9
+ * enxerga o codigo do cliente.
10
+ */
11
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
12
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
13
+ import { z } from "zod";
14
+
15
+ const API_URL = (process.env.PHAROS_API_URL || "http://localhost:8080").replace(/\/$/, "");
16
+ const API_KEY = process.env.PHAROS_API_KEY || "";
17
+ const TIMEOUT_MS = Number(process.env.PHAROS_TIMEOUT_MS || 15000);
18
+
19
+ async function callApi(path, options = {}) {
20
+ const controller = new AbortController();
21
+ const timer = setTimeout(() => controller.abort(), TIMEOUT_MS);
22
+ try {
23
+ const res = await fetch(`${API_URL}/api/v1${path}`, {
24
+ ...options,
25
+ signal: controller.signal,
26
+ headers: {
27
+ "content-type": "application/json",
28
+ ...(API_KEY ? { "X-API-Key": API_KEY } : {}),
29
+ ...(options.headers || {}),
30
+ },
31
+ });
32
+ const text = await res.text();
33
+ if (!res.ok) {
34
+ let detail = text;
35
+ try {
36
+ const problem = JSON.parse(text);
37
+ detail = problem.detail || problem.title || text;
38
+ } catch {
39
+ /* resposta nao-JSON: usa o corpo cru */
40
+ }
41
+ throw new Error(`Pharos respondeu ${res.status}: ${detail}`);
42
+ }
43
+ return text ? JSON.parse(text) : null;
44
+ } catch (err) {
45
+ if (err.name === "AbortError") {
46
+ throw new Error(`Pharos nao respondeu em ${TIMEOUT_MS}ms (${API_URL}).`);
47
+ }
48
+ if (err.cause?.code === "ECONNREFUSED") {
49
+ throw new Error(
50
+ `Nao consegui conectar ao Pharos em ${API_URL}. ` +
51
+ `Confirme que o portal esta no ar ou ajuste PHAROS_API_URL.`
52
+ );
53
+ }
54
+ throw err;
55
+ } finally {
56
+ clearTimeout(timer);
57
+ }
58
+ }
59
+
60
+ const server = new McpServer({ name: "pharos", version: "0.1.0" });
61
+
62
+ server.registerTool(
63
+ "search_knowledge",
64
+ {
65
+ title: "Buscar na base de conhecimento",
66
+ description:
67
+ "Busca trechos na base interna de conhecimento sobre integracoes e servicos " +
68
+ "(Click to Pay, SCOF, MDES, OAuth 1.0a, mTLS, criptografia de payload). " +
69
+ "Devolve os trechos brutos com a fonte, sem resposta pronta — cabe a voce sintetizar " +
70
+ "combinando com o contexto do projeto atual. Cite a fonte ao usar. " +
71
+ "Retorna apenas conteudo revisado e aprovado pela equipe.",
72
+ inputSchema: {
73
+ query: z.string().describe("Pergunta ou termos de busca, em portugues"),
74
+ client: z
75
+ .string()
76
+ .optional()
77
+ .describe("Cliente/bandeira: master ou visa. Se omitido, usa o tenant padrao ativo."),
78
+ product: z
79
+ .string()
80
+ .optional()
81
+ .describe("Filtro opcional de produto: CLICK_TO_PAY, SCOF, MDES, OPEN_FINANCE, GERAL"),
82
+ topK: z.number().int().min(1).max(20).optional().describe("Quantos trechos retornar (padrao 6)"),
83
+ },
84
+ },
85
+ async ({ query, client, product, topK }) => {
86
+ const params = new URLSearchParams({ q: query });
87
+ if (client) params.set("client", client);
88
+ if (product) params.set("product", product);
89
+ if (topK) params.set("topK", String(topK));
90
+
91
+ const result = await callApi(`/search?${params}`);
92
+
93
+ if (!result.hits.length) {
94
+ return {
95
+ content: [
96
+ {
97
+ type: "text",
98
+ text:
99
+ `Nenhum trecho encontrado na base para "${query}".\n\n` +
100
+ `A base cobre apenas o que a equipe ja registrou. Se voce resolver este ` +
101
+ `problema agora, vale registrar com a ferramenta register_solution para o ` +
102
+ `proximo dev nao repetir a investigacao.`,
103
+ },
104
+ ],
105
+ };
106
+ }
107
+
108
+ const formatted = result.hits
109
+ .map((hit, i) => {
110
+ const origem = hit.sourceDocPath
111
+ ? `doc ${hit.sourceDocPath}`
112
+ : `entrada ${hit.entryId} (registrada por um dev)`;
113
+ return [
114
+ `## [${i + 1}] ${hit.title}`,
115
+ `Cliente: ${hit.client || 'master'} | Produto: ${hit.product} | Fonte: ${origem} | Similaridade: ${hit.cosineSimilarity.toFixed(3)}`,
116
+ hit.tags.length ? `Tags: ${hit.tags.join(", ")}` : null,
117
+ "",
118
+ hit.text,
119
+ ]
120
+ .filter((l) => l !== null)
121
+ .join("\n");
122
+ })
123
+ .join("\n\n---\n\n");
124
+
125
+ return {
126
+ content: [
127
+ {
128
+ type: "text",
129
+ text:
130
+ `${result.hits.length} trecho(s) da base do Pharos para "${query}":\n\n${formatted}\n\n` +
131
+ `---\nAo usar qualquer um destes trechos, cite a fonte correspondente. ` +
132
+ `Para comportamento exato de operacoes de API, confirme no MCP oficial correspondente.`,
133
+ },
134
+ ],
135
+ };
136
+ }
137
+ );
138
+
139
+ server.registerTool(
140
+ "register_solution",
141
+ {
142
+ title: "Registrar solucao na base de conhecimento",
143
+ description:
144
+ "Registra um problema e sua solucao na base interna, para outros devs. " +
145
+ "A entrada entra na fila de revisao com status PENDING e NAO fica visivel em busca " +
146
+ "ate ser aprovada manualmente por alguem da equipe. " +
147
+ "Use apenas para conhecimento generico sobre integracao — nunca inclua " +
148
+ "credenciais, dados de cliente, nomes de cliente, endpoints internos ou trechos de " +
149
+ "codigo proprietario.",
150
+ inputSchema: {
151
+ title: z.string().max(300).describe("Titulo curto e especifico do problema"),
152
+ problem: z
153
+ .string()
154
+ .describe("O problema: sintoma, ambiente, mensagem de erro. Sem dados de cliente."),
155
+ solution: z.string().describe("O que resolveu, com codigo ou configuracao relevante"),
156
+ client: z
157
+ .string()
158
+ .optional()
159
+ .describe("Cliente/bandeira: master ou visa (padrao master)"),
160
+ product: z
161
+ .string()
162
+ .describe("Produto: CLICK_TO_PAY, SCOF, MDES, MASTERCARD_SEND, OPEN_FINANCE ou GERAL"),
163
+ tags: z.array(z.string()).optional().describe("Tags como oauth, mtls, sandbox, encryption"),
164
+ },
165
+ },
166
+ async ({ title, problem, solution, client, product, tags }) => {
167
+ const created = await callApi("/entries", {
168
+ method: "POST",
169
+ body: JSON.stringify({
170
+ title,
171
+ problem,
172
+ solution,
173
+ client,
174
+ product,
175
+ tags: tags || [],
176
+ source: "AGENT",
177
+ }),
178
+ });
179
+
180
+ return {
181
+ content: [
182
+ {
183
+ type: "text",
184
+ text:
185
+ `Registrado com id ${created.id} e status ${created.status}.\n\n` +
186
+ `IMPORTANTE: informe ao dev que a entrada esta AGUARDANDO REVISAO — ela ainda ` +
187
+ `nao esta publicada e nao aparece na busca de ninguem. So depois de um revisor ` +
188
+ `aprovar manualmente e que ela vai para o indice. Nunca diga que foi "publicada".`,
189
+ },
190
+ ],
191
+ };
192
+ }
193
+ );
194
+
195
+ const transport = new StdioServerTransport();
196
+ await server.connect(transport);
@@ -0,0 +1,20 @@
1
+ {
2
+ "_comment": "Copie estes servidores para o .mcp.json do projeto do cliente e reinicie a sessao do Claude Code.",
3
+ "mcpServers": {
4
+ "pharos": {
5
+ "type": "stdio",
6
+ "command": "node",
7
+ "args": ["/CAMINHO/ABSOLUTO/PARA/pharos/mcp-server/index.js"],
8
+ "env": {
9
+ "PHAROS_API_URL": "http://localhost:8080",
10
+ "PHAROS_API_KEY": "sua-chave-secreta-aqui"
11
+ }
12
+ },
13
+ "mastercard-developers": {
14
+ "type": "stdio",
15
+ "command": "npx",
16
+ "args": ["-y", "@mastercard/developers-mcp"],
17
+ "env": {}
18
+ }
19
+ }
20
+ }
package/package.json ADDED
@@ -0,0 +1,22 @@
1
+ {
2
+ "name": "gft-pharos-mcp",
3
+ "version": "0.1.0",
4
+ "description": "MCP server do Pharos: retrieval e registro de solucoes na base de conhecimento",
5
+ "type": "module",
6
+ "bin": {
7
+ "gft-pharos-mcp": "./index.js",
8
+ "pharos-mcp": "./index.js"
9
+ },
10
+ "main": "index.js",
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "git+https://github.com/GFT-POCs/pharos.git"
14
+ },
15
+ "engines": {
16
+ "node": ">=18"
17
+ },
18
+ "dependencies": {
19
+ "@modelcontextprotocol/sdk": "^1.12.0",
20
+ "zod": "^3.23.8"
21
+ }
22
+ }