utn-mcp 0.1.0 → 0.2.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.
package/build/http.js CHANGED
@@ -6,11 +6,6 @@ const asMiddleware = (guard) => (req, res, next) => {
6
6
  if (guard(req, res))
7
7
  next();
8
8
  };
9
- /**
10
- * Entrada HTTP local: solo escucha en 127.0.0.1 y rechaza Host/Origin que no sean
11
- * localhost, para que una página web no pueda usar tu sesión de la UTN (DNS rebinding).
12
- * El modo hosteado va a reutilizar el mismo `factory`, con OAuth y una sesión por usuario.
13
- */
14
9
  export function startHttpServer(factory, port) {
15
10
  const handler = createMcpHandler(factory, { onerror: (e) => logger.error(e.message) });
16
11
  const app = express();
package/build/server.js CHANGED
@@ -4,7 +4,7 @@ import { registerAulaVirtualTools } from "./aula-virtual/tools.js";
4
4
  export function createServer(aula) {
5
5
  const server = new McpServer({
6
6
  name: "UTN-MCP",
7
- version: "0.1.0",
7
+ version: "0.2.1",
8
8
  });
9
9
  registerAulaVirtualTools(server, aula);
10
10
  return server;
@@ -0,0 +1,68 @@
1
+ import { htmlToText } from "../html.js";
2
+ import { abrirOffice, formatoOffice } from "./office.js";
3
+ import { abrirPdf } from "./pdf.js";
4
+ export class FormatoNoSoportado extends Error {
5
+ formato;
6
+ constructor(formato) {
7
+ super(`No sé leer archivos ${formato}.`);
8
+ this.formato = formato;
9
+ this.name = "FormatoNoSoportado";
10
+ }
11
+ }
12
+ /** Tamaño de cada fragmento cuando un texto largo viene de una sola pieza (un docx, un html). */
13
+ export const FRAGMENTO = 15_000;
14
+ const IMAGENES = [
15
+ [[0x89, 0x50, 0x4e, 0x47], "image/png"],
16
+ [[0xff, 0xd8, 0xff], "image/jpeg"],
17
+ [[0x47, 0x49, 0x46, 0x38], "image/gif"],
18
+ ];
19
+ const empieza = (bytes, firma) => firma.every((b, i) => bytes[i] === b);
20
+ /** Reconoce el formato por los primeros bytes; el nombre solo se usa para los de texto plano. */
21
+ export async function abrirDocumento(bytes, nombre) {
22
+ if (empieza(bytes, [0x25, 0x50, 0x44, 0x46]))
23
+ return abrirPdf(bytes);
24
+ for (const [firma, mimeType] of IMAGENES) {
25
+ if (empieza(bytes, firma))
26
+ return deTexto("imagen", "imagen", [{ imagen: bytes, mimeType }]);
27
+ }
28
+ if (empieza(bytes, [0x50, 0x4b, 0x03, 0x04])) {
29
+ const formato = formatoOffice(bytes);
30
+ if (!formato)
31
+ throw new FormatoNoSoportado("comprimidos (.zip)");
32
+ return abrirOffice(bytes, formato);
33
+ }
34
+ if (empieza(bytes, [0xd0, 0xcf, 0x11, 0xe0])) {
35
+ throw new FormatoNoSoportado("de Office viejo (.doc, .xls, .ppt, .pps)");
36
+ }
37
+ const extension = nombre.toLowerCase().match(/\.(\w+)$/)?.[1] ?? "";
38
+ if (["txt", "csv", "md", "html", "htm"].includes(extension)) {
39
+ const texto = new TextDecoder().decode(bytes);
40
+ const plano = extension.startsWith("htm") ? htmlToText(texto) : texto;
41
+ return deTexto(extension, "fragmento", fragmentar(plano).map((t) => ({ texto: t })));
42
+ }
43
+ throw new FormatoNoSoportado(extension ? `.${extension}` : "de este tipo");
44
+ }
45
+ /** Un documento que ya está entero en memoria. */
46
+ export function deTexto(formato, unidad, partes) {
47
+ return {
48
+ formato,
49
+ unidad,
50
+ total: partes.length,
51
+ parte: async (n) => partes[n - 1],
52
+ cerrar: async () => { },
53
+ };
54
+ }
55
+ /** Corta un texto largo en pedazos de hasta `max` caracteres, prefiriendo cortar en un salto de línea. */
56
+ export function fragmentar(texto, max = FRAGMENTO) {
57
+ const fragmentos = [];
58
+ let resto = texto.trim();
59
+ while (resto.length > max) {
60
+ const corte = resto.lastIndexOf("\n", max);
61
+ const fin = corte > max / 2 ? corte : max;
62
+ fragmentos.push(resto.slice(0, fin).trim());
63
+ resto = resto.slice(fin).trim();
64
+ }
65
+ if (resto || fragmentos.length === 0)
66
+ fragmentos.push(resto);
67
+ return fragmentos;
68
+ }
@@ -0,0 +1,118 @@
1
+ import { deTexto, fragmentar } from "./index.js";
2
+ import { leerEntrada, listarZip } from "./zip.js";
3
+ /** Tope por entrada descomprimida: un XML de texto de más que esto es un zip malicioso o no es un documento. */
4
+ const MAX_ENTRADA = 50 * 1024 * 1024;
5
+ const MARCAS = {
6
+ docx: "word/document.xml",
7
+ pptx: "ppt/presentation.xml",
8
+ xlsx: "xl/workbook.xml",
9
+ };
10
+ /** Mira la lista de entradas del zip sin descomprimir nada. */
11
+ export function formatoOffice(bytes) {
12
+ const nombres = new Set(listarZip(bytes).map((e) => e.nombre));
13
+ return Object.keys(MARCAS).find((f) => nombres.has(MARCAS[f])) ?? null;
14
+ }
15
+ export function abrirOffice(bytes, formato) {
16
+ const texto = new TextDecoder();
17
+ const zip = Object.fromEntries(listarZip(bytes)
18
+ .filter((e) => necesaria(formato, e.nombre))
19
+ .map((e) => [e.nombre, texto.decode(leerEntrada(bytes, e, MAX_ENTRADA))]));
20
+ switch (formato) {
21
+ case "docx":
22
+ return deTexto("docx", "fragmento", fragmentar(xmlTexto(leer(zip, "word/document.xml"), "w")).map((texto) => ({ texto })));
23
+ case "pptx":
24
+ return deTexto("pptx", "diapositiva", Object.keys(zip)
25
+ .filter((p) => /^ppt\/slides\/slide\d+\.xml$/.test(p))
26
+ .sort((a, b) => numero(a) - numero(b))
27
+ .map((p) => ({ texto: xmlTexto(leer(zip, p), "a") || "(diapositiva sin texto)" })));
28
+ case "xlsx":
29
+ return deTexto("xlsx", "fragmento", hojas(zip).flatMap(({ nombre, texto }) => {
30
+ const partes = fragmentar(texto);
31
+ return partes.map((t, i) => ({
32
+ titulo: partes.length > 1 ? `hoja "${nombre}" (${i + 1}/${partes.length})` : `hoja "${nombre}"`,
33
+ texto: t,
34
+ }));
35
+ }));
36
+ }
37
+ }
38
+ function necesaria(formato, nombre) {
39
+ switch (formato) {
40
+ case "docx":
41
+ return nombre === "word/document.xml";
42
+ case "pptx":
43
+ return /^ppt\/slides\/slide\d+\.xml$/.test(nombre);
44
+ case "xlsx":
45
+ return nombre === "xl/workbook.xml" || nombre === "xl/sharedStrings.xml" ||
46
+ nombre === "xl/_rels/workbook.xml.rels" || nombre.startsWith("xl/worksheets/");
47
+ }
48
+ }
49
+ const leer = (zip, ruta) => zip[ruta] ?? "";
50
+ const numero = (ruta) => Number(ruta.match(/(\d+)\.xml$/)?.[1]);
51
+ const ENTIDADES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" };
52
+ const decodificar = (s) => s.replace(/&(#x[0-9a-f]+|#\d+|\w+);/gi, (m, e) => e[0] !== "#" ? (ENTIDADES[e] ?? m) : String.fromCodePoint(e[1].toLowerCase() === "x" ? parseInt(e.slice(2), 16) : Number(e.slice(1))));
53
+ /**
54
+ * Texto de un XML de Word (`w`) o PowerPoint (`a`), recorriendo los tags en orden: texto de los nodos
55
+ * de texto, salto de línea al cerrar un párrafo, y las tablas como filas con celdas separadas por " | ".
56
+ */
57
+ function xmlTexto(xml, ns) {
58
+ let out = "";
59
+ let enTexto = false;
60
+ let enCelda = 0;
61
+ for (const [, cierre, tag, , autocierre, chars] of xml.matchAll(/<(\/?)([\w:]+)((?:[^>"]|"[^"]*")*?)(\/?)>|([^<]+)/g)) {
62
+ if (chars !== undefined) {
63
+ if (enTexto)
64
+ out += decodificar(chars);
65
+ }
66
+ else if (tag === `${ns}:t`) {
67
+ enTexto = !cierre && !autocierre;
68
+ }
69
+ else if (tag === `${ns}:tc` && !autocierre) {
70
+ enCelda += cierre ? -1 : 1;
71
+ if (cierre)
72
+ out += " | ";
73
+ }
74
+ else if (tag === `${ns}:tr` && cierre) {
75
+ out += "\n";
76
+ }
77
+ else if (tag === `${ns}:p` && cierre) {
78
+ out += enCelda ? " " : "\n";
79
+ }
80
+ else if (tag === `${ns}:tab`) {
81
+ out += " ";
82
+ }
83
+ else if (tag === `${ns}:br`) {
84
+ out += enCelda ? " " : "\n";
85
+ }
86
+ }
87
+ return out
88
+ .split("\n")
89
+ .map((l) => l.replace(/\s+/g, " ").replace(/\s*\|\s*$/, "").trim())
90
+ .filter((l, i, todas) => l !== "|" && (l !== "" || todas[i - 1] !== ""))
91
+ .join("\n")
92
+ .trim();
93
+ }
94
+ /** Cada hoja como filas de celdas separadas por tabs, en el orden del libro. */
95
+ function hojas(zip) {
96
+ const compartidas = [...leer(zip, "xl/sharedStrings.xml").matchAll(/<si>([\s\S]*?)<\/si>/g)].map((m) => decodificar([...m[1].matchAll(/<t[^>]*>([\s\S]*?)<\/t>/g)].map((t) => t[1]).join("")));
97
+ const rels = Object.fromEntries([...leer(zip, "xl/_rels/workbook.xml.rels").matchAll(/<Relationship [^>]*>/g)].map(([tag]) => [
98
+ tag.match(/Id="([^"]+)"/)?.[1],
99
+ tag.match(/Target="([^"]+)"/)?.[1],
100
+ ]));
101
+ return [...leer(zip, "xl/workbook.xml").matchAll(/<sheet [^>]*>/g)].map(([tag]) => {
102
+ const nombre = decodificar(tag.match(/name="([^"]*)"/)?.[1] ?? "");
103
+ const destino = rels[tag.match(/r:id="([^"]+)"/)?.[1] ?? ""] ?? "";
104
+ const ruta = destino.replace(/^\//, "").replace(/^(xl\/)?/, "xl/");
105
+ const filas = [...leer(zip, ruta).matchAll(/<row[^>]*>([\s\S]*?)<\/row>/g)].map((fila) => [...fila[1].matchAll(/<c ([^>]*?)(?:\/>|>([\s\S]*?)<\/c>)/g)]
106
+ .map(([, attrs, cuerpo = ""]) => {
107
+ const tipo = attrs.match(/\bt="(\w+)"/)?.[1];
108
+ if (tipo === "s")
109
+ return compartidas[Number(cuerpo.match(/<v>(\d+)<\/v>/)?.[1])] ?? "";
110
+ if (tipo === "inlineStr")
111
+ return decodificar(cuerpo.match(/<t[^>]*>([\s\S]*?)<\/t>/)?.[1] ?? "");
112
+ return decodificar(cuerpo.match(/<v>([\s\S]*?)<\/v>/)?.[1] ?? "");
113
+ })
114
+ .join("\t")
115
+ .replace(/\t+$/, ""));
116
+ return { nombre, texto: filas.filter(Boolean).join("\n") || "(hoja vacía)" };
117
+ });
118
+ }
@@ -0,0 +1,164 @@
1
+ import { pngGris } from "./png.js";
2
+ /**
3
+ * pdf.js no es una dependencia: scripts/vendor-pdfjs.mjs copia a vendor/pdfjs los pocos archivos que
4
+ * usamos. Está a la misma altura desde src/ y desde build/, así que la ruta sirve en dev y publicado.
5
+ */
6
+ const VENDOR = new URL("../../../vendor/pdfjs/", import.meta.url);
7
+ /** Al arrancar en Node, pdf.js avisa que le falta canvas para renderizar. No renderizamos: son ruido en el log. */
8
+ const AVISOS_DE_CANVAS = /@napi-rs\/canvas|Cannot polyfill/;
9
+ let pdfjsCargado;
10
+ /** Se carga recién al primer PDF: son 3 MB que el servidor no necesita para arrancar. */
11
+ function pdfjs() {
12
+ pdfjsCargado ??= (async () => {
13
+ const warn = console.warn;
14
+ console.warn = (...args) => {
15
+ if (!AVISOS_DE_CANVAS.test(String(args[0])))
16
+ warn(...args);
17
+ };
18
+ try {
19
+ return (await import(new URL("pdf.mjs", VENDOR).href));
20
+ }
21
+ finally {
22
+ console.warn = warn;
23
+ }
24
+ })();
25
+ return pdfjsCargado;
26
+ }
27
+ /** Menos texto que esto en una página la tratamos como escaneada. */
28
+ const MIN_TEXTO = 20;
29
+ /** Lado largo de la imagen de una página: el tamaño que Claude procesa sin reescalar. */
30
+ const LADO_IMAGEN = 1568;
31
+ /** Muestras por eje y por píxel al reducir la imagen; suaviza los bordes y mejora la lectura. */
32
+ const MUESTREO = 2;
33
+ export async function abrirPdf(bytes) {
34
+ const lib = await pdfjs();
35
+ const carga = lib.getDocument({
36
+ data: bytes,
37
+ verbosity: 0,
38
+ isOffscreenCanvasSupported: false,
39
+ // Directo a los decodificadores JS de vendor/pdfjs/wasm: en Node los .wasm no cargan igual.
40
+ useWasm: false,
41
+ wasmUrl: new URL("wasm/", VENDOR).href,
42
+ });
43
+ const pdf = await carga.promise;
44
+ return {
45
+ formato: "pdf",
46
+ unidad: "página",
47
+ total: pdf.numPages,
48
+ parte: async (n) => leerPagina(lib, await pdf.getPage(n)),
49
+ cerrar: () => carga.destroy(),
50
+ };
51
+ }
52
+ async function leerPagina(lib, pagina) {
53
+ const contenido = await pagina.getTextContent();
54
+ let texto = "";
55
+ for (const item of contenido.items) {
56
+ if (!("str" in item))
57
+ continue;
58
+ texto += item.str + (item.hasEOL ? "\n" : "");
59
+ }
60
+ texto = texto.replace(/[ \t]+/g, " ").replace(/ ?\n ?/g, "\n").trim();
61
+ if (texto.length >= MIN_TEXTO)
62
+ return { texto };
63
+ const escaneo = await rasterizarImagenes(lib, pagina);
64
+ if (escaneo)
65
+ return { titulo: "escaneada, como imagen", imagen: escaneo, mimeType: "image/png" };
66
+ return { texto: texto || "(página sin texto)" };
67
+ }
68
+ /**
69
+ * Reconstruye la página dibujando solo sus imágenes, con la posición y rotación con que el PDF
70
+ * las ubica. Una página escaneada es eso: una imagen. Así se evita un renderizador completo, que
71
+ * en Node necesita un canvas nativo.
72
+ */
73
+ async function rasterizarImagenes({ OPS, Util }, pagina) {
74
+ const base = pagina.getViewport({ scale: 1 });
75
+ const vista = pagina.getViewport({ scale: LADO_IMAGEN / Math.max(base.width, base.height) });
76
+ const ancho = Math.round(vista.width);
77
+ const alto = Math.round(vista.height);
78
+ const lienzo = new Uint8Array(ancho * alto).fill(255);
79
+ const ops = await pagina.getOperatorList();
80
+ let ctm = [1, 0, 0, 1, 0, 0];
81
+ const pila = [];
82
+ let pintadas = 0;
83
+ for (let i = 0; i < ops.fnArray.length; i++) {
84
+ const args = ops.argsArray[i];
85
+ switch (ops.fnArray[i]) {
86
+ case OPS.save:
87
+ pila.push(ctm);
88
+ break;
89
+ case OPS.restore:
90
+ ctm = pila.pop() ?? ctm;
91
+ break;
92
+ case OPS.transform:
93
+ ctm = Util.transform(ctm, args);
94
+ break;
95
+ case OPS.paintFormXObjectBegin:
96
+ pila.push(ctm);
97
+ if (args[0])
98
+ ctm = Util.transform(ctm, args[0]);
99
+ break;
100
+ case OPS.paintFormXObjectEnd:
101
+ ctm = pila.pop() ?? ctm;
102
+ break;
103
+ case OPS.paintImageXObject:
104
+ case OPS.paintInlineImageXObject: {
105
+ const imagen = typeof args[0] === "string" ? await new Promise((res) => pagina.objs.get(args[0], res)) : args[0];
106
+ if (imagen?.data && pintar(lienzo, ancho, alto, imagen, Util.transform(vista.transform, ctm))) {
107
+ pintadas++;
108
+ }
109
+ break;
110
+ }
111
+ }
112
+ }
113
+ return pintadas ? pngGris(ancho, alto, lienzo) : null;
114
+ }
115
+ /**
116
+ * Pinta una imagen en el lienzo. La imagen ocupa el cuadrado unitario transformado por `m`; por cada
117
+ * píxel del lienzo se busca el píxel de origen con la transformación inversa, así cualquier rotación
118
+ * o espejado sale bien sin casos especiales.
119
+ */
120
+ function pintar(lienzo, ancho, alto, img, m) {
121
+ const [a, b, c, d, e, f] = m;
122
+ const det = a * d - b * c;
123
+ if (!det)
124
+ return false;
125
+ const inv = [d / det, -b / det, -c / det, a / det, (c * f - d * e) / det, (b * e - a * f) / det];
126
+ const xs = [e, a + e, c + e, a + c + e];
127
+ const ys = [f, b + f, d + f, b + d + f];
128
+ const x0 = Math.max(0, Math.floor(Math.min(...xs)));
129
+ const x1 = Math.min(ancho, Math.ceil(Math.max(...xs)));
130
+ const y0 = Math.max(0, Math.floor(Math.min(...ys)));
131
+ const y1 = Math.min(alto, Math.ceil(Math.max(...ys)));
132
+ const { width: w, height: h, kind } = img;
133
+ const data = img.data;
134
+ const bytesPorFila = (w + 7) >> 3;
135
+ const canales = kind === 2 ? 3 : 4;
136
+ const gris = (col, fila) => {
137
+ if (kind === 1)
138
+ return ((data[fila * bytesPorFila + (col >> 3)] >> (7 - (col & 7))) & 1) * 255;
139
+ const i = (fila * w + col) * canales;
140
+ return data[i] * 0.3 + data[i + 1] * 0.59 + data[i + 2] * 0.11;
141
+ };
142
+ for (let y = y0; y < y1; y++) {
143
+ for (let x = x0; x < x1; x++) {
144
+ let suma = 0;
145
+ let n = 0;
146
+ for (let sy = 0; sy < MUESTREO; sy++) {
147
+ for (let sx = 0; sx < MUESTREO; sx++) {
148
+ const px = x + (sx + 0.5) / MUESTREO;
149
+ const py = y + (sy + 0.5) / MUESTREO;
150
+ const u = inv[0] * px + inv[2] * py + inv[4];
151
+ const v = inv[1] * px + inv[3] * py + inv[5];
152
+ if (u < 0 || u >= 1 || v < 0 || v >= 1)
153
+ continue;
154
+ // En el espacio de la imagen v crece hacia arriba; las filas de datos, hacia abajo.
155
+ suma += gris(Math.floor(u * w), Math.floor((1 - v) * h));
156
+ n++;
157
+ }
158
+ }
159
+ if (n)
160
+ lienzo[y * ancho + x] = suma / n;
161
+ }
162
+ }
163
+ return true;
164
+ }
@@ -0,0 +1,51 @@
1
+ import { deflateSync } from "node:zlib";
2
+ /** PNG en escala de grises, 8 bits. Alcanza para páginas escaneadas y evita una dependencia de imágenes. */
3
+ export function pngGris(ancho, alto, pixeles) {
4
+ // Cada fila va precedida por el byte de filtro (0 = sin filtro).
5
+ const filas = new Uint8Array(alto * (ancho + 1));
6
+ for (let y = 0; y < alto; y++)
7
+ filas.set(pixeles.subarray(y * ancho, (y + 1) * ancho), y * (ancho + 1) + 1);
8
+ const ihdr = new Uint8Array(13);
9
+ const vista = new DataView(ihdr.buffer);
10
+ vista.setUint32(0, ancho);
11
+ vista.setUint32(4, alto);
12
+ ihdr[8] = 8; // bits por canal
13
+ ihdr[9] = 0; // escala de grises
14
+ return concat([
15
+ new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
16
+ chunk("IHDR", ihdr),
17
+ chunk("IDAT", deflateSync(filas, { level: 6 })),
18
+ chunk("IEND", new Uint8Array()),
19
+ ]);
20
+ }
21
+ function chunk(tipo, datos) {
22
+ const out = new Uint8Array(12 + datos.length);
23
+ const vista = new DataView(out.buffer);
24
+ vista.setUint32(0, datos.length);
25
+ for (let i = 0; i < 4; i++)
26
+ out[4 + i] = tipo.charCodeAt(i);
27
+ out.set(datos, 8);
28
+ vista.setUint32(8 + datos.length, crc32(out.subarray(4, 8 + datos.length)));
29
+ return out;
30
+ }
31
+ const TABLA_CRC = Int32Array.from({ length: 256 }, (_, n) => {
32
+ let c = n;
33
+ for (let k = 0; k < 8; k++)
34
+ c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
35
+ return c;
36
+ });
37
+ function crc32(bytes) {
38
+ let c = -1;
39
+ for (const b of bytes)
40
+ c = TABLA_CRC[(c ^ b) & 0xff] ^ (c >>> 8);
41
+ return ~c >>> 0;
42
+ }
43
+ function concat(partes) {
44
+ const out = new Uint8Array(partes.reduce((n, p) => n + p.length, 0));
45
+ let i = 0;
46
+ for (const p of partes) {
47
+ out.set(p, i);
48
+ i += p.length;
49
+ }
50
+ return out;
51
+ }
@@ -0,0 +1,72 @@
1
+ import { inflateRawSync } from "node:zlib";
2
+ const FIN_DIRECTORIO = 0x06054b50;
3
+ const DIRECTORIO = 0x02014b50;
4
+ const ENCABEZADO_LOCAL = 0x04034b50;
5
+ const SIN_COMPRESION = 0;
6
+ const DEFLATE = 8;
7
+ class ZipInvalido extends Error {
8
+ constructor(detalle) {
9
+ super(`El archivo no es un zip válido: ${detalle}.`);
10
+ this.name = "ZipInvalido";
11
+ }
12
+ }
13
+ export function listarZip(bytes) {
14
+ const vista = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
15
+ // El fin del directorio está al final, seguido de un comentario opcional de hasta 64 KB.
16
+ let fin = -1;
17
+ for (let i = bytes.length - 22; i >= Math.max(0, bytes.length - 22 - 0xffff); i--) {
18
+ if (vista.getUint32(i, true) === FIN_DIRECTORIO) {
19
+ fin = i;
20
+ break;
21
+ }
22
+ }
23
+ if (fin < 0)
24
+ throw new ZipInvalido("no tiene índice");
25
+ const cantidad = vista.getUint16(fin + 10, true);
26
+ let p = vista.getUint32(fin + 16, true);
27
+ if (cantidad === 0xffff || p === 0xffffffff)
28
+ throw new ZipInvalido("usa zip64");
29
+ const entradas = [];
30
+ const nombres = new TextDecoder();
31
+ for (let i = 0; i < cantidad; i++) {
32
+ if (p + 46 > bytes.length || vista.getUint32(p, true) !== DIRECTORIO)
33
+ throw new ZipInvalido("índice corrupto");
34
+ const largoNombre = vista.getUint16(p + 28, true);
35
+ entradas.push({
36
+ nombre: nombres.decode(bytes.subarray(p + 46, p + 46 + largoNombre)),
37
+ metodo: vista.getUint16(p + 10, true),
38
+ comprimido: vista.getUint32(p + 20, true),
39
+ tamanio: vista.getUint32(p + 24, true),
40
+ offset: vista.getUint32(p + 42, true),
41
+ });
42
+ p += 46 + largoNombre + vista.getUint16(p + 30, true) + vista.getUint16(p + 32, true);
43
+ }
44
+ return entradas;
45
+ }
46
+ /**
47
+ * Descomprime una entrada. `max` corta aunque el índice mienta sobre el tamaño: un zip chico que se
48
+ * infla a gigas es un ataque conocido.
49
+ */
50
+ export function leerEntrada(bytes, entrada, max) {
51
+ if (entrada.tamanio > max)
52
+ throw new ZipInvalido(`"${entrada.nombre}" descomprimido pesa demasiado`);
53
+ const vista = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
54
+ const p = entrada.offset;
55
+ if (vista.getUint32(p, true) !== ENCABEZADO_LOCAL)
56
+ throw new ZipInvalido(`falta el encabezado de "${entrada.nombre}"`);
57
+ const inicio = p + 30 + vista.getUint16(p + 26, true) + vista.getUint16(p + 28, true);
58
+ const datos = bytes.subarray(inicio, inicio + entrada.comprimido);
59
+ switch (entrada.metodo) {
60
+ case SIN_COMPRESION:
61
+ return datos;
62
+ case DEFLATE:
63
+ try {
64
+ return inflateRawSync(datos, { maxOutputLength: max });
65
+ }
66
+ catch (e) {
67
+ throw new ZipInvalido(`no se pudo descomprimir "${entrada.nombre}" (${e.message})`);
68
+ }
69
+ default:
70
+ throw new ZipInvalido(`"${entrada.nombre}" usa una compresión no soportada (${entrada.metodo})`);
71
+ }
72
+ }
@@ -0,0 +1,19 @@
1
+ const ENTITIES = { nbsp: " ", amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" };
2
+ /** HTML de Moodle a texto plano: alcanza para que el modelo lo lea, no es un parser. */
3
+ export function htmlToText(html) {
4
+ if (!html)
5
+ return "";
6
+ return html
7
+ .replace(/<(script|style)[\s\S]*?<\/\1>/gi, "")
8
+ .replace(/<br\s*\/?>|<\/(p|div|li|h\d|tr)>/gi, "\n")
9
+ .replace(/<[^>]+>/g, "")
10
+ .replace(/&(#\d+|[a-z]+);/gi, (m, e) => e.startsWith("#") ? String.fromCodePoint(Number(e.slice(1))) : (ENTITIES[e.toLowerCase()] ?? m))
11
+ .replace(/[ \t ]+/g, " ")
12
+ .replace(/\s*\n\s*/g, "\n")
13
+ .trim();
14
+ }
15
+ /** Como htmlToText pero recortado: para índices, donde solo hace falta decidir si entrar. */
16
+ export function htmlToSnippet(html, max = 200) {
17
+ const texto = htmlToText(html);
18
+ return texto.length > max ? `${texto.slice(0, max).trimEnd()}…` : texto;
19
+ }
package/package.json CHANGED
@@ -1,18 +1,20 @@
1
1
  {
2
2
  "name": "utn-mcp",
3
- "version": "0.1.0",
3
+ "version": "0.2.1",
4
4
  "description": "Este es el Model Context Protocol server NO OFICIAL de la UTN para buscar informacion o archivos en el aula virtual.",
5
5
  "main": "build/index.js",
6
6
  "bin": {
7
7
  "utn-mcp": "build/index.js"
8
8
  },
9
9
  "files": [
10
- "build"
10
+ "build",
11
+ "vendor"
11
12
  ],
12
13
  "scripts": {
13
14
  "prebuild": "node -e \"require('fs').rmSync('build',{recursive:true,force:true})\"",
14
15
  "build": "tsc",
15
16
  "prepublishOnly": "npm run build",
17
+ "prepare": "node scripts/vendor-pdfjs.mjs",
16
18
  "start": "node build/index.js",
17
19
  "dev": "tsx src/index.ts",
18
20
  "test": "echo \"Error: no test specified\" && exit 1",
@@ -34,7 +36,7 @@
34
36
  "bugs": {
35
37
  "url": "https://github.com/nialvape/utn-mcp/issues"
36
38
  },
37
- "homepage": "https://github.com/nialvape/utn-mcp#readme",
39
+ "homepage": "https://utnmcp.com.ar",
38
40
  "dependencies": {
39
41
  "@modelcontextprotocol/node": "^2.1.1",
40
42
  "@modelcontextprotocol/server": "^2.3.0",
@@ -46,6 +48,7 @@
46
48
  "devDependencies": {
47
49
  "@types/express": "^5.0.6",
48
50
  "@types/node": "^26.6.4",
51
+ "pdfjs-dist": "^6.4.299",
49
52
  "tsx": "^4.23.15",
50
53
  "typescript": "^7.0.2"
51
54
  },