bcb-br-mcp 1.3.4 → 1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,61 @@
1
+ /**
2
+ * SDK v2 registration layer — the SINGLE place where tools, resources and
3
+ * prompts are projected onto an `McpServer`.
4
+ *
5
+ * Design decisions of the v2 migration (fase bcb, Sessão 02):
6
+ *
7
+ * - Before this module there were two independent surfaces: `index.ts`
8
+ * derived its schemas from Zod for stdio, while `worker.ts` hand-rolled the
9
+ * JSON-RPC protocol and served the JSON Schemas from `TOOL_DEFINITIONS`.
10
+ * They had drifted apart (the HTTP contract lacked `minItems`/`maxItems`,
11
+ * `default`, `minimum`/`maximum` and `additionalProperties`; resources were
12
+ * published under different names). `baselines/README.md` records the
13
+ * measured divergence. Both transports now read this module.
14
+ *
15
+ * - The advertised JSON Schemas are the exact objects in `TOOL_DEFINITIONS`,
16
+ * passed through `fromJsonSchema` so `tools/list` publishes them verbatim
17
+ * instead of a re-derived dialect.
18
+ *
19
+ * - INPUT is validated, OUTPUT is not. Rationale: under SDK 1.x the
20
+ * stdio channel validated arguments through the Zod input schema, but the
21
+ * hand-rolled Worker never did — sending `{}` to `bcb_serie_valores` on the
22
+ * hosted endpoint produced a request for "série undefined" against the BCB
23
+ * API. Validating here restores the stdio guarantee and closes that hole,
24
+ * with one contract for both transports. The handlers never validated on
25
+ * their own, so there is no pedagogical Zod error to preserve. Output stays
26
+ * unvalidated at runtime: shapes are covered by the characterization tests,
27
+ * and a strict runtime check could only turn a good answer into an error.
28
+ *
29
+ * - SDK v2 hard rule: a tool declaring `outputSchema` MUST return
30
+ * `structuredContent` on every non-error result. The check runs before any
31
+ * validator and cannot be disabled. All 8 handlers go through
32
+ * `structuredResult()`, and `register.test.ts` pins it.
33
+ */
34
+ import { McpServer } from "@modelcontextprotocol/server";
35
+ /**
36
+ * Optional per-tool usage hook: `tool_call` on every invocation, `tool_error`
37
+ * additionally when the call fails. stdio passes nothing; the Cloudflare
38
+ * Worker passes its UsageTracker recorder. Names and counts only — never
39
+ * arguments, never results.
40
+ */
41
+ export type ToolUsageRecorder = (kind: "tool_call" | "tool_error", name: string) => void;
42
+ export interface RegisterOptions {
43
+ /** Per-transport timeout/retry budget (the Worker uses a tighter one). */
44
+ config?: {
45
+ TIMEOUT_MS: number;
46
+ MAX_RETRIES: number;
47
+ };
48
+ record?: ToolUsageRecorder;
49
+ }
50
+ /**
51
+ * Registers the whole surface onto a given server. Kept separate from
52
+ * `createServer` so the Worker — which builds a fresh `McpServer` per
53
+ * request — reuses the exact same registrations.
54
+ */
55
+ export declare function registerAll(server: McpServer, options?: RegisterOptions): void;
56
+ /**
57
+ * Builds a fresh, fully registered server. No transport is connected, so it is
58
+ * safe to call from tests and once per request on stateless HTTP transports.
59
+ */
60
+ export declare function createServer(version: string, options?: RegisterOptions): McpServer;
61
+ //# sourceMappingURL=register.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"register.d.ts","sourceRoot":"","sources":["../src/register.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AAEH,OAAO,EACL,SAAS,EAOV,MAAM,8BAA8B,CAAC;AAyCtC;;;;;GAKG;AACH,MAAM,MAAM,iBAAiB,GAAG,CAAC,IAAI,EAAE,WAAW,GAAG,YAAY,EAAE,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;AAEzF,MAAM,WAAW,eAAe;IAC9B,0EAA0E;IAC1E,MAAM,CAAC,EAAE;QAAE,UAAU,EAAE,MAAM,CAAC;QAAC,WAAW,EAAE,MAAM,CAAA;KAAE,CAAC;IACrD,MAAM,CAAC,EAAE,iBAAiB,CAAC;CAC5B;AAED;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,MAAM,EAAE,SAAS,EAAE,OAAO,GAAE,eAAoB,GAAG,IAAI,CAsDlF;AAED;;;GAGG;AACH,wBAAgB,YAAY,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,GAAE,eAAoB,GAAG,SAAS,CAItF"}
@@ -0,0 +1,116 @@
1
+ /**
2
+ * SDK v2 registration layer — the SINGLE place where tools, resources and
3
+ * prompts are projected onto an `McpServer`.
4
+ *
5
+ * Design decisions of the v2 migration (fase bcb, Sessão 02):
6
+ *
7
+ * - Before this module there were two independent surfaces: `index.ts`
8
+ * derived its schemas from Zod for stdio, while `worker.ts` hand-rolled the
9
+ * JSON-RPC protocol and served the JSON Schemas from `TOOL_DEFINITIONS`.
10
+ * They had drifted apart (the HTTP contract lacked `minItems`/`maxItems`,
11
+ * `default`, `minimum`/`maximum` and `additionalProperties`; resources were
12
+ * published under different names). `baselines/README.md` records the
13
+ * measured divergence. Both transports now read this module.
14
+ *
15
+ * - The advertised JSON Schemas are the exact objects in `TOOL_DEFINITIONS`,
16
+ * passed through `fromJsonSchema` so `tools/list` publishes them verbatim
17
+ * instead of a re-derived dialect.
18
+ *
19
+ * - INPUT is validated, OUTPUT is not. Rationale: under SDK 1.x the
20
+ * stdio channel validated arguments through the Zod input schema, but the
21
+ * hand-rolled Worker never did — sending `{}` to `bcb_serie_valores` on the
22
+ * hosted endpoint produced a request for "série undefined" against the BCB
23
+ * API. Validating here restores the stdio guarantee and closes that hole,
24
+ * with one contract for both transports. The handlers never validated on
25
+ * their own, so there is no pedagogical Zod error to preserve. Output stays
26
+ * unvalidated at runtime: shapes are covered by the characterization tests,
27
+ * and a strict runtime check could only turn a good answer into an error.
28
+ *
29
+ * - SDK v2 hard rule: a tool declaring `outputSchema` MUST return
30
+ * `structuredContent` on every non-error result. The check runs before any
31
+ * validator and cannot be disabled. All 8 handlers go through
32
+ * `structuredResult()`, and `register.test.ts` pins it.
33
+ */
34
+ import { McpServer, fromJsonSchema } from "@modelcontextprotocol/server";
35
+ // O validador do SDK para Cloudflare Workers, usado nos DOIS runtimes de
36
+ // propósito. O provider baseado em ajv compila os validadores com `new
37
+ // Function`, que o runtime da Cloudflare proíbe — no wrangler dev isso derruba
38
+ // TODA chamada ao /mcp com "Error compiling schema" + HTTP 500. Este aqui
39
+ // interpreta o schema em vez de gerar código, funciona igual no Node, e assim
40
+ // os dois transportes validam exatamente da mesma forma.
41
+ import { CfWorkerJsonSchemaValidator } from "@modelcontextprotocol/server/validators/cf-worker";
42
+ import { TOOL_DEFINITIONS, RESOURCE_DEFINITIONS, PROMPT_DEFINITIONS, dispatchTool, CONFIG } from "./tools.js";
43
+ /** Accepts every value — used for output schemas only (see module docstring). */
44
+ const permissiveValidator = {
45
+ getValidator() {
46
+ return (input) => ({
47
+ valid: true,
48
+ data: input,
49
+ errorMessage: undefined
50
+ });
51
+ }
52
+ };
53
+ const inputValidator = new CfWorkerJsonSchemaValidator();
54
+ /** Advertise a JSON Schema verbatim AND enforce it on incoming arguments. */
55
+ function validatedSchema(schema) {
56
+ return fromJsonSchema(schema, inputValidator);
57
+ }
58
+ /** Advertise a JSON Schema verbatim, without runtime checking. */
59
+ function passthroughSchema(schema) {
60
+ return fromJsonSchema(schema, permissiveValidator);
61
+ }
62
+ /**
63
+ * Registers the whole surface onto a given server. Kept separate from
64
+ * `createServer` so the Worker — which builds a fresh `McpServer` per
65
+ * request — reuses the exact same registrations.
66
+ */
67
+ export function registerAll(server, options = {}) {
68
+ const { config = CONFIG, record } = options;
69
+ for (const tool of TOOL_DEFINITIONS) {
70
+ server.registerTool(tool.name, {
71
+ description: tool.description,
72
+ inputSchema: validatedSchema(tool.inputSchema),
73
+ outputSchema: passthroughSchema(tool.outputSchema),
74
+ annotations: tool.annotations
75
+ }, async (args) => {
76
+ try {
77
+ const result = await dispatchTool(tool.name, (args ?? {}), config.TIMEOUT_MS, config.MAX_RETRIES);
78
+ record?.("tool_call", tool.name);
79
+ if (result.isError === true)
80
+ record?.("tool_error", tool.name);
81
+ return result;
82
+ }
83
+ catch (error) {
84
+ // Handlers already trap their own failures; this is the last resort
85
+ // so an unexpected throw never breaks the transport.
86
+ const message = error instanceof Error ? error.message : String(error);
87
+ record?.("tool_call", tool.name);
88
+ record?.("tool_error", tool.name);
89
+ return {
90
+ content: [{ type: "text", text: `Erro ao executar a tool "${tool.name}": ${message}` }],
91
+ isError: true
92
+ };
93
+ }
94
+ });
95
+ }
96
+ for (const resource of RESOURCE_DEFINITIONS) {
97
+ server.registerResource(resource.name, resource.uri, { description: resource.description, mimeType: resource.mimeType }, async () => ({
98
+ contents: [{ uri: resource.uri, mimeType: resource.mimeType, text: resource.read() }]
99
+ }));
100
+ }
101
+ for (const prompt of PROMPT_DEFINITIONS) {
102
+ server.registerPrompt(prompt.name, { description: prompt.description }, async () => ({
103
+ messages: [{ role: "user", content: { type: "text", text: prompt.text } }]
104
+ }));
105
+ }
106
+ }
107
+ /**
108
+ * Builds a fresh, fully registered server. No transport is connected, so it is
109
+ * safe to call from tests and once per request on stateless HTTP transports.
110
+ */
111
+ export function createServer(version, options = {}) {
112
+ const server = new McpServer({ name: "bcb-br-mcp", version });
113
+ registerAll(server, options);
114
+ return server;
115
+ }
116
+ //# sourceMappingURL=register.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"register.js","sourceRoot":"","sources":["../src/register.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AAEH,OAAO,EACL,SAAS,EACT,cAAc,EAMf,MAAM,8BAA8B,CAAC;AACtC,yEAAyE;AACzE,uEAAuE;AACvE,+EAA+E;AAC/E,0EAA0E;AAC1E,8EAA8E;AAC9E,yDAAyD;AACzD,OAAO,EAAE,2BAA2B,EAAE,MAAM,mDAAmD,CAAC;AAEhG,OAAO,EACL,gBAAgB,EAChB,oBAAoB,EACpB,kBAAkB,EAClB,YAAY,EACZ,MAAM,EAEP,MAAM,YAAY,CAAC;AAEpB,iFAAiF;AACjF,MAAM,mBAAmB,GAAwB;IAC/C,YAAY;QACV,OAAO,CAAC,KAAc,EAAgC,EAAE,CAAC,CAAC;YACxD,KAAK,EAAE,IAAI;YACX,IAAI,EAAE,KAAU;YAChB,YAAY,EA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IAAI,EAAE,MAAM,CAAC,IAAI,EAAE,EAAE,CAAC;SAC7F,CAAC,CAAC,CAAC;IACN,CAAC;AACH,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,YAAY,CAAC,OAAe,EAAE,UAA2B,EAAE;IACzE,MAAM,MAAM,GAAG,IAAI,SAAS,CAAC,EAAE,IAAI,EAAE,YAAY,EAAE,OAAO,EAAE,CAAC,CAAC;IAC9D,WAAW,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAC7B,OAAO,MAAM,CAAC;AAChB,CAAC"}
@@ -0,0 +1,89 @@
1
+ /**
2
+ * Primitivos compartilhados por todas as APIs do BCB que o servidor consome.
3
+ *
4
+ * Extraído de `tools.ts` na sessão de D3, quando o servidor deixou de falar com
5
+ * uma API só (SGS) e passou a falar com três (SGS, Olinda/Expectativas e PTAX).
6
+ * `tools.ts` re-exporta tudo daqui, de propósito: worker e testes importam
7
+ * desses nomes desde a fundação, e o D3 não é hora de mexer em quem importa o
8
+ * quê. A regra de dependência é uma só — `shared.ts` não importa ninguém, e é
9
+ * por isso que não há ciclo entre os módulos de tool.
10
+ */
11
+ export declare const CONFIG: {
12
+ TIMEOUT_MS: number;
13
+ MAX_RETRIES: number;
14
+ RETRY_DELAY_MS: number;
15
+ };
16
+ export declare const WORKER_CONFIG: {
17
+ TIMEOUT_MS: number;
18
+ MAX_RETRIES: number;
19
+ RETRY_DELAY_MS: number;
20
+ };
21
+ export declare function setServerVersion(version: string): void;
22
+ export declare function getUserAgent(): string;
23
+ export interface SerieValor {
24
+ data: string;
25
+ valor: string;
26
+ }
27
+ export interface SerieMetadados {
28
+ codigo: number;
29
+ nome: string;
30
+ unidade: string;
31
+ periodicidade: string;
32
+ fonte: string;
33
+ especial: boolean;
34
+ }
35
+ export interface SeriePopular {
36
+ codigo: number;
37
+ nome: string;
38
+ categoria: string;
39
+ periodicidade: string;
40
+ }
41
+ export interface ToolResult {
42
+ [key: string]: unknown;
43
+ content: Array<{
44
+ type: "text";
45
+ text: string;
46
+ }>;
47
+ structuredContent?: Record<string, unknown>;
48
+ isError?: boolean;
49
+ }
50
+ /**
51
+ * Builds a ToolResult that satisfies an MCP tool's outputSchema:
52
+ * the same payload is exposed as machine-readable structuredContent and,
53
+ * for backward compatibility, serialized into a TextContent block.
54
+ */
55
+ export declare function structuredResult(payload: Record<string, unknown>): ToolResult;
56
+ /** Falha de tool: `isError` com texto em pt-BR, nunca erro de protocolo. */
57
+ export declare function erroResult(texto: string): ToolResult;
58
+ export declare function mensagemDeErro(error: unknown): string;
59
+ export declare function normalizeString(str: string): string;
60
+ export declare function formatDateForApi(dateStr: string): string;
61
+ export declare function sleep(ms: number): Promise<void>;
62
+ export declare function fetchWithTimeout(url: string, timeoutMs: number): Promise<Response>;
63
+ export declare function fetchBcbApi(url: string, timeoutMs?: number, maxRetries?: number): Promise<unknown>;
64
+ export declare function calculateVariation(valorInicial: number, valorFinal: number): number;
65
+ /**
66
+ * Seals every object node of a JSON Schema (`additionalProperties: false`),
67
+ * recursively. Zod sealed objects by construction, so the stdio channel always
68
+ * advertised sealed schemas; doing it here in one place keeps that guarantee
69
+ * after the SDK v2 migration and extends it to the HTTP channel, which never
70
+ * had it.
71
+ */
72
+ export declare function sealDeep<T>(schema: T): T;
73
+ /** Definição canônica de uma tool, igual para os dois transportes. */
74
+ export interface ToolDefinition {
75
+ name: string;
76
+ description: string;
77
+ annotations: {
78
+ title: string;
79
+ readOnlyHint: boolean;
80
+ destructiveHint: boolean;
81
+ idempotentHint: boolean;
82
+ openWorldHint: boolean;
83
+ };
84
+ inputSchema: Record<string, unknown>;
85
+ outputSchema: Record<string, unknown>;
86
+ }
87
+ /** Anotações padrão do portfólio: toda tool aqui é leitura de API pública. */
88
+ export declare function leituraRemota(title: string): ToolDefinition["annotations"];
89
+ //# sourceMappingURL=shared.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"shared.d.ts","sourceRoot":"","sources":["../src/shared.ts"],"names":[],"mappings":"AAAA;;;;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AM,CAKnD;AAED,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAMxD;AAED,wBAAgB,KAAK,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAE/C;AAED,wBAAsB,gBAAgB,CAAC,GAAG,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC,CAgBxF;AAED,wBAAsB,WAAW,CAC/B,GAAG,EAAE,MAAM,EACX,SAAS,GAAE,MAA0B,EACrC,UAAU,GAAE,MAA2B,GACtC,OAAO,CAAC,OAAO,CAAC,CAoClB;AAED,wBAAgB,kBAAkB,CAAC,YAAY,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,MAAM,CAGnF;AAID;;;;;;GAMG;AACH,wBAAgB,QAAQ,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,GAAG,CAAC,CAUxC;AAED,sEAAsE;AACtE,MAAM,WAAW,cAAc;IAC7B,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,WAAW,EAAE;QACX,KAAK,EAAE,MAAM,CAAC;QACd,YAAY,EAAE,OAAO,CAAC;QACtB,eAAe,EAAE,OAAO,CAAC;QACzB,cAAc,EAAE,OAAO,CAAC;QACxB,aAAa,EAAE,OAAO,CAAC;KACxB,CAAC;IACF,WAAW,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACrC,YAAY,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACvC;AAED,8EAA8E;AAC9E,wBAAgB,aAAa,CAAC,KAAK,EAAE,MAAM,GAAG,cAAc,CAAC,aAAa,CAAC,CAE1E"}
package/dist/shared.js ADDED
@@ -0,0 +1,151 @@
1
+ /**
2
+ * Primitivos compartilhados por todas as APIs do BCB que o servidor consome.
3
+ *
4
+ * Extraído de `tools.ts` na sessão de D3, quando o servidor deixou de falar com
5
+ * uma API só (SGS) e passou a falar com três (SGS, Olinda/Expectativas e PTAX).
6
+ * `tools.ts` re-exporta tudo daqui, de propósito: worker e testes importam
7
+ * desses nomes desde a fundação, e o D3 não é hora de mexer em quem importa o
8
+ * quê. A regra de dependência é uma só — `shared.ts` não importa ninguém, e é
9
+ * por isso que não há ciclo entre os módulos de tool.
10
+ */
11
+ // ==================== CONFIG ====================
12
+ export const CONFIG = {
13
+ TIMEOUT_MS: 30000,
14
+ MAX_RETRIES: 3,
15
+ RETRY_DELAY_MS: 1000
16
+ };
17
+ // Worker uses shorter timeout (Cloudflare has its own limits)
18
+ export const WORKER_CONFIG = {
19
+ TIMEOUT_MS: 10000,
20
+ MAX_RETRIES: 2,
21
+ RETRY_DELAY_MS: 1000
22
+ };
23
+ // ==================== VERSION (single source of truth) ====================
24
+ //
25
+ // This module runs under two builds that resolve package.json differently, so the
26
+ // version is injected by each entry point instead of imported here:
27
+ // - index.ts (Node/stdio) reads it via createRequire and calls setServerVersion()
28
+ // - the Worker reads it via a JSON import inlined by esbuild and calls it too
29
+ // A static `import "../package.json"` is avoided on purpose: it breaks tsc's rootDir
30
+ // and createRequire is unavailable in the Worker runtime (no nodejs_compat).
31
+ // The fallback is only used if no entry point injects a version; keep it = package.json.
32
+ let serverVersion = "1.3.5";
33
+ export function setServerVersion(version) {
34
+ serverVersion = version;
35
+ }
36
+ export function getUserAgent() {
37
+ return `bcb-br-mcp/${serverVersion}`;
38
+ }
39
+ // ==================== OUTPUT HELPERS ====================
40
+ /**
41
+ * Builds a ToolResult that satisfies an MCP tool's outputSchema:
42
+ * the same payload is exposed as machine-readable structuredContent and,
43
+ * for backward compatibility, serialized into a TextContent block.
44
+ */
45
+ export function structuredResult(payload) {
46
+ return {
47
+ content: [{ type: "text", text: JSON.stringify(payload, null, 2) }],
48
+ structuredContent: payload
49
+ };
50
+ }
51
+ /** Falha de tool: `isError` com texto em pt-BR, nunca erro de protocolo. */
52
+ export function erroResult(texto) {
53
+ return { content: [{ type: "text", text: texto }], isError: true };
54
+ }
55
+ export function mensagemDeErro(error) {
56
+ return error instanceof Error ? error.message : String(error);
57
+ }
58
+ // ==================== UTILITY FUNCTIONS ====================
59
+ export function normalizeString(str) {
60
+ return str
61
+ .toLowerCase()
62
+ .normalize("NFD")
63
+ .replace(/\p{M}/gu, ""); // marcas de combinação — equivalente a [̀-ͯ] sem escape literal
64
+ }
65
+ export function formatDateForApi(dateStr) {
66
+ if (dateStr.includes("-")) {
67
+ const [year, month, day] = dateStr.split("-");
68
+ return `${day}/${month}/${year}`;
69
+ }
70
+ return dateStr;
71
+ }
72
+ export function sleep(ms) {
73
+ return new Promise(resolve => setTimeout(resolve, ms));
74
+ }
75
+ export async function fetchWithTimeout(url, timeoutMs) {
76
+ const controller = new AbortController();
77
+ const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
78
+ try {
79
+ const response = await fetch(url, {
80
+ signal: controller.signal,
81
+ headers: {
82
+ "Accept": "application/json",
83
+ "User-Agent": getUserAgent()
84
+ }
85
+ });
86
+ return response;
87
+ }
88
+ finally {
89
+ clearTimeout(timeoutId);
90
+ }
91
+ }
92
+ export async function fetchBcbApi(url, timeoutMs = CONFIG.TIMEOUT_MS, maxRetries = CONFIG.MAX_RETRIES) {
93
+ let lastError = null;
94
+ for (let attempt = 1; attempt <= maxRetries; attempt++) {
95
+ try {
96
+ const response = await fetchWithTimeout(url, timeoutMs);
97
+ if (!response.ok) {
98
+ if (response.status === 404) {
99
+ throw new Error(`Série não encontrada ou sem dados para o período solicitado`);
100
+ }
101
+ throw new Error(`Erro na API do BCB: ${response.status} ${response.statusText}`);
102
+ }
103
+ return response.json();
104
+ }
105
+ catch (error) {
106
+ lastError = error instanceof Error ? error : new Error(String(error));
107
+ if (lastError.message.includes("não encontrada")) {
108
+ throw lastError;
109
+ }
110
+ const isTimeout = lastError.name === "AbortError" ||
111
+ lastError.message.includes("aborted") ||
112
+ lastError.message.includes("timeout");
113
+ if (attempt < maxRetries) {
114
+ const delayMs = CONFIG.RETRY_DELAY_MS * Math.pow(2, attempt - 1);
115
+ const reason = isTimeout ? "timeout" : "erro";
116
+ console.error(`Tentativa ${attempt}/${maxRetries} falhou (${reason}). Aguardando ${delayMs}ms...`);
117
+ await sleep(delayMs);
118
+ }
119
+ }
120
+ }
121
+ throw new Error(`Falha após ${maxRetries} tentativas: ${lastError?.message || "Erro desconhecido"}`);
122
+ }
123
+ export function calculateVariation(valorInicial, valorFinal) {
124
+ if (valorInicial === 0)
125
+ return 0;
126
+ return ((valorFinal - valorInicial) / Math.abs(valorInicial)) * 100;
127
+ }
128
+ // ==================== SCHEMA ====================
129
+ /**
130
+ * Seals every object node of a JSON Schema (`additionalProperties: false`),
131
+ * recursively. Zod sealed objects by construction, so the stdio channel always
132
+ * advertised sealed schemas; doing it here in one place keeps that guarantee
133
+ * after the SDK v2 migration and extends it to the HTTP channel, which never
134
+ * had it.
135
+ */
136
+ export function sealDeep(schema) {
137
+ if (Array.isArray(schema))
138
+ return schema.map(sealDeep);
139
+ if (schema === null || typeof schema !== "object")
140
+ return schema;
141
+ const node = schema;
142
+ const sealedEntries = Object.fromEntries(Object.entries(node).map(([k, v]) => [k, sealDeep(v)]));
143
+ return (node.type === "object" && node.properties !== undefined
144
+ ? { ...sealedEntries, additionalProperties: false }
145
+ : sealedEntries);
146
+ }
147
+ /** Anotações padrão do portfólio: toda tool aqui é leitura de API pública. */
148
+ export function leituraRemota(title) {
149
+ return { title, readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true };
150
+ }
151
+ //# sourceMappingURL=shared.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"shared.js","sourceRoot":"","sources":["../src/shared.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,mDAAmD;AAEnD,MAAM,CAAC,MAAM,MAAM,GAAG;IACpB,UAAU,EAAE,KAAK;IACjB,WAAW,EAAE,CAAC;IACd,cAAc,EAAE,IAAI;CACrB,CAAC;AAEF,8DAA8D;AAC9D,MAAM,CAAC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