From f7c5d44f75fa209505f7a5fb522f2086bf249bd9 Mon Sep 17 00:00:00 2001 From: Carlos Lopez Date: Mon, 30 Nov 2026 15:46:19 +0100 Subject: [PATCH 1/5] feat: project tooling, Dockerfile and CI (#128) Co-Authored-By: Claude Opus 5.5 --- .dockerignore | 8 + .env.example | 8 + .github/workflows/ci.yml | 21 ++ .gitignore | 4 + .prettierignore | 4 + .prettierrc.json | 1 + Dockerfile | 26 ++ bun.lock | 578 +++++++++++++++++++++++++++++++++++++++ eslint.config.js | 20 ++ package.json | 35 +++ tsconfig.build.json | 5 + tsconfig.json | 17 ++ vitest.config.ts | 3 + 13 files changed, 730 insertions(+) create mode 100644 .dockerignore create mode 100644 .env.example create mode 100644 .github/workflows/ci.yml create mode 100644 .gitignore create mode 100644 .prettierignore create mode 100644 .prettierrc.json create mode 100644 Dockerfile create mode 100644 bun.lock create mode 100644 eslint.config.js create mode 100644 package.json create mode 100644 tsconfig.build.json create mode 100644 tsconfig.json create mode 100644 vitest.config.ts diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..2c9f143 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,8 @@ +node_modules +dist +.git +.github +.env +test +coverage +*.md diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..30733a4 --- /dev/null +++ b/.env.example @@ -0,0 +1,8 @@ +# Puerto HTTP del servidor MCP +PORT=3000 +# URL base de la API de GitOps (obligatoria), sin barra final +GITOPS_API_URL=https://cloud.getgitops.com +# Timeout de cada petición a la API, en ms +GITOPS_API_TIMEOUT_MS=10000 +# debug | info | warn | error | silent +LOG_LEVEL=info diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..d15972d --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,21 @@ +name: CI + +on: + pull_request: + push: + branches: [development, main] + +jobs: + check: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: oven-sh/setup-bun@v2 + - uses: actions/setup-node@v4 + with: + node-version: 22 + - run: bun install --frozen-lockfile + - run: bun run lint + - run: bun run typecheck + - run: bun run test + - run: bun run build diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4001f4f --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +node_modules +dist +.env +coverage diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 0000000..5b782b1 --- /dev/null +++ b/.prettierignore @@ -0,0 +1,4 @@ +node_modules +dist +bun.lock +license.md diff --git a/.prettierrc.json b/.prettierrc.json new file mode 100644 index 0000000..d2ee69b --- /dev/null +++ b/.prettierrc.json @@ -0,0 +1 @@ +{ "singleQuote": true, "printWidth": 100, "trailingComma": "all" } diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..c6e1785 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,26 @@ +FROM node:22-alpine AS build +WORKDIR /app +RUN npm install -g bun@1 +COPY package.json bun.lock ./ +RUN bun install --frozen-lockfile +COPY tsconfig.json tsconfig.build.json ./ +COPY src ./src +RUN bun run build + +FROM node:22-alpine AS deps +WORKDIR /app +RUN npm install -g bun@1 +COPY package.json bun.lock ./ +RUN bun install --frozen-lockfile --production + +FROM node:22-alpine +ENV NODE_ENV=production PORT=3000 +WORKDIR /app +COPY --from=deps /app/node_modules ./node_modules +COPY --from=build /app/dist ./dist +COPY package.json ./ +USER node +EXPOSE 3000 +HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \ + CMD wget -qO- "http://127.0.0.1:${PORT}/healthz" || exit 1 +CMD ["node", "dist/main.js"] diff --git a/bun.lock b/bun.lock new file mode 100644 index 0000000..a440e41 --- /dev/null +++ b/bun.lock @@ -0,0 +1,578 @@ +{ + "lockfileVersion": 1, + "configVersion": 1, + "workspaces": { + "": { + "name": "gitops-mcp", + "dependencies": { + "@modelcontextprotocol/sdk": "^1.32.2", + "zod": "^4.6.7", + }, + "devDependencies": { + "@eslint/js": "^10.0.1", + "@types/node": "^26.6.11", + "eslint": "^10.16.0", + "eslint-config-prettier": "^10.1.9", + "globals": "^17.14.0", + "prettier": "^3.10.1", + "tsx": "^4.23.15", + "typescript": "~5.9", + "typescript-eslint": "^8.74.0", + "vitest": "^5.1.2", + }, + }, + }, + "packages": { + "@cacheable/memory": ["@cacheable/memory@2.2.0", "", { "dependencies": { "@cacheable/utils": "^2.5.0", "@keyv/bigmap": "^1.3.1", "hookified": "^1.15.1", "keyv": "^5.6.0" } }, "sha512-CTLKqLItRCEixEAewD3/j9DB3/o96gpTPD4eJ1v+DGOlxZRZncRQkGYqqnAGCscYd6RNeXfGeiuCphsPtqyIfQ=="], + + "@cacheable/utils": ["@cacheable/utils@2.5.0", "", { "dependencies": { "hashery": "^1.5.1", "keyv": "^5.6.0" } }, "sha512-buipgOVDkkPXNR5+xBpDw7Zk2n1EvU7qBJCNUcL7rhQ//kfpOXPAvQ511Os0vpLYJ1pZnvudNytkQt2hst3wqA=="], + + "@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.28.2", "", { "os": "aix", "cpu": "ppc64" }, "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ=="], + + "@esbuild/android-arm": ["@esbuild/android-arm@0.28.2", "", { "os": "android", "cpu": "arm" }, "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg=="], + + "@esbuild/android-arm64": ["@esbuild/android-arm64@0.28.2", "", { "os": "android", "cpu": "arm64" }, "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A=="], + + "@esbuild/android-x64": ["@esbuild/android-x64@0.28.2", "", { "os": "android", "cpu": "x64" }, "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q=="], + + "@esbuild/darwin-arm64": ["@esbuild/darwin-arm64@0.28.2", "", { "os": "darwin", "cpu": "arm64" }, "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw=="], + + "@esbuild/darwin-x64": ["@esbuild/darwin-x64@0.28.2", "", { "os": "darwin", "cpu": "x64" }, "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw=="], + + "@esbuild/freebsd-arm64": ["@esbuild/freebsd-arm64@0.28.2", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw=="], + + "@esbuild/freebsd-x64": ["@esbuild/freebsd-x64@0.28.2", "", { "os": "freebsd", "cpu": "x64" }, "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg=="], + + "@esbuild/linux-arm": ["@esbuild/linux-arm@0.28.2", "", { "os": "linux", "cpu": "arm" }, "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w=="], + + "@esbuild/linux-arm64": ["@esbuild/linux-arm64@0.28.2", "", { "os": "linux", "cpu": "arm64" }, "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug=="], + + "@esbuild/linux-ia32": ["@esbuild/linux-ia32@0.28.2", "", { "os": "linux", "cpu": "ia32" }, "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ=="], + + "@esbuild/linux-loong64": ["@esbuild/linux-loong64@0.28.2", "", { "os": "linux", "cpu": "none" }, "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ=="], + + "@esbuild/linux-mips64el": ["@esbuild/linux-mips64el@0.28.2", "", { "os": "linux", "cpu": "none" }, "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA=="], + + "@esbuild/linux-ppc64": ["@esbuild/linux-ppc64@0.28.2", "", { "os": "linux", "cpu": "ppc64" }, "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ=="], + + "@esbuild/linux-riscv64": ["@esbuild/linux-riscv64@0.28.2", "", { "os": "linux", "cpu": "none" }, "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA=="], + + "@esbuild/linux-s390x": ["@esbuild/linux-s390x@0.28.2", "", { "os": "linux", "cpu": "s390x" }, "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg=="], + + "@esbuild/linux-x64": ["@esbuild/linux-x64@0.28.2", "", { "os": "linux", "cpu": "x64" }, "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ=="], + + "@esbuild/netbsd-arm64": ["@esbuild/netbsd-arm64@0.28.2", "", { "os": "none", "cpu": "arm64" }, "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw=="], + + "@esbuild/netbsd-x64": ["@esbuild/netbsd-x64@0.28.2", "", { "os": "none", "cpu": "x64" }, "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw=="], + + "@esbuild/openbsd-arm64": ["@esbuild/openbsd-arm64@0.28.2", "", { "os": "openbsd", "cpu": "arm64" }, "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ=="], + + "@esbuild/openbsd-x64": ["@esbuild/openbsd-x64@0.28.2", "", { "os": "openbsd", "cpu": "x64" }, "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw=="], + + "@esbuild/openharmony-arm64": ["@esbuild/openharmony-arm64@0.28.2", "", { "os": "none", "cpu": "arm64" }, "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q=="], + + "@esbuild/sunos-x64": ["@esbuild/sunos-x64@0.28.2", "", { "os": "sunos", "cpu": "x64" }, "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g=="], + + "@esbuild/win32-arm64": ["@esbuild/win32-arm64@0.28.2", "", { "os": "win32", "cpu": "arm64" }, "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ=="], + + "@esbuild/win32-ia32": ["@esbuild/win32-ia32@0.28.2", "", { "os": "win32", "cpu": "ia32" }, "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA=="], + + "@esbuild/win32-x64": ["@esbuild/win32-x64@0.28.2", "", { "os": "win32", "cpu": "x64" }, "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g=="], + + "@eslint-community/eslint-utils": ["@eslint-community/eslint-utils@4.10.1", "", { "dependencies": { "eslint-visitor-keys": "^3.4.3" }, "peerDependencies": { "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0" } }, "sha512-cuadcxVFE8sDK6iWJbs8Sn0av2Nrh2QSGQhVlBW9AaAHqHwjWsZHT8LJ4hFGPh7ASBV2deFdM7H/DPjulmh8rg=="], + + "@eslint-community/regexpp": ["@eslint-community/regexpp@4.12.4", "", {}, "sha512-1qH3WeISXHFS8P3QI0lntHlMrlfTh1OarxlRbPNDEkSCqoyXC3apBE7MDyRKOL8HpuW48aQtff30wvEFww/4ww=="], + + "@eslint/config-array": ["@eslint/config-array@0.23.7", "", { "dependencies": { "@eslint/object-schema": "^3.0.5", "debug": "^4.3.1", "minimatch": "^11.0.5" } }, "sha512-Ix1tmZjA7/OmE7ROAfORe83hVnqlDzLpZVHFjHQt5mvLm1U03qMexpaxKqFIL362QV32SoPaZqmKQr3tdqFY2w=="], + + "@eslint/config-helpers": ["@eslint/config-helpers@0.7.0", "", { "dependencies": { "@eslint/core": "^1.2.1" } }, "sha512-DObd/KKUsU+FaFv4PLxSRenpXfQWmPXXP3pPZ6/K1PCrMu2vQpMDMuQe/BqYeoLcz8ro0bVDF1RxOJgfVEdhUw=="], + + "@eslint/core": ["@eslint/core@1.2.1", "", { "dependencies": { "@types/json-schema": "^7.0.15" } }, "sha512-MwcE1P+AZ4C6DWlpin/OmOA54mmIZ/+xZuJiQd4SyB29oAJjN30UW9wkKNptW2ctp4cEsvhlLY/CsQ1uoHDloQ=="], + + "@eslint/js": ["@eslint/js@10.0.1", "", { "peerDependencies": { "eslint": "^10.0.0" }, "optionalPeers": ["eslint"] }, "sha512-zeR9k5pd4gxjZ0abRoIaxdc7I3nDktoXZk2qOv9gCNWx3mVwEn32VRhyLaRsDiJjTs0xq/T8mfPtyuXu7GWBcA=="], + + "@eslint/object-schema": ["@eslint/object-schema@3.0.5", "", {}, "sha512-vqTaUEgxzm+YDSdElad6PiRoX4t8VGDjCtt05zn4nU810UIx/uNEV7/lZJ6KwFThKZOzOxzXy48da+No7HZaMw=="], + + "@eslint/plugin-kit": ["@eslint/plugin-kit@0.7.3", "", { "dependencies": { "@eslint/core": "^1.2.1", "levn": "^0.4.1" } }, "sha512-IkO+/KEUvwbVpiURZg+P7zF74z5Jxe0UgJxVni+RtoHQ6IZieXaO02kmadomap/q+l6bc/jdPGGqTjhuZnuz1Q=="], + + "@hono/node-server": ["@hono/node-server@2.1.11", "", { "peerDependencies": { "hono": "^4 || ^5.0.0-0" } }, "sha512-KzKz9vl4vvr1vgLHamj+g5uonbrj5NwAdO3yzOS6cd2HjALVeOgTgeZOyAzNxejbkfOOPIcvuf/Tg8l1pEFLog=="], + + "@humanfs/core": ["@humanfs/core@0.19.2", "", { "dependencies": { "@humanfs/types": "^0.15.0" } }, "sha512-UhXNm+CFMWcbChXywFwkmhqjs3PRCmcSa/hfBgLIb7oQ5HNb1wS0icWsGtSAUNgefHeI+eBrA8I1fxmbHsGdvA=="], + + "@humanfs/node": ["@humanfs/node@0.16.8", "", { "dependencies": { "@humanfs/core": "^0.19.2", "@humanfs/types": "^0.15.0", "@humanwhocodes/retry": "^0.4.0" } }, "sha512-gE1eQNZ3R++kTzFUpdGlpmy8kDZD/MLyHqDwqjkVQI0JMdI1D51sy1H958PNXYkM2rAac7e5/CnIKZrHtPh3BQ=="], + + "@humanfs/types": ["@humanfs/types@0.15.0", "", {}, "sha512-ZZ1w0aoQkwuUuC7Yf+7sdeaNfqQiiLcSRbfI08oAxqLtpXQr9AIVX7Ay7HLDuiLYAaFPu8oBYNq/QIi9URHJ3Q=="], + + "@humanwhocodes/module-importer": ["@humanwhocodes/module-importer@1.0.1", "", {}, "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA=="], + + "@humanwhocodes/retry": ["@humanwhocodes/retry@0.4.3", "", {}, "sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ=="], + + "@isaacs/nonrecursive-glob-match": ["@isaacs/nonrecursive-glob-match@1.1.0", "", {}, "sha512-GPm/Dbvk5RLmhRnxXIa7nTpK0xtl4E0wj0MslsuNiJ1FIROU+2+9lgUC/dgF7Ey4QCWhfEsgxilMRMCdHPfDfw=="], + + "@jridgewell/resolve-uri": ["@jridgewell/resolve-uri@3.1.3", "", {}, "sha512-lhTtjtoEArWBjismtfS761S9Hlyn+nIZqOZVYoZ1Xn82PMNMVnk+jj/NhC4fAXGTs7ydONcJiR5vyQBTMDu27g=="], + + "@jridgewell/sourcemap-codec": ["@jridgewell/sourcemap-codec@1.6.0", "", {}, "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw=="], + + "@jridgewell/trace-mapping": ["@jridgewell/trace-mapping@0.3.31", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="], + + "@keyv/bigmap": ["@keyv/bigmap@1.3.1", "", { "dependencies": { "hashery": "^1.4.0", "hookified": "^1.15.0" }, "peerDependencies": { "keyv": "^5.6.0" } }, "sha512-WbzE9sdmQtKy8vrNPa9BRnwZh5UF4s1KTmSK0KUVLo3eff5BlQNNWDnFOouNpKfPKDnms9xynJjsMYjMaT/aFQ=="], + + "@keyv/serialize": ["@keyv/serialize@1.1.1", "", {}, "sha512-dXn3FZhPv0US+7dtJsIi2R+c7qWYiReoEh5zUntWCf4oSpMNib8FDhSoed6m3QyZdx5hK7iLFkYk3rNxwt8vTA=="], + + "@modelcontextprotocol/sdk": ["@modelcontextprotocol/sdk@1.32.2", "", { "dependencies": { "@hono/node-server": "^1.19.9 || ^2.0.5", "ajv": "^8.17.1", "ajv-formats": "^3.0.1", "content-type": "^1.0.5", "cors": "^2.8.5", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.0", "express": "^5.2.1", "express-rate-limit": "^8.2.1", "hono": "^4.11.4", "jose": "^6.1.3", "json-schema-typed": "^8.0.2", "pkce-challenge": "^5.0.0", "raw-body": "^3.0.0", "zod": "^3.25 || ^4.0", "zod-to-json-schema": "^3.25.1" }, "peerDependencies": { "@cfworker/json-schema": "^4.1.1" }, "optionalPeers": ["@cfworker/json-schema"] }, "sha512-SWsVtH/0vULSQStoZ6xxH2K09Li8fXYTMC64ZeogCdpZ3XSi1eCPOByV1OpuJxuI3OcmHhosDWYyii07tpPsLw=="], + + "@oxc-project/types": ["@oxc-project/types@0.160.0", "", {}, "sha512-gw4k9syEmnckbOgw2A2FU1TBDdX9hfwV9jEn/uio65pguPzwWiXQS3OIJDMEhv9m06tj9XiEe6RoD0YA+LgreA=="], + + "@rolldown/binding-android-arm-eabi": ["@rolldown/binding-android-arm-eabi@1.3.4", "", { "os": "android", "cpu": "arm" }, "sha512-xCW8CkL/ualx/SbYqeG9iK87lJCZGDQ0soE+kaORJ0Bd+pHALyE4qK7BStmEAyYWLEzZ3/biSIpA6/7GDFvzIg=="], + + "@rolldown/binding-android-arm64": ["@rolldown/binding-android-arm64@1.3.4", "", { "os": "android", "cpu": "arm64" }, "sha512-5lifIO+b/prcM9sx/bkPN4w6UEToEfQ3gjhx0+0neuL+dkYskI792CfAq03T51jc8JFcaYXs2hi3l8RjiH/VWQ=="], + + "@rolldown/binding-darwin-arm64": ["@rolldown/binding-darwin-arm64@1.3.4", "", { "os": "darwin", "cpu": "arm64" }, "sha512-RCgxTI4AJQxhVF//BI3ImQOsXTHrF4Eg+f99jBy8WoETA2kSEGFxpnrVmW0leQq/2aBR4R5AC6csmy3rc66e3Q=="], + + "@rolldown/binding-darwin-x64": ["@rolldown/binding-darwin-x64@1.3.4", "", { "os": "darwin", "cpu": "x64" }, "sha512-zNPJVVPUaDEj+L0lImoK3rFv2b+Z5gNijI6DWu/fcD3/1TfmRXKb9ZyxbSN+2AhlctqjbNzUvCsMa+EBhnEM4Q=="], + + "@rolldown/binding-freebsd-x64": ["@rolldown/binding-freebsd-x64@1.3.4", "", { "os": "freebsd", "cpu": "x64" }, "sha512-upP6g7ZIRy5by1RDQ/EphHIdJ5xK0eUD7sUgfZFWJ49s4XdbYsIvIlAPtrFpayR70Hhf9J22lb4Pm8/9FhrZmg=="], + + "@rolldown/binding-linux-arm-gnueabihf": ["@rolldown/binding-linux-arm-gnueabihf@1.3.4", "", { "os": "linux", "cpu": "arm" }, "sha512-SAX5C5+poMLCxu8dkPF6h5yst40rkzs+9Y3cbPn2OFSydmHjAEprrGi64zGgnYyPIVZfdGUFqJ2fJbfbnHI+mA=="], + + "@rolldown/binding-linux-arm64-gnu": ["@rolldown/binding-linux-arm64-gnu@1.3.4", "", { "os": "linux", "cpu": "arm64" }, "sha512-nwHqdlRZS6GWBef3dG5/pMY6RNTBBUjj7s0Da+m6xsFpe7jx6IC46SLZcCu8f46JOfCovZmwnrz51EzGE+7Fyw=="], + + "@rolldown/binding-linux-arm64-musl": ["@rolldown/binding-linux-arm64-musl@1.3.4", "", { "os": "linux", "cpu": "arm64" }, "sha512-Gr78X2ur/AgLCkmZgHffk/FerIX8S5zb/eII4bCcvJo0ANzeXhTShahdNbpnY6bpiszIAgIfiuKS9ziziWsamw=="], + + "@rolldown/binding-linux-ppc64-gnu": ["@rolldown/binding-linux-ppc64-gnu@1.3.4", "", { "os": "linux", "cpu": "ppc64" }, "sha512-o9Wcn8nWrsQasaBRYM4d//FwhlBsTJYWkPVlhlt6FwzpwEoovY4IopRZjk5Fq3+ntRuSDORJjF/nA8sFeF2q6w=="], + + "@rolldown/binding-linux-s390x-gnu": ["@rolldown/binding-linux-s390x-gnu@1.3.4", "", { "os": "linux", "cpu": "s390x" }, "sha512-UDWu4jkVcx2kiBKm3Ec//4lVCbeTWj8gmJ9SyLWCdLWtTlyq7fQVeVV/14nXvRtSLErvJ2+yA/Ux5taS31Y17Q=="], + + "@rolldown/binding-linux-x64-gnu": ["@rolldown/binding-linux-x64-gnu@1.3.4", "", { "os": "linux", "cpu": "x64" }, "sha512-W9mGtTa0w4fWh8RLMNPyaEhhcuqUfO07Q4I1bBc4PDMNg7gQSw0yPQNQ3D0qwbkXwxbyL4YrIzc8n6k1vuFExQ=="], + + "@rolldown/binding-linux-x64-musl": ["@rolldown/binding-linux-x64-musl@1.3.4", "", { "os": "linux", "cpu": "x64" }, "sha512-8B+ofyQZ7/aCmkqnyMonPr5zKLqMVNczhRGFNtdIuItiwNn8iQWJawMq2E58r7bxD1XEbtRRsULY/eCWwZQ01Q=="], + + "@rolldown/binding-openharmony-arm64": ["@rolldown/binding-openharmony-arm64@1.3.4", "", { "os": "none", "cpu": "arm64" }, "sha512-TlD0FSZaC7o2B4NCe9V5N11ugTnhzTM9ksj4sgRLvrKosDzjEkvlsTX3ehkw4ZlPv8AADimZZTvJGEa16pfXug=="], + + "@rolldown/binding-wasm32-wasi": ["@rolldown/binding-wasm32-wasi@1.3.4", "", { "dependencies": { "@oxc-project/types": "0.160.0" }, "cpu": "none" }, "sha512-jwO8P3o53ygo7b5061B7BeaJ1BGv3BKZ6jroFdw/01qWry7Z+qNBlDvulzbTle5s/A0Fc1FRgsTxrke9DvsSbA=="], + + "@rolldown/binding-win32-arm64-msvc": ["@rolldown/binding-win32-arm64-msvc@1.3.4", "", { "os": "win32", "cpu": "arm64" }, "sha512-8adGMrNtrdzi2WD1ozhYapER59gD8Q/DV6SCKJlyG2HqULPdeQUBvMa33lTsiEYwIqTZUaIU2MmvPp5f1wbtXA=="], + + "@rolldown/binding-win32-x64-msvc": ["@rolldown/binding-win32-x64-msvc@1.3.4", "", { "os": "win32", "cpu": "x64" }, "sha512-rIMjtESdXJCIoOiUTroQ1Y1rjVDZkuUVRUxs3APX2vNv175D7TDWvzdELiIhzGq9cUNUFat+co+PTmPHPqSREg=="], + + "@rolldown/pluginutils": ["@rolldown/pluginutils@1.1.1", "", {}, "sha512-glFIJDvLNDtJhT9qrMFWLPbvS+skxgt4L0K8Ei2YtnhPysAJnsI7nyxSJxKj4ADeKX0OLjC4ntRkwpLOoS3rwA=="], + + "@types/chai": ["@types/chai@5.2.3", "", { "dependencies": { "@types/deep-eql": "*", "assertion-error": "^2.0.1" } }, "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA=="], + + "@types/deep-eql": ["@types/deep-eql@4.0.2", "", {}, "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw=="], + + "@types/esrecurse": ["@types/esrecurse@4.3.1", "", {}, "sha512-xJBAbDifo5hpffDBuHl0Y8ywswbiAp/Wi7Y/GtAgSlZyIABppyurxVueOPE8LUQOxdlgi6Zqce7uoEpqNTeiUw=="], + + "@types/estree": ["@types/estree@1.0.11", "", {}, "sha512-YBdNe5JcjYR0sPhJW1QIeRCmI11YhYvaRuGCs9+WCeTTb+Yhb2BE2XMe5/wAqF10FK5g3+q1PDhQABfT7aX0gg=="], + + "@types/json-schema": ["@types/json-schema@7.0.15", "", {}, "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA=="], + + "@types/node": ["@types/node@26.6.11", "", { "dependencies": { "undici-types": "~8.9.0" } }, "sha512-uUyQ2XLEz+EXh34lmS3GhKrkqn/8FU7KUiKRpk347At2bmnMVWss45yz8b4FG/tUtmV1tV/+TVkITItPROyeeQ=="], + + "@typescript-eslint/eslint-plugin": ["@typescript-eslint/eslint-plugin@8.74.0", "", { "dependencies": { "@eslint-community/regexpp": "^4.12.2", "@typescript-eslint/scope-manager": "8.74.0", "@typescript-eslint/type-utils": "8.74.0", "@typescript-eslint/utils": "8.74.0", "@typescript-eslint/visitor-keys": "8.74.0", "ignore": "^7.0.5", "natural-compare": "^1.4.0", "ts-api-utils": "^2.5.0" }, "peerDependencies": { "@typescript-eslint/parser": "^8.74.0", "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", "typescript": ">=4.8.4 <6.1.0" } }, "sha512-z3KXk1+Vm+d82ZRplOoC89ho4Rf1da5ju6sx8//92GnN532U62DGPjECXkkVqtYzIv0zoJlpO39SX2Z9tk6LVw=="], + + "@typescript-eslint/parser": ["@typescript-eslint/parser@8.74.0", "", { "dependencies": { "@typescript-eslint/scope-manager": "8.74.0", "@typescript-eslint/types": "8.74.0", "@typescript-eslint/typescript-estree": "8.74.0", "@typescript-eslint/visitor-keys": "8.74.0", "debug": "^4.4.3" }, "peerDependencies": { "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", "typescript": ">=4.8.4 <6.1.0" } }, "sha512-ecr8AYdig7avVkxaHdQvxHnIJ/mOyliO4Gv/uWF8q69vBew/z3sexqBwHUZX5Vql+Ns0w4sH6gBLkICGbOvJkA=="], + + "@typescript-eslint/project-service": ["@typescript-eslint/project-service@8.74.0", "", { "dependencies": { "@typescript-eslint/tsconfig-utils": "^8.74.0", "@typescript-eslint/types": "^8.74.0", "debug": "^4.4.3" }, "peerDependencies": { "typescript": ">=4.8.4 <6.1.0" } }, "sha512-z/mymuE+JlEeSFIv3Mo70EvgG1Zz74Hl0IDfExfXutARAP834bt+MppTD7mVAwmZO0GdxdOAi0jbTam749eH6g=="], + + "@typescript-eslint/scope-manager": ["@typescript-eslint/scope-manager@8.74.0", "", { "dependencies": { "@typescript-eslint/types": "8.74.0", "@typescript-eslint/visitor-keys": "8.74.0" } }, "sha512-kpOdpu4CpWN5U38ox3f727DwWRBtUAVhyUJtqTBYe5gf2wYoxac7PgKP14txrxN7ICVtcjlLdzjqfRgpSnDKvQ=="], + + "@typescript-eslint/tsconfig-utils": ["@typescript-eslint/tsconfig-utils@8.74.0", "", { "peerDependencies": { "typescript": ">=4.8.4 <6.1.0" } }, "sha512-p07wAuaS6BjCYgOSXKJi4YhvTnAf7fiG37e9THcpnYaQEt2QiTTYZWKwUFNgeRiywiMudazhzgddAirZ0GgHtQ=="], + + "@typescript-eslint/type-utils": ["@typescript-eslint/type-utils@8.74.0", "", { "dependencies": { "@typescript-eslint/types": "8.74.0", "@typescript-eslint/typescript-estree": "8.74.0", "@typescript-eslint/utils": "8.74.0", "debug": "^4.4.3", "ts-api-utils": "^2.5.0" }, "peerDependencies": { "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", "typescript": ">=4.8.4 <6.1.0" } }, "sha512-CV3Y3la8l3F9ANfxcfpgSSiQgJTe4IeLEoZV4O/gcW86Ugp8X6SKiQ0vm+QegXaRIbbDMokZZSF3A1CgiU/kPw=="], + + "@typescript-eslint/types": ["@typescript-eslint/types@8.74.0", "", {}, "sha512-MpnMrJCVNpP1iVL8NiHkQZgQqIMBH5ewDGUPBh1pqQXwFtMFjsl1M03QcYPXmv6stCKEiF0PN7CGbU1ZbXFzEA=="], + + "@typescript-eslint/typescript-estree": ["@typescript-eslint/typescript-estree@8.74.0", "", { "dependencies": { "@typescript-eslint/project-service": "8.74.0", "@typescript-eslint/tsconfig-utils": "8.74.0", "@typescript-eslint/types": "8.74.0", "@typescript-eslint/visitor-keys": "8.74.0", "debug": "^4.4.3", "minimatch": "^11.0.1", "semver": "^7.7.3", "tinyglobby": "^0.2.15", "ts-api-utils": "^2.5.0" }, "peerDependencies": { "@typescript/native": "npm:typescript@>=7.1.0-dev.20261009.1 || >=7.1.0-beta <7.1.0-dev", "typescript": ">=4.8.4 <6.1.0" }, "optionalPeers": ["@typescript/native"] }, "sha512-wL348k6l92DNG+kPP5rVpKwNBoz7a3xRZy3TPKc1uymQttd7u7gcMv3eENmcuh4CjC4mO3FTM0DYstFXMyDLuw=="], + + "@typescript-eslint/utils": ["@typescript-eslint/utils@8.74.0", "", { "dependencies": { "@eslint-community/eslint-utils": "^4.9.1", "@typescript-eslint/scope-manager": "8.74.0", "@typescript-eslint/types": "8.74.0", "@typescript-eslint/typescript-estree": "8.74.0" }, "peerDependencies": { "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", "typescript": ">=4.8.4 <6.1.0" } }, "sha512-IpWXPxXXomzxyTcvjhZJexgdvtTR1TooLAPpuxzaGqQ8BHll1lf4Ysp/BTE/l0U5TJ+x1j7B4bEM8pLRrvY+XA=="], + + "@typescript-eslint/visitor-keys": ["@typescript-eslint/visitor-keys@8.74.0", "", { "dependencies": { "@typescript-eslint/types": "8.74.0", "eslint-visitor-keys": "^5.0.0" } }, "sha512-XSZmOtMUbWCBIM+2BK134FyMFxmll1mW2mPLk/PSwYQYzGIPMgJAqL929U4qXVizLv7Xq5b7r41/o7Ombuwk0g=="], + + "@vitest/mocker": ["@vitest/mocker@5.1.2", "", { "dependencies": { "@jridgewell/trace-mapping": "0.3.31", "@vitest/spy": "5.1.2", "estree-walker": "^3.0.3", "magic-string": "^1.4.5" }, "peerDependencies": { "msw": "^2.4.9 || ^3.0.0", "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" }, "optionalPeers": ["msw", "vite"] }, "sha512-UGc97wUIy0Ji2+9GxzHEJiOhiwkaukgE7VYcUNnjpX3sWnwQ8XogmNXX4WyOukxYgKb8Nh2XFa7KId0ZjpmVhQ=="], + + "@vitest/spy": ["@vitest/spy@5.1.2", "", {}, "sha512-PQl0/3+p9GaY71+MHywN6oyHfLhVDD5kcbm7oNRldA2F0ExMU3S8RQdnpteJ9gFAdK5P6KCgE6LqCpUgy57KzA=="], + + "accepts": ["accepts@2.0.0", "", { "dependencies": { "mime-types": "^3.0.0", "negotiator": "^1.0.0" } }, "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng=="], + + "acorn": ["acorn@8.19.0", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-oJlA3XiRm7Cyk6qFD2Jn8ak9B7jSy0qy00ADO3+8dpT0LSjFihQYv4C02LFCSYJV3Q37xYwwRy5m+IpIiUzqWw=="], + + "acorn-jsx": ["acorn-jsx@5.3.2", "", { "peerDependencies": { "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" } }, "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ=="], + + "ajv": ["ajv@6.15.0", "", { "dependencies": { "fast-deep-equal": "^3.1.1", "fast-json-stable-stringify": "^2.0.0", "json-schema-traverse": "^0.4.1", "uri-js": "^4.2.2" } }, "sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw=="], + + "ajv-formats": ["ajv-formats@3.0.1", "", { "dependencies": { "ajv": "^8.0.0" } }, "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ=="], + + "assertion-error": ["assertion-error@2.0.1", "", {}, "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA=="], + + "balanced-match": ["balanced-match@4.0.4", "", {}, "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA=="], + + "body-parser": ["body-parser@2.4.0", "", { "dependencies": { "bytes": "^3.1.2", "content-type": "^2.1.0", "debug": "^4.4.3", "http-errors": "^2.0.1", "iconv-lite": "^0.7.3", "on-finished": "^2.4.1", "qs": "^6.16.1", "raw-body": "^3.0.2", "type-is": "^2.1.0" } }, "sha512-Ifk1KcLrxaGt1occQagQNFNNOqRt1LFuehEnHHzB8Z6cRgIxRU1TBaiIsUiCdA+gy5PL7Y1IX31DNKkRmxtXjQ=="], + + "brace-expansion": ["brace-expansion@5.1.2", "", { "dependencies": { "balanced-match": "^4.0.2" } }, "sha512-ELhY3JEerIBbhgW+rh0/8glkZAaMqn1x3BAvp3yTULSEGozMK/5PT6WTdBgsdvJqwwmv7MAQNOydfYbvK1Vgfw=="], + + "bytes": ["bytes@3.1.2", "", {}, "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg=="], + + "cacheable": ["cacheable@2.5.0", "", { "dependencies": { "@cacheable/memory": "^2.2.0", "@cacheable/utils": "^2.5.0", "hookified": "^1.15.0", "keyv": "^5.6.0", "qified": "^0.10.1" } }, "sha512-60cyAOytib/OzBw1JNSoSV/boK1AtHryDIjvVBk7XbN4ugfkM3+Sry7fEjNgPMGgOjuaZPAp8ruZ0Cxafwyq9g=="], + + "call-bind-apply-helpers": ["call-bind-apply-helpers@1.0.2", "", { "dependencies": { "es-errors": "^1.3.0", "function-bind": "^1.1.2" } }, "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ=="], + + "call-bound": ["call-bound@1.0.4", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.2", "get-intrinsic": "^1.3.0" } }, "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg=="], + + "chai": ["chai@6.3.0", "", {}, "sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg=="], + + "content-disposition": ["content-disposition@2.0.1", "", {}, "sha512-e+H0ZXHSWYrENhQzw1LPuP4oF5MzVKmDU6d3hxlvaPEYLLg62MxtQNPRx4SYSuYJSBUgnQIG4HIN2tEtNv7Dog=="], + + "content-type": ["content-type@1.0.5", "", {}, "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA=="], + + "cookie": ["cookie@0.7.2", "", {}, "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w=="], + + "cookie-signature": ["cookie-signature@1.2.2", "", {}, "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg=="], + + "cors": ["cors@2.8.6", "", { "dependencies": { "object-assign": "^4", "vary": "^1" } }, "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw=="], + + "cross-spawn": ["cross-spawn@7.1.2", "", { "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", "which": "^2.0.1" } }, "sha512-8BPK2r+sKWC8sDinRwLwrFMq2lXTBBwzYYEB9LiCznfMurOi4FOvQflq3XOLGG+HPdMSVpe+k/s96+AtDEOgPg=="], + + "debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="], + + "deep-is": ["deep-is@0.1.4", "", {}, "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ=="], + + "depd": ["depd@2.0.0", "", {}, "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw=="], + + "detect-libc": ["detect-libc@2.1.2", "", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="], + + "dunder-proto": ["dunder-proto@1.0.1", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.1", "es-errors": "^1.3.0", "gopd": "^1.2.0" } }, "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A=="], + + "ee-first": ["ee-first@1.1.1", "", {}, "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow=="], + + "encodeurl": ["encodeurl@2.0.3", "", {}, "sha512-mIteYONiEfc4xWf2F1WXovh1c8npzS00vNeiUPdwFF+QlVJni+gNvpQltLMQhob8rew/bWWc/bGTuUr0EUGt0w=="], + + "es-define-property": ["es-define-property@1.0.1", "", {}, "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g=="], + + "es-errors": ["es-errors@1.3.0", "", {}, "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw=="], + + "es-module-lexer": ["es-module-lexer@2.3.2", "", {}, "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw=="], + + "es-object-atoms": ["es-object-atoms@1.1.2", "", { "dependencies": { "es-errors": "^1.3.0" } }, "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw=="], + + "esbuild": ["esbuild@0.28.2", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.28.2", "@esbuild/android-arm": "0.28.2", "@esbuild/android-arm64": "0.28.2", "@esbuild/android-x64": "0.28.2", "@esbuild/darwin-arm64": "0.28.2", "@esbuild/darwin-x64": "0.28.2", "@esbuild/freebsd-arm64": "0.28.2", "@esbuild/freebsd-x64": "0.28.2", "@esbuild/linux-arm": "0.28.2", "@esbuild/linux-arm64": "0.28.2", "@esbuild/linux-ia32": "0.28.2", "@esbuild/linux-loong64": "0.28.2", "@esbuild/linux-mips64el": "0.28.2", "@esbuild/linux-ppc64": "0.28.2", "@esbuild/linux-riscv64": "0.28.2", "@esbuild/linux-s390x": "0.28.2", "@esbuild/linux-x64": "0.28.2", "@esbuild/netbsd-arm64": "0.28.2", "@esbuild/netbsd-x64": "0.28.2", "@esbuild/openbsd-arm64": "0.28.2", "@esbuild/openbsd-x64": "0.28.2", "@esbuild/openharmony-arm64": "0.28.2", "@esbuild/sunos-x64": "0.28.2", "@esbuild/win32-arm64": "0.28.2", "@esbuild/win32-ia32": "0.28.2", "@esbuild/win32-x64": "0.28.2" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA=="], + + "escape-html": ["escape-html@1.0.3", "", {}, "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow=="], + + "escape-string-regexp": ["escape-string-regexp@4.0.0", "", {}, "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA=="], + + "eslint": ["eslint@10.16.0", "", { "dependencies": { "@eslint-community/eslint-utils": "^4.8.0", "@eslint-community/regexpp": "^4.12.2", "@eslint/config-array": "^0.23.7", "@eslint/config-helpers": "^0.7.0", "@eslint/core": "^1.2.1", "@eslint/plugin-kit": "^0.7.3", "@humanfs/node": "^0.16.8", "@humanwhocodes/module-importer": "^1.0.1", "@humanwhocodes/retry": "^0.4.2", "@types/estree": "^1.0.6", "ajv": "^6.14.0", "cross-spawn": "^7.0.6", "debug": "^4.3.2", "escape-string-regexp": "^4.0.0", "eslint-scope": "^9.1.2", "eslint-visitor-keys": "^5.0.1", "espree": "^11.2.0", "esquery": "^1.7.0", "esutils": "^2.0.2", "fast-deep-equal": "^3.1.3", "file-entry-cache": "11.1.5 || >11.1.6 <12", "find-up": "^5.0.0", "glob-parent": "^6.0.2", "ignore": "^5.2.0", "imurmurhash": "^0.1.4", "is-glob": "^4.0.0", "json-stable-stringify-without-jsonify": "^1.0.1", "minimatch": "^11.0.5", "natural-compare": "^1.4.0", "optionator": "^0.9.3" }, "peerDependencies": { "jiti": "*" }, "optionalPeers": ["jiti"], "bin": { "eslint": "bin/eslint.js" } }, "sha512-Xu3PRLG/wCaZWZ20gkExUcNqL2mWWsXTR+Lln3Sof4Y9WuA678fH9hrlQ8B6UNwbTnsKdDdBYOd2jxtycXVTGQ=="], + + "eslint-config-prettier": ["eslint-config-prettier@10.1.9", "", { "peerDependencies": { "eslint": ">=7.0.0" }, "bin": { "eslint-config-prettier": "bin/cli.js" } }, "sha512-JnOR0K4u67CWOiSS3vaduGlLUWS32lGiyglMIV6AyvK9DBRpS+QhR2ESKaUe2eWGRsdVmrxy77yaOk2hzDa4Bg=="], + + "eslint-scope": ["eslint-scope@9.1.2", "", { "dependencies": { "@types/esrecurse": "^4.3.1", "@types/estree": "^1.0.8", "esrecurse": "^4.3.0", "estraverse": "^5.2.0" } }, "sha512-xS90H51cKw0jltxmvmHy2Iai1LIqrfbw57b79w/J7MfvDfkIkFZ+kj6zC3BjtUwh150HsSSdxXZcsuv72miDFQ=="], + + "eslint-visitor-keys": ["eslint-visitor-keys@5.0.1", "", {}, "sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA=="], + + "espree": ["espree@11.2.0", "", { "dependencies": { "acorn": "^8.16.0", "acorn-jsx": "^5.3.2", "eslint-visitor-keys": "^5.0.1" } }, "sha512-7p3DrVEIopW1B1avAGLuCSh1jubc01H2JHc8B4qqGblmg5gI9yumBgACjWo4JlIc04ufug4xJ3SQI8HkS/Rgzw=="], + + "esquery": ["esquery@1.7.0", "", { "dependencies": { "estraverse": "^5.1.0" } }, "sha512-Ap6G0WQwcU/LHsvLwON1fAQX9Zp0A2Y6Y/cJBl9r/JbW90Zyg4/zbG6zzKa2OTALELarYHmKu0GhpM5EO+7T0g=="], + + "esrecurse": ["esrecurse@4.3.0", "", { "dependencies": { "estraverse": "^5.2.0" } }, "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag=="], + + "estraverse": ["estraverse@5.3.0", "", {}, "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA=="], + + "estree-walker": ["estree-walker@3.0.3", "", { "dependencies": { "@types/estree": "^1.0.0" } }, "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g=="], + + "esutils": ["esutils@2.0.3", "", {}, "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g=="], + + "etag": ["etag@1.8.1", "", {}, "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg=="], + + "eventsource": ["eventsource@3.0.7", "", { "dependencies": { "eventsource-parser": "^3.0.1" } }, "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA=="], + + "eventsource-parser": ["eventsource-parser@3.1.1", "", {}, "sha512-EKN1vKAMcZ8MlYMpaNuxN6R9yakzH6uajHcHVTqWJzvu5pWw9DyhbP35HH8MVBQ+dZjAfDxk+A8NiR9KWaXiyQ=="], + + "expect-type": ["expect-type@1.4.0", "", {}, "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA=="], + + "express": ["express@5.3.0", "", { "dependencies": { "accepts": "^2.0.0", "body-parser": "^2.3.0", "content-disposition": "^2.0.1", "content-type": "^2.0.0", "cookie": "^0.7.1", "cookie-signature": "^1.2.1", "debug": "^4.4.0", "depd": "^2.0.0", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "etag": "^1.8.1", "finalhandler": "^2.1.0", "fresh": "^2.0.0", "http-errors": "^2.0.0", "merge-descriptors": "^2.0.0", "mime-types": "^3.0.0", "on-finished": "^2.4.1", "once": "^1.4.0", "parseurl": "^1.3.3", "proxy-addr": "^2.0.8", "qs": "^6.16.0", "range-parser": "^1.2.1", "router": "^2.2.0", "send": "^1.1.0", "serve-static": "^2.2.0", "statuses": "^2.0.1", "type-is": "^2.1.0", "vary": "^1.1.2" } }, "sha512-qCqy1xSoaugxOD4IVHb1ZWdkvCF2W3aE2okKouWj8VwJ+ztskSiXoBnCSJqfKT+cVPJhuJqe9YLbY425+Zh00g=="], + + "express-rate-limit": ["express-rate-limit@8.7.5", "", { "dependencies": { "debug": "^4.4.3", "ip-address": "^10.2.0" }, "peerDependencies": { "express": ">= 4.11" } }, "sha512-wi+v38cx2EqD0JnhE/e74o5tFqKWUOAPFJIgyEiqJ8v2MNpoOAA3kI2hXYOI+YM+HE5yqbdAlVxm2GqOIeYOgA=="], + + "fast-deep-equal": ["fast-deep-equal@3.1.3", "", {}, "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q=="], + + "fast-json-stable-stringify": ["fast-json-stable-stringify@2.1.0", "", {}, "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw=="], + + "fast-levenshtein": ["fast-levenshtein@2.0.6", "", {}, "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw=="], + + "fast-uri": ["fast-uri@3.1.9", "", {}, "sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ=="], + + "fdir": ["fdir@6.5.0", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="], + + "file-entry-cache": ["file-entry-cache@11.1.5", "", { "dependencies": { "flat-cache": "^6.1.23" } }, "sha512-+PFTHITI08JIGhnNpGNI8T8inUpgZfk3GNEqfT9R2zZV2iFXg3CvqzSl/uEhs7TSGujYRELEANyDvS8Fj7+S7Q=="], + + "finalhandler": ["finalhandler@2.1.1", "", { "dependencies": { "debug": "^4.4.0", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "on-finished": "^2.4.1", "parseurl": "^1.3.3", "statuses": "^2.0.1" } }, "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA=="], + + "find-up": ["find-up@5.0.0", "", { "dependencies": { "locate-path": "^6.0.0", "path-exists": "^4.0.0" } }, "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng=="], + + "flat-cache": ["flat-cache@6.1.23", "", { "dependencies": { "cacheable": "^2.5.0", "flatted": "^3.4.2", "hookified": "^1.15.0" } }, "sha512-f++BY9pTk+983xK1FLzlLpmM0i0z+jHmx3QESGkURMXujQZz1k5wzwX6hjnQ8goaD0B+sYnDK1yZ6MTyZfUaqA=="], + + "flatted": ["flatted@3.5.0", "", {}, "sha512-H1rcmGe7Uf0PeYcuqKoc+/0+b1QX5QEya1kPyJhx4JnZcQateq0R0MGBi6aHSPuptJ/EtnnP94/saw0M3pOJTw=="], + + "forwarded": ["forwarded@0.2.0", "", {}, "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow=="], + + "fresh": ["fresh@2.0.0", "", {}, "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A=="], + + "fsevents": ["fsevents@2.3.3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="], + + "function-bind": ["function-bind@1.1.2", "", {}, "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA=="], + + "get-intrinsic": ["get-intrinsic@1.3.0", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.2", "es-define-property": "^1.0.1", "es-errors": "^1.3.0", "es-object-atoms": "^1.1.1", "function-bind": "^1.1.2", "get-proto": "^1.0.1", "gopd": "^1.2.0", "has-symbols": "^1.1.0", "hasown": "^2.0.2", "math-intrinsics": "^1.1.0" } }, "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ=="], + + "get-proto": ["get-proto@1.0.1", "", { "dependencies": { "dunder-proto": "^1.0.1", "es-object-atoms": "^1.0.0" } }, "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g=="], + + "glob-parent": ["glob-parent@6.0.2", "", { "dependencies": { "is-glob": "^4.0.3" } }, "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A=="], + + "globals": ["globals@17.14.0", "", {}, "sha512-UtdkTVyAJePQv0J2M9Xe4L0ruNSDV314XiIJsADI2Zf40bcdAonE/D/OhAU8AT99oij9mhLByb+NvA3QWZYgCg=="], + + "gopd": ["gopd@1.2.0", "", {}, "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg=="], + + "has-symbols": ["has-symbols@1.1.0", "", {}, "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ=="], + + "hashery": ["hashery@1.5.1", "", { "dependencies": { "hookified": "^1.15.0" } }, "sha512-iZyKG96/JwPz1N55vj2Ie2vXbhu440zfUfJvSwEqEbeLluk7NnapfGqa7LH0mOsnDxTF85Mx8/dyR6HfqcbmbQ=="], + + "hasown": ["hasown@2.0.4", "", { "dependencies": { "function-bind": "^1.1.2" } }, "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A=="], + + "hono": ["hono@4.13.23", "", {}, "sha512-OS90dj7dcsftEEWCOef8jRbnHE5lbrOq0hNRqjSyPsOnaGZvvfof1KS05hQNb4kUOCfDq1mG3PmHoX37DMnHQg=="], + + "hookified": ["hookified@1.15.1", "", {}, "sha512-MvG/clsADq1GPM2KGo2nyfaWVyn9naPiXrqIe4jYjXNZQt238kWyOGrsyc/DmRAQ+Re6yeo6yX/yoNCG5KAEVg=="], + + "http-errors": ["http-errors@2.0.1", "", { "dependencies": { "depd": "~2.0.0", "inherits": "~2.0.4", "setprototypeof": "~1.2.0", "statuses": "~2.0.2", "toidentifier": "~1.0.1" } }, "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ=="], + + "iconv-lite": ["iconv-lite@0.7.3", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ=="], + + "ignore": ["ignore@5.3.2", "", {}, "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g=="], + + "imurmurhash": ["imurmurhash@0.1.4", "", {}, "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA=="], + + "inherits": ["inherits@2.0.4", "", {}, "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="], + + "ip-address": ["ip-address@10.7.7", "", {}, "sha512-He15rAs4jip5AEAz7XM9L+S6Y8LBMIDj6YewbYuJfmDnOCKWb+3TLOGnHFBTAIW7wpm5ohtZ+Xyo5PEaG+O2vQ=="], + + "ipaddr.js": ["ipaddr.js@1.9.1", "", {}, "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g=="], + + "is-extglob": ["is-extglob@2.1.1", "", {}, "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ=="], + + "is-glob": ["is-glob@4.0.3", "", { "dependencies": { "is-extglob": "^2.1.1" } }, "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg=="], + + "is-promise": ["is-promise@4.0.0", "", {}, "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ=="], + + "isexe": ["isexe@2.0.0", "", {}, "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw=="], + + "jose": ["jose@6.2.18", "", {}, "sha512-doV4thUwgkrycJH4yLeqwTGIIZphHl+pk7CPReuMIhYhncmgzdko85MaCG4YQFTxqMFr1/oEH32tZuKKovcDEg=="], + + "json-schema-traverse": ["json-schema-traverse@0.4.1", "", {}, "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg=="], + + "json-schema-typed": ["json-schema-typed@8.0.2", "", {}, "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA=="], + + "json-stable-stringify-without-jsonify": ["json-stable-stringify-without-jsonify@1.0.1", "", {}, "sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw=="], + + "keyv": ["keyv@5.6.0", "", { "dependencies": { "@keyv/serialize": "^1.1.1" } }, "sha512-CYDD3SOtsHtyXeEORYRx2qBtpDJFjRTGXUtmNEMGyzYOKj1TE3tycdlho7kA1Ufx9OYWZzg52QFBGALTirzDSw=="], + + "levn": ["levn@0.4.1", "", { "dependencies": { "prelude-ls": "^1.2.1", "type-check": "~0.4.0" } }, "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ=="], + + "lightningcss": ["lightningcss@1.33.0", "", { "dependencies": { "detect-libc": "^2.0.3" }, "optionalDependencies": { "lightningcss-android-arm64": "1.33.0", "lightningcss-darwin-arm64": "1.33.0", "lightningcss-darwin-x64": "1.33.0", "lightningcss-freebsd-x64": "1.33.0", "lightningcss-linux-arm-gnueabihf": "1.33.0", "lightningcss-linux-arm64-gnu": "1.33.0", "lightningcss-linux-arm64-musl": "1.33.0", "lightningcss-linux-x64-gnu": "1.33.0", "lightningcss-linux-x64-musl": "1.33.0", "lightningcss-win32-arm64-msvc": "1.33.0", "lightningcss-win32-x64-msvc": "1.33.0" } }, "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA=="], + + "lightningcss-android-arm64": ["lightningcss-android-arm64@1.33.0", "", { "os": "android", "cpu": "arm64" }, "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg=="], + + "lightningcss-darwin-arm64": ["lightningcss-darwin-arm64@1.33.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg=="], + + "lightningcss-darwin-x64": ["lightningcss-darwin-x64@1.33.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ=="], + + "lightningcss-freebsd-x64": ["lightningcss-freebsd-x64@1.33.0", "", { "os": "freebsd", "cpu": "x64" }, "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg=="], + + "lightningcss-linux-arm-gnueabihf": ["lightningcss-linux-arm-gnueabihf@1.33.0", "", { "os": "linux", "cpu": "arm" }, "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ=="], + + "lightningcss-linux-arm64-gnu": ["lightningcss-linux-arm64-gnu@1.33.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg=="], + + "lightningcss-linux-arm64-musl": ["lightningcss-linux-arm64-musl@1.33.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ=="], + + "lightningcss-linux-x64-gnu": ["lightningcss-linux-x64-gnu@1.33.0", "", { "os": "linux", "cpu": "x64" }, "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg=="], + + "lightningcss-linux-x64-musl": ["lightningcss-linux-x64-musl@1.33.0", "", { "os": "linux", "cpu": "x64" }, "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw=="], + + "lightningcss-win32-arm64-msvc": ["lightningcss-win32-arm64-msvc@1.33.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA=="], + + "lightningcss-win32-x64-msvc": ["lightningcss-win32-x64-msvc@1.33.0", "", { "os": "win32", "cpu": "x64" }, "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA=="], + + "locate-path": ["locate-path@6.0.0", "", { "dependencies": { "p-locate": "^5.0.0" } }, "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw=="], + + "magic-string": ["magic-string@1.4.5", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.6.0" } }, "sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w=="], + + "math-intrinsics": ["math-intrinsics@1.1.0", "", {}, "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g=="], + + "media-typer": ["media-typer@1.1.1", "", {}, "sha512-yz3xRaG20c6/BOzvYoDaGtPmGscs7YivItZEEqe6GbwNfHuxu9YNmvnEkMzKldAGY4/80pRcQRZSEnhquk9XuQ=="], + + "merge-descriptors": ["merge-descriptors@2.0.0", "", {}, "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g=="], + + "mime-db": ["mime-db@1.54.0", "", {}, "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ=="], + + "mime-types": ["mime-types@3.0.2", "", { "dependencies": { "mime-db": "^1.54.0" } }, "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A=="], + + "minimatch": ["minimatch@11.0.9", "", { "dependencies": { "@isaacs/nonrecursive-glob-match": "^1.1.0", "brace-expansion": "^5.0.12" } }, "sha512-KCFkfyjqerNlSstjlhIGNXIKZGA/6O4V4RlhZ+Dsr621SPPw0mzlypE9D9ZOoPiVefHID+j7/XuMMlqfD/F60Q=="], + + "ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="], + + "nanoid": ["nanoid@3.3.20", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ=="], + + "napi-windows-process-start-time": ["napi-windows-process-start-time@0.1.0", "", { "os": "win32", "cpu": [ "x64", "arm64", ] }, "sha512-zHxhzKsIFu3elch3eFw69WEUGc79DFhbc3nD/WEOzWL/pFFLZRW13EHnuO0c+0YjncE5uCaS9ICHxOBXkb6vPw=="], + + "natural-compare": ["natural-compare@1.4.0", "", {}, "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw=="], + + "negotiator": ["negotiator@1.1.0", "", { "dependencies": { "content-type": "^2.1.0" } }, "sha512-NMPBRMJgiQHjbd8phG3Vebdx4kZ1H121rbl5IkMqeOsahptB9BKo/d7oJ3zTXqTgagn2bWlNSXkh0QUGM31RYg=="], + + "object-assign": ["object-assign@4.1.1", "", {}, "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg=="], + + "object-inspect": ["object-inspect@1.14.0", "", {}, "sha512-IVgHNlp/jwQX271+Xzoq9LZNTWXxZK+cEOrGBOBxXNbn7fapnZ+Ts6TVMgNOuAezwG2wdtnMX97tTPK6VEnuOQ=="], + + "obug": ["obug@3.0.0", "", {}, "sha512-5vvB5+W7ePv+p3uqxi+RcW1XAzLW0/hxt3/4X4Lc4qHudzOhmBiBwOY6DRob4WnanAEGvNcLjF+KNOufrUoEQw=="], + + "on-finished": ["on-finished@2.4.2", "", { "dependencies": { "ee-first": "1.1.1" } }, "sha512-ATWUv387i+nLD49EiDoOft5scf32Vsdz3ktrQJG9bi7jRFmaXTssvyvj1EmeKVVgvesbqUtvQQvaS2TpTukAZQ=="], + + "once": ["once@1.4.0", "", { "dependencies": { "wrappy": "1" } }, "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w=="], + + "optionator": ["optionator@0.9.4", "", { "dependencies": { "deep-is": "^0.1.3", "fast-levenshtein": "^2.0.6", "levn": "^0.4.1", "prelude-ls": "^1.2.1", "type-check": "^0.4.0", "word-wrap": "^1.2.5" } }, "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g=="], + + "p-limit": ["p-limit@3.1.0", "", { "dependencies": { "yocto-queue": "^0.1.0" } }, "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ=="], + + "p-locate": ["p-locate@5.0.0", "", { "dependencies": { "p-limit": "^3.0.2" } }, "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw=="], + + "parseurl": ["parseurl@1.3.3", "", {}, "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ=="], + + "path-exists": ["path-exists@4.0.0", "", {}, "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w=="], + + "path-key": ["path-key@3.1.1", "", {}, "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q=="], + + "path-to-regexp": ["path-to-regexp@8.4.2", "", {}, "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA=="], + + "picocolors": ["picocolors@1.1.1", "", {}, "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="], + + "picomatch": ["picomatch@4.0.7", "", {}, "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA=="], + + "pkce-challenge": ["pkce-challenge@5.0.2", "", {}, "sha512-vCc54+qyIfKC5e2UN28AZKElwqjLINgiIV3RKI8pDu93TjaAJoB3QrgMzEBouy8yOKsXVXdAinO1QArJf9x5WA=="], + + "postcss": ["postcss@8.5.34", "", { "dependencies": { "nanoid": "^3.3.20", "picocolors": "^1.1.1", "source-map-js": "^1.2.4" } }, "sha512-P1Qzj0XXZjMda74C7qiVnBG90UKNbyNUAOeQRBW8X63RsIMV57gevRqjnkELdwtZ/S2/uQFksJhmwuN8xShLPw=="], + + "prelude-ls": ["prelude-ls@1.2.1", "", {}, "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g=="], + + "prettier": ["prettier@3.10.1", "", { "bin": { "prettier": "bin/prettier.cjs" } }, "sha512-70vp3ZUYoPlFbF9uiTdXHUUCGEIp7d4+6p+8DYbkm2jP7x/3i/paXVF6dopSI3zd/CEitrZN1rc4i85xWmmXlg=="], + + "proxy-addr": ["proxy-addr@2.0.8", "", { "dependencies": { "forwarded": "0.2.0", "ipaddr.js": "1.9.1" } }, "sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ=="], + + "punycode": ["punycode@2.3.1", "", {}, "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg=="], + + "qified": ["qified@0.10.1", "", { "dependencies": { "hookified": "^2.1.1" } }, "sha512-+Owyggi9IxT1ePKGafcI87ubSmxol6smwJ+RAHDQlx9+9cPwFWDiKFFCPuWhr9ignlGpZ9vDQLw67N4dcTVFEA=="], + + "qs": ["qs@6.17.1", "", { "dependencies": { "es-define-property": "^1.0.1", "side-channel": "^1.1.1" } }, "sha512-jd3COkaKVgGUW+ZHyEHCG9bH7RoaaiWuMgzsIBjUMVjLAaWGWpoUAVwljVvBHxRu/2qEHnadLGZrkutYUBPQJA=="], + + "range-parser": ["range-parser@1.3.0", "", {}, "sha512-hek2mFQpPuI4E1BBKrSto+BU3e3x4xuarsbiwr3+lf7p44juvFMV0XFWQAP3xUyqXA4RrXLIoaSUGbSt056ZMw=="], + + "raw-body": ["raw-body@3.0.2", "", { "dependencies": { "bytes": "~3.1.2", "http-errors": "~2.0.1", "iconv-lite": "~0.7.0", "unpipe": "~1.0.0" } }, "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA=="], + + "require-from-string": ["require-from-string@2.0.2", "", {}, "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw=="], + + "rolldown": ["rolldown@1.3.4", "", { "dependencies": { "@oxc-project/types": "=0.160.0", "@rolldown/pluginutils": "^1.0.0" }, "optionalDependencies": { "@rolldown/binding-android-arm-eabi": "1.3.4", "@rolldown/binding-android-arm64": "1.3.4", "@rolldown/binding-darwin-arm64": "1.3.4", "@rolldown/binding-darwin-x64": "1.3.4", "@rolldown/binding-freebsd-x64": "1.3.4", "@rolldown/binding-linux-arm-gnueabihf": "1.3.4", "@rolldown/binding-linux-arm64-gnu": "1.3.4", "@rolldown/binding-linux-arm64-musl": "1.3.4", "@rolldown/binding-linux-ppc64-gnu": "1.3.4", "@rolldown/binding-linux-s390x-gnu": "1.3.4", "@rolldown/binding-linux-x64-gnu": "1.3.4", "@rolldown/binding-linux-x64-musl": "1.3.4", "@rolldown/binding-openharmony-arm64": "1.3.4", "@rolldown/binding-wasm32-wasi": "1.3.4", "@rolldown/binding-win32-arm64-msvc": "1.3.4", "@rolldown/binding-win32-x64-msvc": "1.3.4" }, "bin": { "rolldown": "./bin/cli.mjs" } }, "sha512-p2rq4bfBmF0M6yaR8+A89fbkBQynZI2fxUW4G07eq9kpctAkpo7q5BZ4X4Mo4XZ7HHROu33cX9PeopUFN6u+2Q=="], + + "router": ["router@2.3.0", "", { "dependencies": { "debug": "^4.4.0", "depd": "^2.0.0", "is-promise": "^4.0.0", "parseurl": "^1.3.3", "path-to-regexp": "^8.0.0" } }, "sha512-bpowRfGjEPe8t9R6fJIzhwmyCGAXwKvxBUsgJm+bJukwdcWmUXbMo7p22w7aYmQBPQTUMNqMV39YX0kMou3z8w=="], + + "safer-buffer": ["safer-buffer@2.1.2", "", {}, "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg=="], + + "semver": ["semver@7.8.6", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw=="], + + "send": ["send@1.2.1", "", { "dependencies": { "debug": "^4.4.3", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "etag": "^1.8.1", "fresh": "^2.0.0", "http-errors": "^2.0.1", "mime-types": "^3.0.2", "ms": "^2.1.3", "on-finished": "^2.4.1", "range-parser": "^1.2.1", "statuses": "^2.0.2" } }, "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ=="], + + "serve-static": ["serve-static@2.2.1", "", { "dependencies": { "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "parseurl": "^1.3.3", "send": "^1.2.0" } }, "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw=="], + + "setprototypeof": ["setprototypeof@1.2.0", "", {}, "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw=="], + + "shebang-command": ["shebang-command@2.0.0", "", { "dependencies": { "shebang-regex": "^3.0.0" } }, "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA=="], + + "shebang-regex": ["shebang-regex@3.0.0", "", {}, "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A=="], + + "side-channel": ["side-channel@1.1.1", "", { "dependencies": { "es-errors": "^1.3.0", "object-inspect": "^1.13.4", "side-channel-list": "^1.0.1", "side-channel-map": "^1.0.1", "side-channel-weakmap": "^1.0.2" } }, "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ=="], + + "side-channel-list": ["side-channel-list@1.0.1", "", { "dependencies": { "es-errors": "^1.3.0", "object-inspect": "^1.13.4" } }, "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w=="], + + "side-channel-map": ["side-channel-map@1.0.1", "", { "dependencies": { "call-bound": "^1.0.2", "es-errors": "^1.3.0", "get-intrinsic": "^1.2.5", "object-inspect": "^1.13.3" } }, "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA=="], + + "side-channel-weakmap": ["side-channel-weakmap@1.0.2", "", { "dependencies": { "call-bound": "^1.0.2", "es-errors": "^1.3.0", "get-intrinsic": "^1.2.5", "object-inspect": "^1.13.3", "side-channel-map": "^1.0.1" } }, "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A=="], + + "source-map-js": ["source-map-js@1.3.0", "", {}, "sha512-pdUVfIWcK0kCgK831ibqkZDcL7I9zljjOu0TQFnA+fiQ6y1CYqYB7RkTOHHO45FGMg5P/Mvk/+4ToQ7gAYAL5Q=="], + + "statuses": ["statuses@2.0.2", "", {}, "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw=="], + + "std-env": ["std-env@4.3.0", "", {}, "sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag=="], + + "tinybench": ["tinybench@6.2.5", "", {}, "sha512-b/8GRMdnY4cqkfCLyaFpTGIv1qwfi3oT0mWaepwT++6Z/ZrYehNfZZ2JDKVLKGhNoEkS3IIB1ELtCT0XS5DtOA=="], + + "tinyexec": ["tinyexec@1.4.0", "", {}, "sha512-PV6lIcJQh57aFeJDwx16JNHmgFRh5xguzallrDW1qe8nAghYgr5MKz2K5k7wEyV/ygZhdnIAP8+HZSarHPBCsg=="], + + "tinyglobby": ["tinyglobby@0.2.17", "", { "dependencies": { "fdir": "^6.5.0", "picomatch": "^4.0.4" } }, "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g=="], + + "toidentifier": ["toidentifier@1.0.1", "", {}, "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA=="], + + "ts-api-utils": ["ts-api-utils@2.5.0", "", { "peerDependencies": { "typescript": ">=4.8.4" } }, "sha512-OJ/ibxhPlqrMM0UiNHJ/0CKQkoKF243/AEmplt3qpRgkW8VG7IfOS41h7V8TjITqdByHzrjcS/2si+y4lIh8NA=="], + + "tsx": ["tsx@4.23.15", "", { "dependencies": { "esbuild": "~0.28.0" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "bin": { "tsx": "dist/cli.mjs" } }, "sha512-Yiex1Ovn8z2xPpOWckIiysV1SSyRMY9BkLF++q0yKiDxCqRhosKfMg3janKkiLBwZ5c/YryloKwGZcrEmtwxKw=="], + + "type-check": ["type-check@0.4.0", "", { "dependencies": { "prelude-ls": "^1.2.1" } }, "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew=="], + + "type-is": ["type-is@2.1.0", "", { "dependencies": { "content-type": "^2.0.0", "media-typer": "^1.1.0", "mime-types": "^3.0.0" } }, "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA=="], + + "typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="], + + "typescript-eslint": ["typescript-eslint@8.74.0", "", { "dependencies": { "@typescript-eslint/eslint-plugin": "8.74.0", "@typescript-eslint/parser": "8.74.0", "@typescript-eslint/typescript-estree": "8.74.0", "@typescript-eslint/utils": "8.74.0" }, "peerDependencies": { "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", "typescript": ">=4.8.4 <6.1.0" } }, "sha512-OsWQlsedt1ZpZXfZZMNK3m4SoQONFFcy4h/uRznsCeRfVuEic3gh4KGUs2pJJ5o0Jj0Jr7keUHQGN1Ns9aDw7Q=="], + + "undici-types": ["undici-types@8.9.0", "", {}, "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg=="], + + "unpipe": ["unpipe@1.0.0", "", {}, "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ=="], + + "uri-js": ["uri-js@4.4.1", "", { "dependencies": { "punycode": "^2.1.0" } }, "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg=="], + + "vary": ["vary@1.1.2", "", {}, "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg=="], + + "vite": ["vite@8.4.0", "", { "dependencies": { "lightningcss": "^1.33.0", "picomatch": "^4.0.7", "postcss": "^8.5.33", "rolldown": "~1.3.2", "tinyglobby": "^0.2.17" }, "optionalDependencies": { "fsevents": "~2.3.3", "napi-windows-process-start-time": "^0.1.0" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "@vitejs/devtools": "^0.7.1 || ^0.8.0", "esbuild": "^0.27.0 || ^0.28.0", "jiti": ">=1.21.0", "less": "^4.0.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "@vitejs/devtools", "esbuild", "jiti", "less", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-X2nUJg+9cutlz3hzqyO6p+WTwk9H257DjwAEf9EQYUFrQbDItmetadi9gYmb+l7VDy4r3VXLUnmLTwuPmzejDw=="], + + "vitest": ["vitest@5.1.2", "", { "dependencies": { "@types/chai": "^5.2.2", "@vitest/mocker": "5.1.2", "chai": "^6.3.0", "es-module-lexer": "^2.3.2", "expect-type": "^1.4.0", "magic-string": "^1.4.5", "obug": "^3.0.0", "picomatch": "^4.0.7", "std-env": "^4.3.0", "tinybench": "^6.2.3", "tinyexec": "^1.3.1", "tinyglobby": "^0.2.17", "why-is-node-running": "3.2.1" }, "peerDependencies": { "@edge-runtime/vm": "*", "@opentelemetry/api": "^1.9.0", "@types/node": "^22.0.0 || >=24.0.0", "@vitest/browser-playwright": "5.1.2", "@vitest/browser-preview": "5.1.2", "@vitest/browser-webdriverio": "^5.0.0-beta.5 || >=5.0.0", "@vitest/coverage-istanbul": "5.1.2", "@vitest/coverage-v8": "5.1.2", "@vitest/ui": "5.1.2", "happy-dom": "*", "jsdom": "*", "vite": "^6.4.0 || ^7.0.0 || ^8.0.0" }, "optionalPeers": ["@edge-runtime/vm", "@opentelemetry/api", "@types/node", "@vitest/browser-playwright", "@vitest/browser-preview", "@vitest/browser-webdriverio", "@vitest/coverage-istanbul", "@vitest/coverage-v8", "@vitest/ui", "happy-dom", "jsdom"], "bin": { "vitest": "./vitest.mjs" } }, "sha512-VIa2wXV208WraXUbzH+dQUrGcFpPuaiRA8HlhXS8R6/sy9cynw6OMqGj8fmAlH1hot7huTCtWUE14+FdXU3eLw=="], + + "which": ["which@2.0.2", "", { "dependencies": { "isexe": "^2.0.0" }, "bin": { "node-which": "./bin/node-which" } }, "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA=="], + + "why-is-node-running": ["why-is-node-running@3.2.1", "", { "bin": { "why-is-node-running": "cli.js" } }, "sha512-Tb2FUhB4vUsGQlfSquQLYkApkuPAFQXGFzxWKHHumVz2dK+X1RUm/HnID4+TfIGYJ1kTcwOaCk/buYCEJr6YjQ=="], + + "word-wrap": ["word-wrap@1.2.5", "", {}, "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA=="], + + "wrappy": ["wrappy@1.0.2", "", {}, "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="], + + "yocto-queue": ["yocto-queue@0.1.0", "", {}, "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q=="], + + "zod": ["zod@4.6.7", "", {}, "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg=="], + + "zod-to-json-schema": ["zod-to-json-schema@3.25.2", "", { "peerDependencies": { "zod": "^3.25.28 || ^4" } }, "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA=="], + + "@eslint-community/eslint-utils/eslint-visitor-keys": ["eslint-visitor-keys@3.4.3", "", {}, "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag=="], + + "@modelcontextprotocol/sdk/ajv": ["ajv@8.20.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA=="], + + "@typescript-eslint/eslint-plugin/ignore": ["ignore@7.0.17", "", {}, "sha512-0c3zcBRlWmcKhcIQWckzkYncJRv5HHB8O32wO/FcWL8DDXWDJgiEF6SX9ThbTv5h/eZ+xJK+VvDjjQ+cQJhp3Q=="], + + "ajv-formats/ajv": ["ajv@8.20.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA=="], + + "body-parser/content-type": ["content-type@2.1.0", "", {}, "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag=="], + + "express/content-type": ["content-type@2.1.0", "", {}, "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag=="], + + "negotiator/content-type": ["content-type@2.1.0", "", {}, "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag=="], + + "qified/hookified": ["hookified@2.2.0", "", {}, "sha512-p/LgFzRN5FeoD3DLS6bkUapeye6E4SI6yJs6KetENd18S+FBthqYq2amJUWpt5z0EQwwHemidjY5OqJGEKm5uA=="], + + "type-is/content-type": ["content-type@2.1.0", "", {}, "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag=="], + + "@modelcontextprotocol/sdk/ajv/json-schema-traverse": ["json-schema-traverse@1.0.0", "", {}, "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug=="], + + "ajv-formats/ajv/json-schema-traverse": ["json-schema-traverse@1.0.0", "", {}, "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug=="], + } +} diff --git a/eslint.config.js b/eslint.config.js new file mode 100644 index 0000000..c3f524e --- /dev/null +++ b/eslint.config.js @@ -0,0 +1,20 @@ +import js from '@eslint/js'; +import tseslint from 'typescript-eslint'; +import prettier from 'eslint-config-prettier'; +import globals from 'globals'; + +export default tseslint.config( + { ignores: ['dist', 'node_modules', 'coverage'] }, + js.configs.recommended, + ...tseslint.configs.recommended, + prettier, + { + languageOptions: { globals: globals.node }, + rules: { + '@typescript-eslint/no-unused-vars': [ + 'error', + { argsIgnorePattern: '^_', varsIgnorePattern: '^_' }, + ], + }, + }, +); diff --git a/package.json b/package.json new file mode 100644 index 0000000..da763d2 --- /dev/null +++ b/package.json @@ -0,0 +1,35 @@ +{ + "name": "gitops-mcp", + "version": "0.1.0", + "private": true, + "type": "module", + "description": "MCP server for GitOps: a stateless client of the public GitOps API", + "engines": { + "node": ">=22" + }, + "scripts": { + "dev": "tsx watch src/main.ts", + "build": "tsc -p tsconfig.build.json", + "start": "node dist/main.js", + "test": "vitest run", + "lint": "eslint .", + "typecheck": "tsc --noEmit", + "format": "prettier --write ." + }, + "dependencies": { + "@modelcontextprotocol/sdk": "^1.32.2", + "zod": "^4.6.7" + }, + "devDependencies": { + "@eslint/js": "^10.0.1", + "@types/node": "^26.6.11", + "eslint": "^10.16.0", + "eslint-config-prettier": "^10.1.9", + "globals": "^17.14.0", + "prettier": "^3.10.1", + "tsx": "^4.23.15", + "typescript": "~5.9", + "typescript-eslint": "^8.74.0", + "vitest": "^5.1.2" + } +} diff --git a/tsconfig.build.json b/tsconfig.build.json new file mode 100644 index 0000000..55c7815 --- /dev/null +++ b/tsconfig.build.json @@ -0,0 +1,5 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { "rootDir": "src", "outDir": "dist", "sourceMap": true }, + "include": ["src"] +} diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..2fcefb5 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "target": "ES2023", + "module": "NodeNext", + "moduleResolution": "NodeNext", + "strict": true, + "noUncheckedIndexedAccess": true, + "noImplicitOverride": true, + "esModuleInterop": true, + "skipLibCheck": true, + "isolatedModules": true, + "outDir": "dist", + "rootDir": ".", + "types": ["node"] + }, + "include": ["src", "test", "vitest.config.ts", "eslint.config.js"] +} diff --git a/vitest.config.ts b/vitest.config.ts new file mode 100644 index 0000000..271cbab --- /dev/null +++ b/vitest.config.ts @@ -0,0 +1,3 @@ +import { defineConfig } from 'vitest/config'; + +export default defineConfig({ test: { include: ['test/**/*.test.ts'], testTimeout: 15000 } }); From 6ab74e1d351866f4cd4beb3b076937547b51432f Mon Sep 17 00:00:00 2001 From: Carlos Lopez Date: Mon, 30 Nov 2026 15:46:19 +0100 Subject: [PATCH 2/5] feat: stateless Streamable HTTP server, API client, resolvers and list_projects tool (#128) Co-Authored-By: Claude Opus 5.5 --- src/api/client.ts | 205 ++++++++++++ src/api/types.ts | 286 +++++++++++++++++ src/config.ts | 37 +++ src/http.ts | 118 +++++++ src/log.ts | 42 +++ src/main.ts | 19 ++ src/resolve.ts | 138 ++++++++ src/server.ts | 11 + src/tools/code-report.ts | 53 +++ src/tools/context.ts | 36 +++ src/tools/cves.ts | 6 + src/tools/index.ts | 12 + src/tools/monitoring.ts | 6 + src/tools/result.ts | 64 ++++ test/fake-api.ts | 677 +++++++++++++++++++++++++++++++++++++++ test/helpers.ts | 47 +++ 16 files changed, 1757 insertions(+) create mode 100644 src/api/client.ts create mode 100644 src/api/types.ts create mode 100644 src/config.ts create mode 100644 src/http.ts create mode 100644 src/log.ts create mode 100644 src/main.ts create mode 100644 src/resolve.ts create mode 100644 src/server.ts create mode 100644 src/tools/code-report.ts create mode 100644 src/tools/context.ts create mode 100644 src/tools/cves.ts create mode 100644 src/tools/index.ts create mode 100644 src/tools/monitoring.ts create mode 100644 src/tools/result.ts create mode 100644 test/fake-api.ts create mode 100644 test/helpers.ts diff --git a/src/api/client.ts b/src/api/client.ts new file mode 100644 index 0000000..b09c3df --- /dev/null +++ b/src/api/client.ts @@ -0,0 +1,205 @@ +import type { ApiErrorBody } from './types.js'; + +export const VERSION = '0.1.0'; + +export class GitOpsApiError extends Error { + readonly status: number; + readonly code: string; + readonly fieldErrors?: Record; + /** Seconds, from `Retry-After`. */ + readonly retryAfter?: number; + + constructor(init: { + status: number; + code: string; + message: string; + fieldErrors?: Record; + retryAfter?: number; + }) { + super(init.message); + this.name = 'GitOpsApiError'; + this.status = init.status; + this.code = init.code; + if (init.fieldErrors) this.fieldErrors = init.fieldErrors; + if (init.retryAfter !== undefined) this.retryAfter = init.retryAfter; + } +} + +export type QueryValue = string | number | boolean | undefined | null; +export type Query = Record; + +export interface ClientOptions { + baseUrl: string; + /** The caller's `Authorization` header value, forwarded as is. Never stored or logged. */ + authorization: string; + timeoutMs?: number; + /** Retries for GET on network errors, 502, 503 and 504. */ + retries?: number; + /** Base backoff in ms (doubles each retry). */ + backoffMs?: number; + fetch?: typeof fetch; + /** Called once per API call (never with headers or bodies). */ + onCall?: (info: { method: string; path: string; status: number; durationMs: number }) => void; +} + +const RETRY_STATUS = new Set([502, 503, 504]); +const MAX_RETRY_AFTER_S = 10; + +const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); + +export class GitOpsApiClient { + private readonly baseUrl: string; + private readonly authorization: string; + private readonly timeoutMs: number; + private readonly retries: number; + private readonly backoffMs: number; + private readonly fetchImpl: typeof fetch; + private readonly onCall: ClientOptions['onCall']; + + constructor(options: ClientOptions) { + this.baseUrl = options.baseUrl.replace(/\/+$/, ''); + this.authorization = options.authorization; + this.timeoutMs = options.timeoutMs ?? 10000; + this.retries = options.retries ?? 2; + this.backoffMs = options.backoffMs ?? 200; + this.fetchImpl = options.fetch ?? fetch; + this.onCall = options.onCall; + } + + get(path: string, query?: Query): Promise { + return this.request('GET', path, query); + } + + /** Always sends a JSON body (`{}` when there is none): the API's CSRF guard needs it. */ + post(path: string, body: unknown = {}): Promise { + return this.request('POST', path, undefined, body ?? {}); + } + + private buildUrl(path: string, query?: Query): string { + const url = new URL(this.baseUrl + path); + for (const [key, value] of Object.entries(query ?? {})) { + if (value !== undefined && value !== null && value !== '') { + url.searchParams.set(key, String(value)); + } + } + return url.toString(); + } + + private async request( + method: 'GET' | 'POST', + path: string, + query?: Query, + body?: unknown, + ): Promise { + const url = this.buildUrl(path, query); + const maxRetries = method === 'GET' ? this.retries : 0; + const started = Date.now(); + let lastError: unknown; + + for (let attempt = 0; attempt <= maxRetries; attempt++) { + let waitMs = this.backoffMs * 2 ** attempt; + try { + const response = await this.attempt(method, url, body); + if (response.ok) { + this.onCall?.({ + method, + path, + status: response.status, + durationMs: Date.now() - started, + }); + return (await response.json()) as T; + } + const error = await this.toApiError(response); + this.onCall?.({ method, path, status: response.status, durationMs: Date.now() - started }); + if (attempt < maxRetries && RETRY_STATUS.has(response.status)) { + if (response.status === 503 && error.retryAfter !== undefined) { + waitMs = Math.min(error.retryAfter, MAX_RETRY_AFTER_S) * 1000; + } + lastError = error; + await sleep(waitMs); + continue; + } + throw error; + } catch (err) { + if (err instanceof GitOpsApiError) throw err; + lastError = this.toNetworkError(err); + if (attempt < maxRetries) { + await sleep(waitMs); + continue; + } + this.onCall?.({ method, path, status: 0, durationMs: Date.now() - started }); + throw lastError; + } + } + throw lastError; + } + + private attempt(method: string, url: string, body: unknown): Promise { + const headers: Record = { + Authorization: this.authorization, + Accept: 'application/json', + 'User-Agent': `gitops-mcp/${VERSION}`, + }; + const init: RequestInit = { method, headers, signal: AbortSignal.timeout(this.timeoutMs) }; + if (method === 'POST') { + headers['Content-Type'] = 'application/json'; + init.body = JSON.stringify(body ?? {}); + } + return this.fetchImpl(url, init); + } + + private toNetworkError(err: unknown): GitOpsApiError { + const timedOut = + err instanceof Error && (err.name === 'TimeoutError' || err.name === 'AbortError'); + return new GitOpsApiError( + timedOut + ? { + status: 504, + code: 'timeout', + message: `GitOps API timed out after ${this.timeoutMs} ms`, + } + : { status: 502, code: 'network_error', message: 'Could not reach the GitOps API' }, + ); + } + + private async toApiError(response: Response): Promise { + let parsed: Partial = {}; + try { + parsed = (await response.json()) as Partial; + } catch { + // non-JSON error body (e.g. a proxy page): fall back to the status text + } + const retryAfterRaw = Number(response.headers.get('retry-after')); + return new GitOpsApiError({ + status: response.status, + code: parsed.code ?? 'http_error', + message: parsed.error ?? `GitOps API answered ${response.status}`, + ...(parsed.errors ? { fieldErrors: parsed.errors } : {}), + ...(Number.isFinite(retryAfterRaw) && response.headers.has('retry-after') + ? { retryAfter: retryAfterRaw } + : {}), + }); + } +} + +/** Follows `nextCursor` until the end and returns every item. */ +export async function fetchAll( + client: GitOpsApiClient, + path: string, + query: Query = {}, + maxPages = 50, +): Promise { + const items: T[] = []; + let cursor: string | undefined; + for (let i = 0; i < maxPages; i++) { + const page = await client.get<{ items: T[]; nextCursor: string | null }>(path, { + ...query, + limit: 100, + cursor, + }); + items.push(...page.items); + if (!page.nextCursor) break; + cursor = page.nextCursor; + } + return items; +} diff --git a/src/api/types.ts b/src/api/types.ts new file mode 100644 index 0000000..2d70e42 --- /dev/null +++ b/src/api/types.ts @@ -0,0 +1,286 @@ +/** + * Response shapes of the GitOps public API (ADR 0005). Copied from the handlers in the gitops repo + * (`src/lib/server/{code-report,monitoring,cve-feed}/api.ts`). JSON `null` values are typed as + * `| null`. Keep these in sync with the API; the MCP never adds fields of its own. + */ + +// ---- Conventions ------------------------------------------------------------------------- + +export type ApiErrorCode = + | 'unauthorized' + | 'forbidden' + | 'not_found' + | 'invalid_request' + | 'invalid_cursor' + | 'validation_failed' + | 'mcp_monitor_secrets_not_allowed' + | 'module_disabled' + | 'rate_limited'; + +/** Error body: `{ error, code, errors? }` (`errors` is field -> code, validation failures only). */ +export interface ApiErrorBody { + error: string; + code: ApiErrorCode; + errors?: Record; +} + +export interface Page { + items: T[]; + nextCursor: string | null; +} + +/** Query accepted by every paginated endpoint (`limit` default 25, max 100). */ +export interface PageQuery { + limit?: number; + cursor?: string; +} + +// ---- Projects: GET /api/projects ---------------------------------------------------------- + +export interface ApiOrganizationRef { + id: string; + slug: string; + name: string; +} + +export interface ApiProject { + id: string; + slug: string | null; + name: string; + organization: ApiOrganizationRef; + /** Names of the enabled modules, sorted (e.g. `codereport`, `monitoring`). */ + modules: string[]; +} + +// ---- Code Report: /api/code-report/services... --------------------------------------------- + +export type Severity = 'critical' | 'high' | 'medium' | 'low' | 'unknown'; + +export type SeverityCounts = Record; + +/** GET /api/code-report/services?projectId= (items). Analysis fields are null without a scan. */ +export interface ApiServiceSummary { + id: string; + name: string; + slug: string | null; + lastAnalysisAt: string | null; + score: number | null; + severityCounts: SeverityCounts | null; + policyCompliant: boolean | null; +} + +export interface ApiFailedRule { + policy: string; + enforcement: string; + rule: string; + actual: unknown; + limit: unknown; + message: string; +} + +export interface ApiSecurityPolicy { + status: string | null; + compliant: boolean | null; + failedRules: ApiFailedRule[]; +} + +export interface ApiLinkedMonitor { + id: string; + name: string; + status: MonitorStatus; +} + +/** GET /api/code-report/services/[id]. `monitors` only when monitoring is on and readable. */ +export interface ApiServiceReport extends ApiServiceSummary { + projectId: string; + commit: string | null; + branch: string | null; + securityPolicy: ApiSecurityPolicy | null; + monitors?: ApiLinkedMonitor[]; +} + +/** GET /api/code-report/services/[id]/vulnerabilities?severity=&fixable= (items). */ +export interface ApiVulnerability { + id: string; + package: string; + installedVersion: string; + fixedVersion: string | null; + severity: Severity; + kev: boolean; + title: string; +} + +// ---- Monitoring: /api/monitoring/... --------------------------------------------------------- + +export type MonitorStatus = 'up' | 'degraded' | 'down' | 'paused' | 'pending'; + +/** GET /api/monitoring/monitors?projectId=&serviceId= (items). */ +export interface ApiMonitorSummary { + id: string; + name: string; + method: string; + url: string; + serviceId: string | null; + enabled: boolean; + status: MonitorStatus; + uptime24h: number | null; + hasHeaders: boolean; + hasBody: boolean; +} + +export interface ApiIncident { + id: string; + status: string; + cause: string | null; + httpStatus: number | null; + error: string | null; + startedAt: string; + endedAt: string | null; + failedChecks: number; +} + +/** GET /api/monitoring/monitors/[id] and the 201 of POST /api/monitoring/monitors. */ +export interface ApiMonitorDetail extends ApiMonitorSummary { + /** Names only; header values are never returned. */ + headerNames: string[]; + intervalSeconds: number; + timeoutMs: number; + expectedStatus: unknown; + uptime: { h24: number | null; d7: number | null; d30: number | null }; + openIncident: ApiIncident | null; + incidents: ApiIncident[]; +} + +export interface ApiOpenIncident { + monitorId: string; + name: string; + status: string; + since: string; + cause: string | null; +} + +/** GET /api/monitoring/status?projectId= */ +export interface ApiMonitoringStatus { + up: number; + degraded: number; + down: number; + paused: number; + pending: number; + total: number; + openIncidents: ApiOpenIncident[]; +} + +/** Body of POST /api/monitoring/monitors. MCP keys cannot send `headers` or `body`. */ +export interface CreateMonitorBody { + projectId: string; + name: string; + url: string; + method?: string; + serviceId?: string; + intervalSeconds?: number; + timeoutMs?: number; + expectedStatus?: number | string; + degradedThresholdMs?: number; + confirmations?: number; + followRedirects?: boolean; + enabled?: boolean; + headers?: { name: string; value: string }[]; + body?: string | null; +} + +/** POST /api/monitoring/monitors/[id]/test */ +export interface ApiMonitorTestResult { + status: string; + httpStatus: number | null; + latencyMs: number | null; + error: string | null; +} + +// ---- CVE feed: /api/cves/... ----------------------------------------------------------------- + +export type CveSeverity = 'low' | 'medium' | 'high' | 'critical'; + +export type ApiWatchedTechnology = + | { + id: string; + name: string; + minSeverity?: CveSeverity; + kind: 'osv'; + ecosystem: string; + package: string; + } + | { id: string; name: string; minSeverity?: CveSeverity; kind: 'cpe'; cpe: string } + | { + id: string; + name: string; + minSeverity?: CveSeverity; + kind: 'catalog'; + packages?: unknown[]; + cpes?: unknown[]; + }; + +/** GET /api/cves/watchlist?organizationId= */ +export interface ApiCveWatchlist { + feedEnabled: boolean; + technologies: ApiWatchedTechnology[]; + minSeverity: CveSeverity | null; + includeKev: boolean; +} + +/** GET /api/cves/feed (items). `affectsMe` only when the caller has `organization:projects:read`. */ +export interface ApiCveItem { + id: string; + aliases: string[]; + severity: CveSeverity | string; + cvss: number | null; + epss: number | null; + kev: boolean; + technologies: string[]; + summary: string; + publishedAt: string | null; + modifiedAt: string | null; + affectsMe?: boolean; +} + +/** GET /api/cves/feed. With `CVE_FEED_ENABLED=false`: `feedEnabled: false`, empty items. */ +export interface ApiCveFeed { + feedEnabled: boolean; + items: ApiCveItem[]; + nextCursor: string | null; + total: number; +} + +export interface ApiCveAffected { + technology: string | null; + ecosystem: string | null; + package: string | null; + cpe: string | null; + ranges: unknown; + fixedVersions: string[]; +} + +export interface ApiAffectedService { + projectId: string; + projectSlug: string; + projectName: string; + serviceId: string; + serviceSlug: string; + serviceName: string; +} + +/** GET /api/cves/[cve]?organizationId=. With the feed off: `{ feedEnabled: false, cve: null }`. */ +export type ApiCveDetail = + | { feedEnabled: false; cve: null } + | (ApiCveItem & { + feedEnabled: true; + title: string; + cvssVector: string | null; + epssPercentile: number | null; + kevAddedAt: string | null; + cwe: string[]; + fixedVersions: string[]; + affected: ApiCveAffected[]; + references: unknown[]; + details: string; + affectedServices?: ApiAffectedService[]; + }); diff --git a/src/config.ts b/src/config.ts new file mode 100644 index 0000000..ff2e231 --- /dev/null +++ b/src/config.ts @@ -0,0 +1,37 @@ +export type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'silent'; + +export interface Config { + port: number; + apiUrl: string; + apiTimeoutMs: number; + logLevel: LogLevel; +} + +const LOG_LEVELS: readonly LogLevel[] = ['debug', 'info', 'warn', 'error', 'silent']; + +function positiveInt(name: string, raw: string | undefined, fallback: number): number { + if (raw === undefined || raw.trim() === '') return fallback; + const n = Number(raw); + if (!Number.isInteger(n) || n <= 0) throw new Error(`${name} must be a positive integer`); + return n; +} + +export function loadConfig(env: NodeJS.ProcessEnv = process.env): Config { + const apiUrl = env.GITOPS_API_URL?.trim(); + if (!apiUrl) throw new Error('GITOPS_API_URL is required'); + try { + new URL(apiUrl); + } catch { + throw new Error('GITOPS_API_URL must be a valid URL'); + } + const level = (env.LOG_LEVEL?.trim().toLowerCase() || 'info') as LogLevel; + if (!LOG_LEVELS.includes(level)) { + throw new Error(`LOG_LEVEL must be one of ${LOG_LEVELS.join(', ')}`); + } + return { + port: positiveInt('PORT', env.PORT, 3000), + apiUrl: apiUrl.replace(/\/+$/, ''), + apiTimeoutMs: positiveInt('GITOPS_API_TIMEOUT_MS', env.GITOPS_API_TIMEOUT_MS, 10000), + logLevel: level, + }; +} diff --git a/src/http.ts b/src/http.ts new file mode 100644 index 0000000..8cc2d87 --- /dev/null +++ b/src/http.ts @@ -0,0 +1,118 @@ +import { randomUUID } from 'node:crypto'; +import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http'; +import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js'; +import { GitOpsApiClient } from './api/client.js'; +import type { Config } from './config.js'; +import type { Logger } from './log.js'; +import { createMcpServer } from './server.js'; + +const MAX_BODY_BYTES = 1024 * 1024; +const BEARER = /^Bearer\s+\S+$/i; + +function sendJson( + res: ServerResponse, + status: number, + body: unknown, + headers: Record = {}, +): void { + if (res.headersSent) return; + res.writeHead(status, { 'Content-Type': 'application/json', ...headers }); + res.end(JSON.stringify(body)); +} + +const rpcError = (code: number, message: string) => ({ + jsonrpc: '2.0', + error: { code, message }, + id: null, +}); + +class BodyTooLarge extends Error {} + +async function readJson(req: IncomingMessage): Promise { + const chunks: Buffer[] = []; + let size = 0; + for await (const chunk of req) { + size += (chunk as Buffer).length; + if (size > MAX_BODY_BYTES) throw new BodyTooLarge(); + chunks.push(chunk as Buffer); + } + const text = Buffer.concat(chunks).toString('utf8'); + return text ? JSON.parse(text) : undefined; +} + +export function createHttpServer(config: Config, log: Logger): Server { + async function handleMcp(req: IncomingMessage, res: ServerResponse, requestId: string) { + if (req.method !== 'POST') { + return sendJson(res, 405, rpcError(-32000, 'Method not allowed.'), { Allow: 'POST' }); + } + // The header value is forwarded as is to the API. It is never stored nor logged. + const authorization = req.headers.authorization; + if (!authorization || !BEARER.test(authorization)) { + return sendJson( + res, + 401, + rpcError(-32001, 'Unauthorized: send "Authorization: Bearer ".'), + { 'WWW-Authenticate': 'Bearer realm="gitops-mcp"' }, + ); + } + + let body: unknown; + try { + body = await readJson(req); + } catch (err) { + return err instanceof BodyTooLarge + ? sendJson(res, 413, rpcError(-32000, 'Request body too large.')) + : sendJson(res, 400, rpcError(-32700, 'Parse error: invalid JSON.')); + } + + const client = new GitOpsApiClient({ + baseUrl: config.apiUrl, + authorization, + timeoutMs: config.apiTimeoutMs, + onCall: ({ path, status, durationMs }) => + log.debug('api call', { requestId, apiPath: path, apiStatus: status, durationMs }), + }); + const server = createMcpServer({ client, log, requestId }); + const transport = new StreamableHTTPServerTransport({ + sessionIdGenerator: undefined, + enableJsonResponse: true, + }); + res.on('close', () => { + void transport.close(); + void server.close(); + }); + await server.connect(transport); + await transport.handleRequest(req, res, body); + } + + return createServer((req, res) => { + const requestId = randomUUID(); + const started = Date.now(); + const path = (req.url ?? '/').split('?')[0] ?? '/'; + res.on('finish', () => { + if (path === '/healthz') return; + log.info('http request', { + requestId, + method: req.method ?? '', + path, + status: res.statusCode, + durationMs: Date.now() - started, + }); + }); + + const run = async () => { + if (path === '/healthz' && (req.method === 'GET' || req.method === 'HEAD')) { + return sendJson(res, 200, { ok: true }); + } + if (path === '/mcp') return handleMcp(req, res, requestId); + sendJson(res, 404, { error: 'Not found' }); + }; + run().catch((err: unknown) => { + log.error('unhandled error', { + requestId, + error: err instanceof Error ? err.name : 'unknown', + }); + sendJson(res, 500, rpcError(-32603, 'Internal server error')); + }); + }); +} diff --git a/src/log.ts b/src/log.ts new file mode 100644 index 0000000..8fad1be --- /dev/null +++ b/src/log.ts @@ -0,0 +1,42 @@ +import type { LogLevel } from './config.js'; + +const ORDER: Record = { debug: 10, info: 20, warn: 30, error: 40, silent: 100 }; + +/** + * Fields allowed in a log line. Deliberately a closed set: never add headers, tokens, tool + * arguments or response bodies here. + */ +export interface LogFields { + requestId?: string; + tool?: string; + durationMs?: number; + apiStatus?: number; + apiPath?: string; + method?: string; + path?: string; + status?: number; + code?: string; + error?: string; +} + +export interface Logger { + debug(msg: string, fields?: LogFields): void; + info(msg: string, fields?: LogFields): void; + warn(msg: string, fields?: LogFields): void; + error(msg: string, fields?: LogFields): void; +} + +export type LogSink = (line: string) => void; + +export function createLogger( + level: LogLevel, + sink: LogSink = (line) => process.stdout.write(line + '\n'), +): Logger { + const emit = + (lvl: Exclude) => + (msg: string, fields: LogFields = {}) => { + if (ORDER[lvl] < ORDER[level]) return; + sink(JSON.stringify({ level: lvl, time: new Date().toISOString(), msg, ...fields })); + }; + return { debug: emit('debug'), info: emit('info'), warn: emit('warn'), error: emit('error') }; +} diff --git a/src/main.ts b/src/main.ts new file mode 100644 index 0000000..7a535fb --- /dev/null +++ b/src/main.ts @@ -0,0 +1,19 @@ +import { loadConfig } from './config.js'; +import { createHttpServer } from './http.js'; +import { createLogger } from './log.js'; + +const config = loadConfig(); +const log = createLogger(config.logLevel); +const server = createHttpServer(config, log); + +server.listen(config.port, () => { + log.info('gitops-mcp listening', { path: `:${config.port}` }); +}); + +for (const signal of ['SIGINT', 'SIGTERM'] as const) { + process.on(signal, () => { + log.info('shutting down'); + server.close(() => process.exit(0)); + setTimeout(() => process.exit(0), 5000).unref(); + }); +} diff --git a/src/resolve.ts b/src/resolve.ts new file mode 100644 index 0000000..4e3f50c --- /dev/null +++ b/src/resolve.ts @@ -0,0 +1,138 @@ +import { fetchAll, type GitOpsApiClient } from './api/client.js'; +import type { ApiOrganizationRef, ApiProject, ApiServiceSummary } from './api/types.js'; + +/** A reference the agent gave that cannot be resolved; the message is safe to show to the agent. */ +export class ResolveError extends Error { + constructor(message: string) { + super(message); + this.name = 'ResolveError'; + } +} + +const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; +export const isUuid = (value: string) => UUID.test(value); + +/** `org/project` label of a project (falls back to the id when it has no slug). */ +export const projectLabel = (p: ApiProject) => `${p.organization.slug}/${p.slug ?? p.id}`; + +// Per-request cache: one client lives for exactly one MCP request, so this never outlives it. +const projectCache = new WeakMap>(); + +/** Every project visible to the caller (follows pagination to the end). */ +export function listAllProjects(client: GitOpsApiClient): Promise { + let cached = projectCache.get(client); + if (!cached) { + cached = fetchAll(client, '/api/projects'); + projectCache.set(client, cached); + cached.catch(() => projectCache.delete(client)); + } + return cached; +} + +const candidates = (projects: ApiProject[]) => + projects.slice(0, 10).map(projectLabel).join(', ') + (projects.length > 10 ? ', …' : ''); + +/** `ref`: project uuid, `org/project` or `project` (when unique among the visible ones). */ +export async function resolveProject(client: GitOpsApiClient, ref: string): Promise { + const value = ref.trim(); + if (!value) throw new ResolveError('Project reference is empty. Use org/project or an id.'); + const projects = await listAllProjects(client); + + if (isUuid(value)) { + const found = projects.find((p) => p.id.toLowerCase() === value.toLowerCase()); + if (found) return found; + throw new ResolveError(`Project not found or no access: ${value}`); + } + + const parts = value.split('/'); + if (parts.length > 2) { + throw new ResolveError(`Invalid project reference "${value}". Use org/project or an id.`); + } + const [orgSlug, projectSlug] = parts.length === 2 ? [parts[0], parts[1]] : [undefined, parts[0]]; + const matches = projects.filter( + (p) => + (p.slug ?? '').toLowerCase() === projectSlug!.toLowerCase() && + (orgSlug === undefined || p.organization.slug.toLowerCase() === orgSlug.toLowerCase()), + ); + if (matches.length === 1) return matches[0]!; + if (matches.length > 1) { + throw new ResolveError( + `Project "${value}" is ambiguous. Use one of: ${candidates(matches)} (or its id).`, + ); + } + const hint = projects.length + ? ` Visible projects: ${candidates(projects)}.` + : ' You have no visible projects.'; + throw new ResolveError(`Project not found or no access: ${value}.${hint}`); +} + +/** `ref`: organization id or slug (slugs come from the visible projects). */ +export async function resolveOrganization( + client: GitOpsApiClient, + ref: string, +): Promise { + const value = ref.trim(); + if (!value) throw new ResolveError('Organization reference is empty. Use a slug or an id.'); + const projects = await listAllProjects(client); + const orgs = new Map(); + for (const p of projects) orgs.set(p.organization.id, p.organization); + + const lower = value.toLowerCase(); + const byId = orgs.get(value) ?? [...orgs.values()].find((o) => o.id.toLowerCase() === lower); + if (byId) return byId; + const bySlug = [...orgs.values()].find((o) => o.slug.toLowerCase() === lower); + if (bySlug) return bySlug; + const known = [...orgs.values()].map((o) => o.slug).join(', '); + throw new ResolveError( + `Organization not found or no access: ${value}.` + + (known ? ` Known organizations: ${known}.` : ''), + ); +} + +export interface ResolvedService { + id: string; + name: string; + slug: string | null; + /** Unknown when the service was given by uuid (no lookup is done). */ + project: ApiProject | null; +} + +/** `ref`: service uuid (used as is) or `org/project/service` (slug or name). */ +export async function resolveService( + client: GitOpsApiClient, + ref: string, +): Promise { + const value = ref.trim(); + if (!value) + throw new ResolveError('Service reference is empty. Use org/project/service or an id.'); + if (isUuid(value)) return { id: value, name: value, slug: null, project: null }; + + const parts = value.split('/'); + if (parts.length !== 3) { + throw new ResolveError( + `Invalid service reference "${value}". Use org/project/service or an id.`, + ); + } + const project = await resolveProject(client, `${parts[0]}/${parts[1]}`); + const wanted = parts[2]!.toLowerCase(); + const services = await fetchAll(client, '/api/code-report/services', { + projectId: project.id, + }); + const matches = services.filter( + (s) => (s.slug ?? '').toLowerCase() === wanted || s.name.toLowerCase() === wanted, + ); + if (matches.length === 1) { + const s = matches[0]!; + return { id: s.id, name: s.name, slug: s.slug, project }; + } + const names = services.map((s) => s.slug ?? s.name).join(', '); + if (matches.length > 1) { + throw new ResolveError( + `Service "${value}" is ambiguous in ${projectLabel(project)}. Use its id.`, + ); + } + throw new ResolveError( + `Service not found in ${projectLabel(project)}: ${parts[2]}.` + + (names ? ` Services: ${names}.` : ' The project has no services.'), + ); +} diff --git a/src/server.ts b/src/server.ts new file mode 100644 index 0000000..9f507fc --- /dev/null +++ b/src/server.ts @@ -0,0 +1,11 @@ +import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; +import { VERSION } from './api/client.js'; +import { registerTools } from './tools/index.js'; +import type { ToolContext } from './tools/context.js'; + +/** A fresh MCP server for one request (stateless mode). */ +export function createMcpServer(ctx: ToolContext): McpServer { + const server = new McpServer({ name: 'gitops-mcp', version: VERSION }); + registerTools(server, ctx); + return server; +} diff --git a/src/tools/code-report.ts b/src/tools/code-report.ts new file mode 100644 index 0000000..7da3cb3 --- /dev/null +++ b/src/tools/code-report.ts @@ -0,0 +1,53 @@ +import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; +import * as z from 'zod'; +import type { Page, ApiProject } from '../api/types.js'; +import { projectLabel, resolveOrganization } from '../resolve.js'; +import { runTool, type ToolContext } from './context.js'; +import { toolResult } from './result.js'; + +const projectSchema = z.object({ + id: z.string(), + slug: z.string().nullable(), + name: z.string(), + organization: z.object({ id: z.string(), slug: z.string(), name: z.string() }), + modules: z.array(z.string()), +}); + +export function registerCodeReportTools(server: McpServer, ctx: ToolContext): void { + server.registerTool( + 'list_projects', + { + title: 'List projects', + description: + 'Lists the GitOps projects the user can see, with their org/project slug, id and enabled modules. ' + + 'Use it first to discover what exists. Other tools accept "org/project" or an id.', + inputSchema: { + organization: z + .string() + .optional() + .describe('Organization slug or id. Omit to list every organization.'), + limit: z.number().int().min(1).max(100).optional().describe('Page size (default 25).'), + cursor: z.string().optional().describe('nextCursor from a previous call.'), + }, + outputSchema: { projects: z.array(projectSchema), nextCursor: z.string().nullable() }, + annotations: { readOnlyHint: true, openWorldHint: false }, + }, + ({ organization, limit, cursor }) => + runTool(ctx, 'list_projects', async () => { + const org = organization ? await resolveOrganization(ctx.client, organization) : null; + const page = await ctx.client.get>('/api/projects', { + organizationId: org?.id, + limit, + cursor, + }); + const labels = page.items.map(projectLabel); + const summary = page.items.length + ? `${page.items.length} ${page.items.length === 1 ? 'proyecto' : 'proyectos'}: ${labels.join(', ')}` + + (page.nextCursor ? ' (hay más, usa cursor)' : '') + : 'No hay proyectos visibles.'; + return toolResult(summary, { projects: page.items, nextCursor: page.nextCursor }); + }), + ); + + // TODO(#129): list_services, get_service_report, list_service_vulnerabilities +} diff --git a/src/tools/context.ts b/src/tools/context.ts new file mode 100644 index 0000000..e1044b8 --- /dev/null +++ b/src/tools/context.ts @@ -0,0 +1,36 @@ +import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js'; +import { GitOpsApiError, type GitOpsApiClient } from '../api/client.js'; +import type { Logger } from '../log.js'; +import { toolError } from './result.js'; + +/** What every tool gets. One per MCP request; `client` already carries the caller's token. */ +export interface ToolContext { + client: GitOpsApiClient; + log: Logger; + requestId?: string; +} + +/** + * Runs a tool body: times it, logs name + duration + API status (never arguments or results) and + * turns any thrown error into an `isError` tool result. Use it in every tool handler. + */ +export async function runTool( + ctx: ToolContext, + tool: string, + body: () => Promise, +): Promise { + const started = Date.now(); + const base = { tool, ...(ctx.requestId ? { requestId: ctx.requestId } : {}) }; + try { + const result = await body(); + ctx.log.info('tool ok', { ...base, durationMs: Date.now() - started }); + return result; + } catch (err) { + ctx.log.warn('tool error', { + ...base, + durationMs: Date.now() - started, + ...(err instanceof GitOpsApiError ? { apiStatus: err.status, code: err.code } : {}), + }); + return toolError(err); + } +} diff --git a/src/tools/cves.ts b/src/tools/cves.ts new file mode 100644 index 0000000..6cde488 --- /dev/null +++ b/src/tools/cves.ts @@ -0,0 +1,6 @@ +import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; +import type { ToolContext } from './context.js'; + +export function registerCveTools(_server: McpServer, _ctx: ToolContext): void { + // TODO(#129): get_cve_watchlist, list_cve_feed, get_cve +} diff --git a/src/tools/index.ts b/src/tools/index.ts new file mode 100644 index 0000000..6e81624 --- /dev/null +++ b/src/tools/index.ts @@ -0,0 +1,12 @@ +import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; +import { registerCodeReportTools } from './code-report.js'; +import type { ToolContext } from './context.js'; +import { registerCveTools } from './cves.js'; +import { registerMonitoringTools } from './monitoring.js'; + +/** One file per area, so features can be added in parallel without touching each other. */ +export function registerTools(server: McpServer, ctx: ToolContext): void { + registerCodeReportTools(server, ctx); + registerCveTools(server, ctx); + registerMonitoringTools(server, ctx); +} diff --git a/src/tools/monitoring.ts b/src/tools/monitoring.ts new file mode 100644 index 0000000..302edd6 --- /dev/null +++ b/src/tools/monitoring.ts @@ -0,0 +1,6 @@ +import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; +import type { ToolContext } from './context.js'; + +export function registerMonitoringTools(_server: McpServer, _ctx: ToolContext): void { + // TODO(#130): get_monitoring_status, list_monitors, get_monitor, create_monitor, test_monitor +} diff --git a/src/tools/result.ts b/src/tools/result.ts new file mode 100644 index 0000000..39d9705 --- /dev/null +++ b/src/tools/result.ts @@ -0,0 +1,64 @@ +import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js'; +import { GitOpsApiError } from '../api/client.js'; +import { ResolveError } from '../resolve.js'; + +/** Drops `null` and `undefined` recursively (arrays keep their length; null items are removed). */ +export function compact(value: unknown): unknown { + if (Array.isArray(value)) return value.filter((v) => v != null).map(compact); + if (value && typeof value === 'object') { + return Object.fromEntries( + Object.entries(value) + .filter(([, v]) => v != null) + .map(([k, v]) => [k, compact(v)]), + ); + } + return value; +} + +/** Short summary first, then compact JSON without nulls. `data` also goes in `structuredContent`. */ +export function toolResult(summary: string, data: object): CallToolResult { + return { + content: [{ type: 'text', text: `${summary}\n\n${JSON.stringify(compact(data))}` }], + structuredContent: data as Record, + }; +} + +function describe(err: GitOpsApiError): string { + switch (err.status) { + case 401: + return 'Token inválido o revocado. Revisa la clave MCP en GitOps (/profile → "Para MCP / agentes IA").'; + case 403: + return `Sin permiso: ${err.message}`; + case 404: + return `No encontrado o sin acceso: ${err.message}`; + case 429: + return err.retryAfter !== undefined + ? `Límite de peticiones alcanzado, reintenta en ${err.retryAfter} s.` + : 'Límite de peticiones alcanzado, reintenta más tarde.'; + case 400: + case 422: { + const fields = Object.entries(err.fieldErrors ?? {}); + const detail = fields.length + ? ` Campos a corregir: ${fields.map(([field, code]) => `${field} → ${code}`).join('; ')}.` + : ''; + return `Petición inválida (${err.code}): ${err.message}.${detail}`; + } + case 409: + return `Conflicto (${err.code}): ${err.message}`; + case 504: + case 502: + case 503: + return `La API de GitOps no está disponible ahora (${err.code}). Reintenta en unos segundos.`; + default: + return `Error de la API de GitOps (${err.status} ${err.code}): ${err.message}`; + } +} + +/** Readable tool error for the agent. Never a stack trace. */ +export function toolError(err: unknown): CallToolResult { + let text: string; + if (err instanceof GitOpsApiError) text = describe(err); + else if (err instanceof ResolveError) text = err.message; + else text = 'Error interno del servidor MCP.'; + return { isError: true, content: [{ type: 'text', text }] }; +} diff --git a/test/fake-api.ts b/test/fake-api.ts new file mode 100644 index 0000000..b5e4cb0 --- /dev/null +++ b/test/fake-api.ts @@ -0,0 +1,677 @@ +/** + * In-memory fake of the GitOps public API (ADR 0005) for tests. A real HTTP server on an ephemeral + * port, so the whole chain (MCP client -> gitops-mcp -> HTTP -> API) is exercised. + * + * How to extend (tools of #129 and #130): + * - Data: `seed()` returns the seed data; mutate `fake.db` in a test, or add records to the seed. + * - Handlers: every endpoint is an entry of `defaultRoutes()` (method + RegExp + handler). Add or + * fix routes there, or per test with `fake.route('GET', /^\/api\/foo$/, (req) => ...)` (custom + * routes win over the defaults). + * - Failures: `fake.failNext(status, { code, error, errors, headers })` answers the next request + * with that error (queue); useful for 429/503/400 cases. + * - Inspection: `fake.requests` records method, path+query, Authorization and Content-Type. + * + * Rules reproduced from the real API: Bearer required (401 `unauthorized`), and the CSRF guard of + * GitOps (403 to a POST whose Content-Type is not application/json). + */ +import { createServer, type Server } from 'node:http'; +import type { AddressInfo } from 'node:net'; +import type { + ApiCveDetail, + ApiCveFeed, + ApiCveItem, + ApiCveWatchlist, + ApiMonitorDetail, + ApiMonitoringStatus, + ApiProject, + ApiServiceReport, + ApiVulnerability, +} from '../src/api/types.js'; + +export const VALID_TOKEN = 'gvs_test_token_123'; + +export const IDS = { + orgAcme: '11111111-1111-4111-8111-111111111111', + orgGlobex: '22222222-2222-4222-8222-222222222222', + acmeBilling: 'aaaaaaaa-0000-4000-8000-000000000001', + acmeWeb: 'aaaaaaaa-0000-4000-8000-000000000002', + globexBilling: 'aaaaaaaa-0000-4000-8000-000000000003', + svcBillingApi: 'bbbbbbbb-0000-4000-8000-000000000001', + svcBillingWorker: 'bbbbbbbb-0000-4000-8000-000000000002', + svcWebFront: 'bbbbbbbb-0000-4000-8000-000000000003', + monBillingApi: 'cccccccc-0000-4000-8000-000000000001', + monWeb: 'cccccccc-0000-4000-8000-000000000002', +}; + +export interface FakeService { + id: string; + projectId: string; + name: string; + slug: string; + report: Omit; + vulnerabilities: ApiVulnerability[]; +} + +export interface FakeDb { + projects: ApiProject[]; + services: FakeService[]; + monitors: (ApiMonitorDetail & { projectId: string })[]; + cves: ApiCveItem[]; + cveDetails: Record; + watchlist: ApiCveWatchlist; +} + +const counts = (c: number, h: number, m: number, l: number) => ({ + critical: c, + high: h, + medium: m, + low: l, + unknown: 0, +}); + +export function seed(): FakeDb { + const acme = { id: IDS.orgAcme, slug: 'acme', name: 'Acme Inc' }; + const globex = { id: IDS.orgGlobex, slug: 'globex', name: 'Globex' }; + const monitor = ( + id: string, + projectId: string, + name: string, + status: ApiMonitorDetail['status'], + serviceId: string | null, + ): FakeDb['monitors'][number] => ({ + id, + projectId, + name, + method: 'GET', + url: `https://${name}.example.com/health`, + serviceId, + enabled: true, + status, + uptime24h: status === 'down' ? 91.5 : 100, + hasHeaders: false, + hasBody: false, + headerNames: [], + intervalSeconds: 60, + timeoutMs: 10000, + expectedStatus: 200, + uptime: { h24: status === 'down' ? 91.5 : 100, d7: 99.9, d30: 99.95 }, + openIncident: + status === 'down' + ? { + id: 'inc-1', + status: 'down', + cause: 'HTTP 503', + httpStatus: 503, + error: null, + startedAt: '2026-11-30T08:00:00.000Z', + endedAt: null, + failedChecks: 3, + } + : null, + incidents: [], + }); + const cve = (id: string, severity: string, kev: boolean): ApiCveItem => ({ + id, + aliases: [], + severity, + cvss: severity === 'critical' ? 9.8 : 7.5, + epss: 0.12, + kev, + technologies: ['nodejs'], + summary: `Advisory ${id}`, + publishedAt: '2026-11-01T00:00:00.000Z', + modifiedAt: '2026-11-02T00:00:00.000Z', + affectsMe: id === 'CVE-2026-0001', + }); + const cves = [cve('CVE-2026-0001', 'critical', true), cve('CVE-2026-0002', 'high', false)]; + return { + projects: [ + { + id: IDS.acmeBilling, + slug: 'billing', + name: 'Billing', + organization: acme, + modules: ['codereport', 'monitoring'], + }, + { + id: IDS.acmeWeb, + slug: 'web', + name: 'Web', + organization: acme, + modules: ['codereport', 'monitoring'], + }, + { + id: IDS.globexBilling, + slug: 'billing', + name: 'Billing', + organization: globex, + modules: ['codereport'], + }, + ], + services: [ + { + id: IDS.svcBillingApi, + projectId: IDS.acmeBilling, + name: 'billing-api', + slug: 'billing-api', + report: { + lastAnalysisAt: '2026-11-29T10:00:00.000Z', + score: 72, + severityCounts: counts(2, 3, 5, 1), + policyCompliant: false, + commit: 'abc1234', + branch: 'main', + securityPolicy: { + status: 'violated', + compliant: false, + failedRules: [ + { + policy: 'default', + enforcement: 'block', + rule: 'critical', + actual: 2, + limit: 0, + message: 'Too many critical', + }, + ], + }, + monitors: [{ id: IDS.monBillingApi, name: 'billing-api', status: 'down' }], + }, + vulnerabilities: [ + { + id: 'CVE-2026-0001', + package: 'lodash', + installedVersion: '4.17.0', + fixedVersion: '4.17.21', + severity: 'critical', + kev: true, + title: 'Prototype pollution', + }, + { + id: 'CVE-2026-0003', + package: 'express', + installedVersion: '4.0.0', + fixedVersion: null, + severity: 'high', + kev: false, + title: 'Open redirect', + }, + ], + }, + { + id: IDS.svcBillingWorker, + projectId: IDS.acmeBilling, + name: 'billing-worker', + slug: 'billing-worker', + report: { + lastAnalysisAt: null, + score: null, + severityCounts: null, + policyCompliant: null, + commit: null, + branch: null, + securityPolicy: null, + }, + vulnerabilities: [], + }, + { + id: IDS.svcWebFront, + projectId: IDS.acmeWeb, + name: 'web-front', + slug: 'web-front', + report: { + lastAnalysisAt: '2026-11-28T10:00:00.000Z', + score: 95, + severityCounts: counts(0, 0, 1, 2), + policyCompliant: true, + commit: 'def5678', + branch: 'main', + securityPolicy: { status: 'passed', compliant: true, failedRules: [] }, + }, + vulnerabilities: [], + }, + ], + monitors: [ + monitor(IDS.monBillingApi, IDS.acmeBilling, 'billing-api', 'down', IDS.svcBillingApi), + monitor(IDS.monWeb, IDS.acmeWeb, 'web', 'up', IDS.svcWebFront), + ], + cves, + cveDetails: {}, + watchlist: { + feedEnabled: true, + technologies: [{ id: 'nodejs', name: 'Node.js', kind: 'catalog' }], + minSeverity: 'medium', + includeKev: true, + }, + }; +} + +// ---- Routing ------------------------------------------------------------------------------- + +export interface FakeRequest { + method: string; + url: URL; + params: string[]; + body: unknown; + db: FakeDb; +} +export interface FakeResponse { + status?: number; + body: unknown; + headers?: Record; +} +export type Handler = (req: FakeRequest) => FakeResponse; +export interface Route { + method: string; + pattern: RegExp; + handler: Handler; +} + +const err = ( + status: number, + code: string, + error: string, + errors?: Record, +): FakeResponse => ({ + status, + body: { error, code, ...(errors ? { errors } : {}) }, +}); +const notFound = (what: string) => err(404, 'not_found', `${what} not found`); + +/** Same shape as the real API: opaque base64url cursor over an offset. */ +export function paginate(all: T[], url: URL): FakeResponse { + const limit = Math.min(Number(url.searchParams.get('limit') ?? 25) || 25, 100); + const cursor = url.searchParams.get('cursor'); + let offset = 0; + if (cursor) { + try { + offset = (JSON.parse(Buffer.from(cursor, 'base64url').toString()) as { o: number }).o; + } catch { + return err(400, 'invalid_cursor', 'Invalid cursor'); + } + } + const items = all.slice(offset, offset + limit); + const next = offset + limit; + const nextCursor = + next < all.length ? Buffer.from(JSON.stringify({ o: next })).toString('base64url') : null; + return { body: { items, nextCursor } }; +} + +const summaryOf = (s: FakeService) => ({ + id: s.id, + name: s.name, + slug: s.slug, + lastAnalysisAt: s.report.lastAnalysisAt, + score: s.report.score, + severityCounts: s.report.severityCounts, + policyCompliant: s.report.policyCompliant, +}); + +const monitorSummary = (m: FakeDb['monitors'][number]) => ({ + id: m.id, + name: m.name, + method: m.method, + url: m.url, + serviceId: m.serviceId, + enabled: m.enabled, + status: m.status, + uptime24h: m.uptime24h, + hasHeaders: m.hasHeaders, + hasBody: m.hasBody, +}); + +export function defaultRoutes(): Route[] { + return [ + { + method: 'GET', + pattern: /^\/api\/projects$/, + handler: ({ url, db }) => { + const orgId = url.searchParams.get('organizationId'); + if (orgId && !db.projects.some((p) => p.organization.id === orgId)) + return notFound('Organization'); + const rows = db.projects + .filter((p) => !orgId || p.organization.id === orgId) + .sort( + (a, b) => + a.organization.slug.localeCompare(b.organization.slug) || + (a.slug ?? '').localeCompare(b.slug ?? ''), + ); + return paginate(rows, url); + }, + }, + { + method: 'GET', + pattern: /^\/api\/code-report\/services$/, + handler: ({ url, db }) => { + const projectId = url.searchParams.get('projectId'); + if (!projectId) return err(400, 'invalid_request', 'projectId is required'); + if (!db.projects.some((p) => p.id === projectId)) return notFound('Project'); + return paginate(db.services.filter((s) => s.projectId === projectId).map(summaryOf), url); + }, + }, + { + method: 'GET', + pattern: /^\/api\/code-report\/services\/([^/]+)$/, + handler: ({ params, db }) => { + const s = db.services.find((x) => x.id === params[0]); + if (!s) return notFound('Service'); + return { body: { ...summaryOf(s), projectId: s.projectId, ...s.report } }; + }, + }, + { + method: 'GET', + pattern: /^\/api\/code-report\/services\/([^/]+)\/vulnerabilities$/, + handler: ({ params, url, db }) => { + const s = db.services.find((x) => x.id === params[0]); + if (!s) return notFound('Service'); + const sev = url.searchParams.get('severity')?.split(','); + const fixable = url.searchParams.get('fixable'); + const rows = s.vulnerabilities + .filter((v) => !sev || sev.includes(v.severity)) + .filter((v) => fixable === null || Boolean(v.fixedVersion) === (fixable === 'true')); + return paginate(rows, url); + }, + }, + { + method: 'GET', + pattern: /^\/api\/monitoring\/monitors$/, + handler: ({ url, db }) => { + const projectId = url.searchParams.get('projectId'); + if (!projectId) return err(400, 'invalid_request', 'projectId is required'); + const project = db.projects.find((p) => p.id === projectId); + if (!project) return notFound('Project'); + if (!project.modules.includes('monitoring')) + return err(409, 'module_disabled', 'Monitoring is not enabled in this project'); + const serviceId = url.searchParams.get('serviceId'); + return paginate( + db.monitors + .filter((m) => m.projectId === projectId && (!serviceId || m.serviceId === serviceId)) + .map(monitorSummary), + url, + ); + }, + }, + { + method: 'GET', + pattern: /^\/api\/monitoring\/monitors\/([^/]+)$/, + handler: ({ params, db }) => { + const m = db.monitors.find((x) => x.id === params[0]); + if (!m) return notFound('Monitor'); + const { projectId: _projectId, ...rest } = m; + return { body: rest }; + }, + }, + { + method: 'GET', + pattern: /^\/api\/monitoring\/status$/, + handler: ({ url, db }) => { + const projectId = url.searchParams.get('projectId'); + if (!projectId) return err(400, 'invalid_request', 'projectId is required'); + if (!db.projects.some((p) => p.id === projectId)) return notFound('Project'); + const rows = db.monitors.filter((m) => m.projectId === projectId); + const status: ApiMonitoringStatus = { + up: 0, + degraded: 0, + down: 0, + paused: 0, + pending: 0, + total: rows.length, + openIncidents: [], + }; + for (const m of rows) { + status[m.status]++; + if (m.openIncident) { + status.openIncidents.push({ + monitorId: m.id, + name: m.name, + status: m.openIncident.status, + since: m.openIncident.startedAt, + cause: m.openIncident.cause, + }); + } + } + return { body: status }; + }, + }, + { + method: 'POST', + pattern: /^\/api\/monitoring\/monitors$/, + handler: ({ body, db }) => { + const b = (body ?? {}) as Record; + if (b.headers || b.body) + return err( + 400, + 'mcp_monitor_secrets_not_allowed', + 'MCP keys cannot set monitor headers or body', + ); + const project = db.projects.find((p) => p.id === b.projectId); + if (!project) return notFound('Project'); + const errors: Record = {}; + if (typeof b.name !== 'string' || !b.name) errors.name = 'monitoring.errors.required'; + if (typeof b.url !== 'string' || !/^https?:\/\//.test(b.url)) + errors.url = 'monitoring.errors.invalid_url'; + if (Object.keys(errors).length) + return err(400, 'validation_failed', 'Invalid monitor', errors); + const created = { + id: `cccccccc-0000-4000-8000-${String(db.monitors.length + 1).padStart(12, '0')}`, + projectId: project.id, + name: b.name as string, + method: (b.method as string) ?? 'GET', + url: b.url as string, + serviceId: (b.serviceId as string) ?? null, + enabled: true, + status: 'pending' as const, + uptime24h: null, + hasHeaders: false, + hasBody: false, + headerNames: [], + intervalSeconds: (b.intervalSeconds as number) ?? 60, + timeoutMs: (b.timeoutMs as number) ?? 10000, + expectedStatus: b.expectedStatus ?? 200, + uptime: { h24: null, d7: null, d30: null }, + openIncident: null, + incidents: [], + }; + db.monitors.push(created); + const { projectId: _projectId, ...rest } = created; + return { status: 201, body: rest }; + }, + }, + { + method: 'POST', + pattern: /^\/api\/monitoring\/monitors\/([^/]+)\/test$/, + handler: ({ params, db }) => { + const m = db.monitors.find((x) => x.id === params[0]); + if (!m) return notFound('Monitor'); + return { + body: { + status: m.status === 'down' ? 'down' : 'up', + httpStatus: m.status === 'down' ? 503 : 200, + latencyMs: 42, + error: null, + }, + }; + }, + }, + { + method: 'GET', + pattern: /^\/api\/cves\/watchlist$/, + handler: ({ url, db }) => { + const orgId = url.searchParams.get('organizationId'); + if (!orgId) return err(400, 'invalid_request', 'organizationId is required'); + if (!db.projects.some((p) => p.organization.id === orgId)) return notFound('Organization'); + return { body: db.watchlist }; + }, + }, + { + method: 'GET', + pattern: /^\/api\/cves\/feed$/, + handler: ({ url, db }) => { + const orgId = url.searchParams.get('organizationId'); + if (!orgId) return err(400, 'invalid_request', 'organizationId is required'); + if (!db.projects.some((p) => p.organization.id === orgId)) return notFound('Organization'); + const kev = url.searchParams.get('kev'); + const affectsMe = url.searchParams.get('affectsMe'); + const rows = db.cves + .filter((c) => kev === null || c.kev === (kev === 'true')) + .filter((c) => affectsMe === null || Boolean(c.affectsMe) === (affectsMe === 'true')); + const page = paginate(rows, url); + const feed: ApiCveFeed = { + feedEnabled: true, + ...(page.body as { items: ApiCveItem[]; nextCursor: string | null }), + total: rows.length, + }; + return { body: feed }; + }, + }, + { + method: 'GET', + pattern: /^\/api\/cves\/([^/]+)$/, + handler: ({ params, url, db }) => { + const orgId = url.searchParams.get('organizationId'); + if (!orgId) return err(400, 'invalid_request', 'organizationId is required'); + const id = decodeURIComponent(params[0]!); + const detail = db.cveDetails[id]; + if (detail) return { body: detail }; + const item = db.cves.find((c) => c.id === id); + if (!item) return err(404, 'not_found', 'CVE not found in the feed of the organization'); + return { + body: { + feedEnabled: true, + ...item, + title: item.summary, + cvssVector: null, + epssPercentile: null, + kevAddedAt: null, + cwe: [], + fixedVersions: [], + affected: [], + references: [], + details: item.summary, + }, + }; + }, + }, + ]; +} + +// ---- Server -------------------------------------------------------------------------------- + +export interface RecordedRequest { + method: string; + path: string; + authorization: string | undefined; + contentType: string | undefined; + accept: string | undefined; + userAgent: string | undefined; + body: unknown; +} + +export interface QueuedFailure { + status: number; + code?: string; + error?: string; + errors?: Record; + headers?: Record; +} + +export interface FakeApi { + url: string; + db: FakeDb; + requests: RecordedRequest[]; + /** Adds a route that takes precedence over the defaults. */ + route(method: string, pattern: RegExp, handler: Handler): void; + /** The next `times` requests (any path, after auth) fail with this error. */ + failNext(failure: QueuedFailure, times?: number): void; + /** Clears queued failures, custom routes and recorded requests. */ + reset(): void; + close(): Promise; +} + +export async function startFakeApi(options: { validTokens?: string[] } = {}): Promise { + const validTokens = new Set(options.validTokens ?? [VALID_TOKEN]); + const db = seed(); + const custom: Route[] = []; + const defaults = defaultRoutes(); + const failures: QueuedFailure[] = []; + const requests: RecordedRequest[] = []; + + const server: Server = createServer((req, res) => { + const chunks: Buffer[] = []; + req.on('data', (c: Buffer) => chunks.push(c)); + req.on('end', () => { + const raw = Buffer.concat(chunks).toString('utf8'); + let body: unknown; + try { + body = raw ? JSON.parse(raw) : undefined; + } catch { + body = undefined; + } + const url = new URL(req.url ?? '/', 'http://fake'); + const method = req.method ?? 'GET'; + requests.push({ + method, + path: url.pathname + url.search, + authorization: req.headers.authorization, + contentType: req.headers['content-type'], + accept: req.headers.accept, + userAgent: req.headers['user-agent'], + body, + }); + + const send = (r: FakeResponse) => { + res.writeHead(r.status ?? 200, { 'Content-Type': 'application/json', ...r.headers }); + res.end(JSON.stringify(r.body)); + }; + + const match = /^Bearer (\S+)$/.exec(req.headers.authorization ?? ''); + if (!match || !validTokens.has(match[1]!)) { + return send(err(401, 'unauthorized', 'Invalid or missing API key')); + } + // CSRF guard of GitOps: a POST must be application/json + if ( + method === 'POST' && + !(req.headers['content-type'] ?? '').toLowerCase().startsWith('application/json') + ) { + return send(err(403, 'forbidden', 'Cross-site POST form submissions are forbidden')); + } + const failure = failures.shift(); + if (failure) { + return send({ + status: failure.status, + headers: failure.headers, + body: { + error: failure.error ?? 'Simulated failure', + code: failure.code ?? 'forbidden', + ...(failure.errors ? { errors: failure.errors } : {}), + }, + }); + } + for (const route of [...custom, ...defaults]) { + const m = route.pattern.exec(url.pathname); + if (route.method === method && m) { + return send(route.handler({ method, url, params: m.slice(1), body, db })); + } + } + send(notFound('Route')); + }); + }); + + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + const { port } = server.address() as AddressInfo; + + return { + url: `http://127.0.0.1:${port}`, + db, + requests, + route: (method, pattern, handler) => void custom.unshift({ method, pattern, handler }), + failNext: (failure, times = 1) => + void failures.push(...Array.from({ length: times }, () => failure)), + reset: () => { + failures.length = 0; + custom.length = 0; + requests.length = 0; + }, + close: () => new Promise((resolve) => server.close(() => resolve())), + }; +} diff --git a/test/helpers.ts b/test/helpers.ts new file mode 100644 index 0000000..b483de1 --- /dev/null +++ b/test/helpers.ts @@ -0,0 +1,47 @@ +import type { Server } from 'node:http'; +import type { AddressInfo } from 'node:net'; +import { GitOpsApiClient } from '../src/api/client.js'; +import type { Config } from '../src/config.js'; +import { createHttpServer } from '../src/http.js'; +import { createLogger } from '../src/log.js'; +import { VALID_TOKEN, type FakeApi } from './fake-api.js'; + +export const makeClient = ( + api: FakeApi, + options: Partial[0]> = {}, +) => + new GitOpsApiClient({ + baseUrl: api.url, + authorization: `Bearer ${VALID_TOKEN}`, + backoffMs: 1, + ...options, + }); + +export interface TestMcp { + url: string; + logs: string[]; + close(): Promise; +} + +/** The real MCP HTTP server pointed at the fake API, capturing every log line. */ +export async function startMcp(api: FakeApi, overrides: Partial = {}): Promise { + const logs: string[] = []; + const config: Config = { + port: 0, + apiUrl: api.url, + apiTimeoutMs: 5000, + logLevel: 'debug', + ...overrides, + }; + const server: Server = createHttpServer( + config, + createLogger('debug', (l) => logs.push(l)), + ); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + const { port } = server.address() as AddressInfo; + return { + url: `http://127.0.0.1:${port}`, + logs, + close: () => new Promise((resolve) => server.close(() => resolve())), + }; +} From 1c71e1667fabc42d60b48aeca96912309f77893b Mon Sep 17 00:00:00 2001 From: Carlos Lopez Date: Mon, 30 Nov 2026 15:46:19 +0100 Subject: [PATCH 3/5] feat: tests, README and CLAUDE.md (#128) Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 32 ++++++++++ README.md | 99 +++++++++++++++++++++++++++++- test/client.test.ts | 124 ++++++++++++++++++++++++++++++++++++++ test/http.test.ts | 139 +++++++++++++++++++++++++++++++++++++++++++ test/resolve.test.ts | 85 ++++++++++++++++++++++++++ test/result.test.ts | 41 +++++++++++++ 6 files changed, 519 insertions(+), 1 deletion(-) create mode 100644 CLAUDE.md create mode 100644 test/client.test.ts create mode 100644 test/http.test.ts create mode 100644 test/resolve.test.ts create mode 100644 test/result.test.ts diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..2b44617 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,32 @@ +# gitops-mcp + +Servidor MCP stateless de GitOps (ADR 0005 en el repo `gitops`). Es un cliente de la API pública: no accede a GitDB. Código e identificadores en inglés, README en español. Ramas y PR sobre `development`, nunca `main` (main = producción). + +## Comandos + +`bun install`, `bun run lint`, `bun run typecheck`, `bun run test`, `bun run build`, `bun run format`. Ejecuta lint, typecheck y test antes de cada commit. + +## Estructura + +- `src/config.ts`: variables de entorno. `src/log.ts`: logs JSON con campos cerrados (`LogFields`). +- `src/http.ts`: servidor HTTP (`/mcp`, `/healthz`, auth Bearer, un server+transport por petición). `src/server.ts`: crea el `McpServer`. +- `src/api/client.ts`: `GitOpsApiClient` (`get`, `post`, `fetchAll`), `GitOpsApiError`. `src/api/types.ts`: tipos de las respuestas de la API. +- `src/resolve.ts`: `resolveProject`, `resolveService`, `resolveOrganization` (slug o id, caché por petición). +- `src/tools/{code-report,cves,monitoring}.ts`: un `registerXTools(server, ctx)` por área. `src/tools/context.ts`: `ToolContext` y `runTool`. `src/tools/result.ts`: `toolResult`, `toolError`. +- `test/fake-api.ts`: API falsa en memoria (datos semilla, rutas, `failNext`, `route`). + +## Añadir una tool + +1. Regístrala en el `registerXTools` de su área con `server.registerTool(name, { title, description, inputSchema, outputSchema, annotations }, handler)` (zod). `readOnlyHint: true` en las de lectura, `false` en las de escritura. +2. Envuelve el cuerpo en `runTool(ctx, name, async () => ...)`: mide, loguea y convierte errores en `toolError`. +3. Resuelve referencias con `resolve*` (acepta slug o id), llama a la API con `ctx.client`, y responde con `toolResult(resumen, datos)`: resumen corto en español y `structuredContent` con la misma forma que `outputSchema`. +4. Tipos de la API en `src/api/types.ts`. Listas con `limit` y `cursor`, devuelve `nextCursor`. +5. Añade datos/rutas al fake (`test/fake-api.ts`) y tests e2e con el cliente MCP del SDK. + +## Reglas de seguridad + +- Nada de vault, ni tool genérica "llama a cualquier endpoint". Todo pasa por la API pública. +- El token (`Authorization`) se reenvía tal cual y nunca se guarda ni se loguea. No loguees cabeceras, argumentos de tools ni cuerpos de respuesta (hay un test que lo comprueba). +- Ningún secreto, token ni valor de cabecera de monitor en respuestas de tools. Respuestas pequeñas (recorta textos largos). +- `post` siempre envía `Content-Type: application/json` y body JSON: el guard CSRF de GitOps rechaza lo contrario. Los GET se reintentan; los POST nunca. +- Errores al agente: mensajes legibles, nunca stack traces. diff --git a/README.md b/README.md index aa4e771..e67a6d7 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,100 @@ # gitops-mcp -Servidor MCP de [GitOps](https://github.com/getgitops/gitops) para agentes IA. Diseño: ADR 0005 en el repo `gitops`. +Servidor [MCP](https://modelcontextprotocol.io) de [GitOps](https://github.com/getgitops/gitops) para agentes IA (Claude Code en terminal o VS Code). Permite preguntar "¿está este servicio sano y seguro?" sin salir de la conversación: Code Report, monitorización y CVEs. + +Diseño completo: ADR 0005 (`docs/adr/0005-mcp-server.md` en el repo `gitops`). + +## Arquitectura + +``` +Claude Code ──MCP (HTTP + Bearer gvs_…)──▶ gitops-mcp ──REST + mismo Bearer──▶ GitOps API ──▶ GitDB + (sin estado) (permisos, auditoría, + vault bloqueado) +``` + +- **Sin acceso a GitDB, sin credenciales propias, sin estado.** Cada tool son una o varias llamadas REST a `/api/...` reenviando la cabecera `Authorization` del usuario tal cual. Permisos, auditoría y rate limit viven en la API: el MCP no puede hacer nada que el usuario no pueda hacer en la UI. +- **Transporte:** Streamable HTTP en modo stateless (un server + transport nuevo por petición, sin `Mcp-Session-Id`). Cualquier réplica atiende cualquier petición. +- **Sin vault:** no hay ninguna tool de secretos ni una tool genérica "llama a cualquier endpoint". +- No se guarda ni se loguea el token, las cabeceras, los argumentos ni los cuerpos de respuesta. + +## Variables de entorno + +| Variable | Por defecto | Descripción | +| ----------------------- | ------------- | ------------------------------------------- | +| `GITOPS_API_URL` | (obligatoria) | URL base de la API de GitOps | +| `PORT` | `3000` | Puerto HTTP | +| `GITOPS_API_TIMEOUT_MS` | `10000` | Timeout de cada petición a la API | +| `LOG_LEVEL` | `info` | `debug`, `info`, `warn`, `error` o `silent` | + +Ver `.env.example`. + +## Endpoints + +- `POST /mcp`: protocolo MCP. Requiere `Authorization: Bearer gvs_…` (si no, 401 con `WWW-Authenticate: Bearer realm="gitops-mcp"`). +- `GET /mcp` y `DELETE /mcp`: 405 (modo stateless). +- `GET /healthz`: `200 {"ok":true}`. + +## Desarrollo local + +Requiere Node 22+ y [bun](https://bun.sh). + +```bash +bun install +cp .env.example .env # y ajusta GITOPS_API_URL +GITOPS_API_URL=http://localhost:5173 bun run dev +``` + +Scripts: `dev`, `build` (tsc → `dist/`), `start`, `test` (vitest), `lint`, `typecheck`, `format`. + +Los tests no necesitan la API real: `test/fake-api.ts` levanta una API falsa en memoria (2 organizaciones, 3 proyectos, servicios, vulnerabilidades, monitores y CVEs) y los tests e2e usan el cliente MCP del SDK contra el servidor real. + +Docker: + +```bash +docker build -t gitops-mcp . +docker run --rm -p 3000:3000 -e GITOPS_API_URL=https://cloud.getgitops.com gitops-mcp +``` + +## Uso desde Claude Code + +1. En GitOps, ve a **/profile → "Para MCP / agentes IA"** y crea una clave MCP. Empieza por `gvs_…` y se muestra una sola vez. La clave actúa con los permisos de tu usuario (sin vault). +2. Añade el servidor: + + ```bash + claude mcp add --transport http gitops https://mcp.cloud.getgitops.com/mcp \ + --header "Authorization: Bearer gvs_…" + ``` + + Para desarrollo, el servidor es `mcp.cloud.dev.getgitops.com`; en local, `http://localhost:3000/mcp`. + +3. En VS Code o para compartirlo en un proyecto, usa un `.mcp.json` en la raíz (no subas el token; usa una variable de entorno): + + ```json + { + "mcpServers": { + "gitops": { + "type": "http", + "url": "https://mcp.cloud.getgitops.com/mcp", + "headers": { "Authorization": "Bearer ${GITOPS_MCP_TOKEN}" } + } + } + } + ``` + +4. Pregunta, por ejemplo: "¿qué proyectos tengo en GitOps?". + +Las tools aceptan referencias legibles: `org/proyecto`, `proyecto` (si es único) o `org/proyecto/servicio`, además de ids. + +## Tools + +Todas devuelven primero un resumen corto y después JSON compacto (sin nulls). Los errores de la API se devuelven como errores de tool legibles (`isError`), nunca como stack traces. + +| Tool | API | Descripción | +| --------------- | ------------------- | --------------------------------------------------------------------- | +| `list_projects` | `GET /api/projects` | Proyectos visibles (`organization?` por slug/id, `limit?`, `cursor?`) | + +Pendientes: Code Report y CVEs (#129), Monitoring (#130). + +## Licencia + +Ver `license.md`. diff --git a/test/client.test.ts b/test/client.test.ts new file mode 100644 index 0000000..fe426f0 --- /dev/null +++ b/test/client.test.ts @@ -0,0 +1,124 @@ +import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'; +import { GitOpsApiError } from '../src/api/client.js'; +import { startFakeApi, VALID_TOKEN, type FakeApi } from './fake-api.js'; +import { makeClient } from './helpers.js'; + +let api: FakeApi; +beforeAll(async () => (api = await startFakeApi())); +afterAll(() => api.close()); +beforeEach(() => api.reset()); + +describe('GitOpsApiClient', () => { + it('forwards the token as is and sends the standard headers', async () => { + await makeClient(api).get('/api/projects', { limit: 2 }); + const req = api.requests[0]!; + expect(req.authorization).toBe(`Bearer ${VALID_TOKEN}`); + expect(req.accept).toBe('application/json'); + expect(req.userAgent).toMatch(/^gitops-mcp\/\d/); + expect(req.path).toBe('/api/projects?limit=2'); + }); + + it('POST always sends application/json and a JSON body ({} by default)', async () => { + const id = api.db.monitors[0]!.id; + await makeClient(api).post(`/api/monitoring/monitors/${id}/test`); + const req = api.requests[0]!; + expect(req.method).toBe('POST'); + expect(req.contentType).toBe('application/json'); + expect(req.accept).toBe('application/json'); + expect(req.body).toEqual({}); + }); + + it('the fake API rejects a POST that is not JSON (CSRF guard)', async () => { + const res = await fetch(`${api.url}/api/monitoring/monitors`, { + method: 'POST', + headers: { Authorization: `Bearer ${VALID_TOKEN}` }, + }); + expect(res.status).toBe(403); + }); + + it('retries GET on 503 respecting Retry-After, then succeeds', async () => { + api.failNext({ status: 503, code: 'forbidden', headers: { 'Retry-After': '0' } }, 2); + const res = await makeClient(api).get<{ items: unknown[] }>('/api/projects'); + expect(res.items.length).toBe(3); + expect(api.requests).toHaveLength(3); + }); + + it('gives up after 2 retries', async () => { + api.failNext({ status: 502 }, 5); + await expect(makeClient(api).get('/api/projects')).rejects.toMatchObject({ status: 502 }); + expect(api.requests).toHaveLength(3); + }); + + it('does not retry POST', async () => { + api.failNext({ status: 503 }, 3); + await expect(makeClient(api).post('/api/monitoring/monitors', {})).rejects.toBeInstanceOf( + GitOpsApiError, + ); + expect(api.requests).toHaveLength(1); + }); + + it('does not retry 4xx', async () => { + api.failNext({ status: 404, code: 'not_found' }, 3); + await expect(makeClient(api).get('/api/projects')).rejects.toMatchObject({ status: 404 }); + expect(api.requests).toHaveLength(1); + }); + + it('maps errors: status, code, fieldErrors, retryAfter', async () => { + api.failNext({ + status: 400, + code: 'validation_failed', + error: 'Invalid monitor', + errors: { url: 'monitoring.errors.invalid_url' }, + }); + await expect(makeClient(api).get('/x')).rejects.toMatchObject({ + status: 400, + code: 'validation_failed', + message: 'Invalid monitor', + fieldErrors: { url: 'monitoring.errors.invalid_url' }, + }); + api.failNext({ status: 429, code: 'rate_limited', headers: { 'Retry-After': '30' } }); + await expect(makeClient(api).get('/x')).rejects.toMatchObject({ + status: 429, + code: 'rate_limited', + retryAfter: 30, + }); + }); + + it('maps a 401 from a bad token', async () => { + await expect( + makeClient(api, { authorization: 'Bearer nope' }).get('/api/projects'), + ).rejects.toMatchObject({ status: 401, code: 'unauthorized' }); + }); + + it('times out with an AbortController-based timeout', async () => { + const slow = await startSlowServer(); + try { + const client = makeClient(api, { baseUrl: slow.url, timeoutMs: 50, retries: 0 }); + await expect(client.get('/x')).rejects.toMatchObject({ status: 504, code: 'timeout' }); + } finally { + await slow.close(); + } + }); + + it('maps a network failure to 502 after retries', async () => { + const client = makeClient(api, { baseUrl: 'http://127.0.0.1:1', timeoutMs: 500 }); + await expect(client.get('/x')).rejects.toMatchObject({ status: 502, code: 'network_error' }); + }); +}); + +async function startSlowServer() { + const { createServer } = await import('node:http'); + const server = createServer(() => { + /* never responds */ + }); + await new Promise((r) => server.listen(0, '127.0.0.1', r)); + const port = (server.address() as import('node:net').AddressInfo).port; + return { + url: `http://127.0.0.1:${port}`, + close: () => + new Promise((r) => { + server.closeAllConnections(); + server.close(() => r()); + }), + }; +} diff --git a/test/http.test.ts b/test/http.test.ts new file mode 100644 index 0000000..3603a4d --- /dev/null +++ b/test/http.test.ts @@ -0,0 +1,139 @@ +import { Client } from '@modelcontextprotocol/sdk/client/index.js'; +import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { startFakeApi, VALID_TOKEN, type FakeApi } from './fake-api.js'; +import { startMcp, type TestMcp } from './helpers.js'; + +let api: FakeApi; +let mcp: TestMcp; +beforeAll(async () => { + api = await startFakeApi(); + mcp = await startMcp(api); +}); +afterAll(async () => { + await mcp.close(); + await api.close(); +}); + +const initBody = { + jsonrpc: '2.0', + id: 1, + method: 'initialize', + params: { + protocolVersion: '2025-03-26', + capabilities: {}, + clientInfo: { name: 't', version: '1' }, + }, +}; +const post = (headers: Record) => + fetch(`${mcp.url}/mcp`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + Accept: 'application/json, text/event-stream', + ...headers, + }, + body: JSON.stringify(initBody), + }); + +describe('http', () => { + it('GET /healthz', async () => { + const res = await fetch(`${mcp.url}/healthz`); + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ ok: true }); + }); + + it('401 without Bearer, with WWW-Authenticate and a JSON-RPC error', async () => { + for (const headers of [{} as Record, { Authorization: 'Basic abc' }]) { + const res = await post(headers); + expect(res.status).toBe(401); + expect(res.headers.get('www-authenticate')).toBe('Bearer realm="gitops-mcp"'); + const body = (await res.json()) as { jsonrpc: string; error: { code: number } }; + expect(body.jsonrpc).toBe('2.0'); + expect(body.error.code).toBeLessThan(0); + } + }); + + it('GET and DELETE /mcp are 405', async () => { + for (const method of ['GET', 'DELETE']) { + const res = await fetch(`${mcp.url}/mcp`, { method }); + expect(res.status).toBe(405); + } + }); + + it('accepts a valid Bearer', async () => { + const res = await post({ Authorization: `Bearer ${VALID_TOKEN}` }); + expect(res.status).toBe(200); + expect(res.headers.get('mcp-session-id')).toBeNull(); + }); +}); + +describe('e2e with the MCP SDK client', () => { + const connect = async (token = VALID_TOKEN) => { + const client = new Client({ name: 'test', version: '1' }); + await client.connect( + new StreamableHTTPClientTransport(new URL(`${mcp.url}/mcp`), { + requestInit: { headers: { Authorization: `Bearer ${token}` } }, + }), + ); + return client; + }; + + it('lists tools and calls list_projects; the token reaches the API', async () => { + api.requests.length = 0; + const client = await connect(); + const { tools } = await client.listTools(); + const tool = tools.find((t) => t.name === 'list_projects'); + expect(tool?.annotations?.readOnlyHint).toBe(true); + + const result = await client.callTool({ name: 'list_projects', arguments: {} }); + expect(result.isError).toBeFalsy(); + const text = (result.content as { text: string }[])[0]!.text; + expect(text).toContain('3 proyectos: acme/billing, acme/web, globex/billing'); + expect((result.structuredContent as { projects: unknown[] }).projects).toHaveLength(3); + expect(api.requests.every((r) => r.authorization === `Bearer ${VALID_TOKEN}`)).toBe(true); + await client.close(); + }); + + it('filters by organization slug', async () => { + const client = await connect(); + const result = await client.callTool({ + name: 'list_projects', + arguments: { organization: 'globex' }, + }); + expect((result.content as { text: string }[])[0]!.text).toContain('1 proyecto: globex/billing'); + await client.close(); + }); + + it('turns API errors into readable tool errors', async () => { + const client = await connect(); + const result = await client.callTool({ + name: 'list_projects', + arguments: { organization: 'nope' }, + }); + expect(result.isError).toBe(true); + expect((result.content as { text: string }[])[0]!.text).toMatch(/Organization not found/); + + api.failNext({ status: 429, code: 'rate_limited', headers: { 'Retry-After': '7' } }); + const limited = await client.callTool({ name: 'list_projects', arguments: {} }); + expect((limited.content as { text: string }[])[0]!.text).toMatch(/reintenta en 7 s/); + await client.close(); + }); + + it('a revoked token gives a readable tool error', async () => { + const client = await connect('gvs_revoked'); + const result = await client.callTool({ name: 'list_projects', arguments: {} }); + expect(result.isError).toBe(true); + expect((result.content as { text: string }[])[0]!.text).toMatch(/token inválido o revocado/i); + await client.close(); + }); + + it('never logs the token', () => { + expect(mcp.logs.length).toBeGreaterThan(0); + const all = mcp.logs.join('\n'); + expect(all).not.toContain(VALID_TOKEN); + expect(all).not.toContain('gvs_revoked'); + expect(all).not.toMatch(/bearer/i); + expect(all).not.toMatch(/authorization/i); + }); +}); diff --git a/test/resolve.test.ts b/test/resolve.test.ts new file mode 100644 index 0000000..b0dba52 --- /dev/null +++ b/test/resolve.test.ts @@ -0,0 +1,85 @@ +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { + ResolveError, + resolveOrganization, + resolveProject, + resolveService, +} from '../src/resolve.js'; +import { IDS, startFakeApi, type FakeApi } from './fake-api.js'; +import { makeClient } from './helpers.js'; + +let api: FakeApi; +beforeAll(async () => (api = await startFakeApi())); +afterAll(() => api.close()); + +describe('resolveProject', () => { + it('resolves org/project', async () => { + expect((await resolveProject(makeClient(api), 'globex/billing')).id).toBe(IDS.globexBilling); + }); + it('resolves by id', async () => { + expect((await resolveProject(makeClient(api), IDS.acmeWeb)).slug).toBe('web'); + }); + it('resolves a unique bare slug', async () => { + expect((await resolveProject(makeClient(api), 'web')).id).toBe(IDS.acmeWeb); + }); + it('lists candidates when the slug is ambiguous', async () => { + const err = await resolveProject(makeClient(api), 'billing').catch((e: unknown) => e); + expect(err).toBeInstanceOf(ResolveError); + expect((err as Error).message).toContain('acme/billing'); + expect((err as Error).message).toContain('globex/billing'); + }); + it('fails with visible projects when not found', async () => { + await expect(resolveProject(makeClient(api), 'acme/nope')).rejects.toThrow(/acme\/web/); + }); + it('fetches the project list once per client (per-request cache)', async () => { + api.requests.length = 0; + const client = makeClient(api); + await resolveProject(client, 'acme/web'); + await resolveProject(client, 'acme/billing'); + await resolveOrganization(client, 'acme'); + expect(api.requests.filter((r) => r.path.startsWith('/api/projects'))).toHaveLength(1); + }); + it('follows pagination to the end', async () => { + const many = await startFakeApi(); + for (let i = 0; i < 120; i++) { + many.db.projects.push({ + ...many.db.projects[0]!, + id: `dddddddd-0000-4000-8000-${String(i).padStart(12, '0')}`, + slug: `p${i}`, + }); + } + expect((await resolveProject(makeClient(many), 'acme/p119')).slug).toBe('p119'); + await many.close(); + }); +}); + +describe('resolveOrganization', () => { + it('by slug and by id', async () => { + expect((await resolveOrganization(makeClient(api), 'acme')).id).toBe(IDS.orgAcme); + expect((await resolveOrganization(makeClient(api), IDS.orgGlobex)).slug).toBe('globex'); + }); + it('unknown', async () => { + await expect(resolveOrganization(makeClient(api), 'zzz')).rejects.toThrow(/acme, globex/); + }); +}); + +describe('resolveService', () => { + it('by org/project/service', async () => { + const s = await resolveService(makeClient(api), 'acme/billing/billing-api'); + expect(s.id).toBe(IDS.svcBillingApi); + expect(s.project?.id).toBe(IDS.acmeBilling); + }); + it('by uuid, without lookups', async () => { + api.requests.length = 0; + expect((await resolveService(makeClient(api), IDS.svcWebFront)).id).toBe(IDS.svcWebFront); + expect(api.requests).toHaveLength(0); + }); + it('unknown service lists the existing ones', async () => { + await expect(resolveService(makeClient(api), 'acme/billing/x')).rejects.toThrow( + /billing-worker/, + ); + }); + it('rejects malformed refs', async () => { + await expect(resolveService(makeClient(api), 'acme/billing')).rejects.toThrow(ResolveError); + }); +}); diff --git a/test/result.test.ts b/test/result.test.ts new file mode 100644 index 0000000..73b2570 --- /dev/null +++ b/test/result.test.ts @@ -0,0 +1,41 @@ +import { describe, expect, it } from 'vitest'; +import { GitOpsApiError } from '../src/api/client.js'; +import { toolError, toolResult } from '../src/tools/result.js'; + +const text = (r: { content: { type: string; text?: string }[] }) => r.content[0]!.text!; + +describe('toolResult', () => { + it('summary + compact JSON without nulls, structuredContent intact', () => { + const data = { a: 1, b: null, c: { d: null, e: 'x' }, f: [1, null] }; + const r = toolResult('Resumen', data); + expect(text(r as never)).toBe('Resumen\n\n{"a":1,"c":{"e":"x"},"f":[1]}'); + expect(r.structuredContent).toBe(data); + }); +}); + +describe('toolError', () => { + const err = ( + status: number, + extra: Partial[0]> = {}, + ) => toolError(new GitOpsApiError({ status, code: 'c', message: 'msg', ...extra })); + it.each([ + [401, /token inválido o revocado/i], + [403, /sin permiso: msg/i], + [404, /no encontrado o sin acceso/i], + ])('%i', (status, re) => { + const r = err(status); + expect(r.isError).toBe(true); + expect(text(r as never)).toMatch(re); + }); + it('429 with retry', () => + expect(text(err(429, { retryAfter: 12 }) as never)).toMatch(/reintenta en 12 s/)); + it('400 lists field errors', () => { + const t = text(err(400, { fieldErrors: { url: 'invalid_url', name: 'required' } }) as never); + expect(t).toContain('url → invalid_url'); + expect(t).toContain('name → required'); + }); + it('unknown errors never leak details', () => { + const t = text(toolError(new Error('secret stack at /app/x.js')) as never); + expect(t).not.toContain('secret'); + }); +}); From 57f6996c790028af5246563cb7106687a7bac15b Mon Sep 17 00:00:00 2001 From: Carlos Lopez Date: Mon, 30 Nov 2026 15:49:45 +0100 Subject: [PATCH 4/5] feat: Code Report and CVE tools (#129) Co-Authored-By: Claude Opus 5.5 --- README.md | 15 +- src/tools/code-report.ts | 247 ++++++++++++++++++++++++++- src/tools/cves.ts | 223 +++++++++++++++++++++++- test/code-report-cves.test.ts | 312 ++++++++++++++++++++++++++++++++++ 4 files changed, 790 insertions(+), 7 deletions(-) create mode 100644 test/code-report-cves.test.ts diff --git a/README.md b/README.md index e67a6d7..c7f31e3 100644 --- a/README.md +++ b/README.md @@ -93,7 +93,20 @@ Todas devuelven primero un resumen corto y después JSON compacto (sin nulls). L | --------------- | ------------------- | --------------------------------------------------------------------- | | `list_projects` | `GET /api/projects` | Proyectos visibles (`organization?` por slug/id, `limit?`, `cursor?`) | -Pendientes: Code Report y CVEs (#129), Monitoring (#130). +### Code Report y CVEs (solo lectura) + +| Tool | API | Descripción | +| ---------------------- | ---------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- | +| `list_services` | `GET /api/code-report/services` | Servicios de un proyecto (`project`) con riesgo, severidades y política (`limit?`, `cursor?`) | +| `get_code_report` | `GET /api/code-report/services/[id]` | Último análisis de un servicio (`service`): riesgo, severidades, política y reglas incumplidas, monitores | +| `list_service_cves` | `GET /api/code-report/services/[id]/vulnerabilities` | CVEs de un servicio (`service`, `severity?[]`, `fixable?`, `limit?`, `cursor?`) | +| `list_technology_cves` | `GET /api/cves/feed` | Feed de CVEs por tecnología (`organization`, `technology?`, `severity?` mínima, `kev?`, `affects_me?`, ...) | +| `get_cve` | `GET /api/cves/[cve]` | Detalle de un CVE (`id`, `organization`) y servicios afectados | +| `get_cve_watchlist` | `GET /api/cves/watchlist` | Tecnologías vigiladas por la organización (`organization`) | + +`score` es un **riesgo** (más alto = peor). Los servicios se identifican como `org/proyecto/servicio` o por id. Con el feed de CVEs desactivado, las tools de CVEs lo indican sin error. Ejemplos: "¿cómo está el code report de acme/billing/api?", "¿qué CVEs críticos afectan a acme/billing?", "¿qué CVEs de la lista KEV me afectan en acme?". + +Pendientes: Monitoring (#130). ## Licencia diff --git a/src/tools/code-report.ts b/src/tools/code-report.ts index 7da3cb3..4382c7b 100644 --- a/src/tools/code-report.ts +++ b/src/tools/code-report.ts @@ -1,7 +1,15 @@ import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; import * as z from 'zod'; -import type { Page, ApiProject } from '../api/types.js'; -import { projectLabel, resolveOrganization } from '../resolve.js'; +import type { + ApiProject, + ApiServiceReport, + ApiServiceSummary, + ApiVulnerability, + Page, + Severity, + SeverityCounts, +} from '../api/types.js'; +import { projectLabel, resolveOrganization, resolveProject, resolveService } from '../resolve.js'; import { runTool, type ToolContext } from './context.js'; import { toolResult } from './result.js'; @@ -13,6 +21,67 @@ const projectSchema = z.object({ modules: z.array(z.string()), }); +const SEVERITIES = ['critical', 'high', 'medium', 'low', 'unknown'] as const; +const SEVERITY_ES: Record = { + critical: ['crítica', 'críticas'], + high: ['alta', 'altas'], + medium: ['media', 'medias'], + low: ['baja', 'bajas'], + unknown: ['desconocida', 'desconocidas'], +}; + +const severityCountsSchema = z.object({ + critical: z.number(), + high: z.number(), + medium: z.number(), + low: z.number(), + unknown: z.number(), +}); + +const serviceSummarySchema = z.object({ + id: z.string(), + name: z.string(), + slug: z.string().nullable(), + lastAnalysisAt: z.string().nullable(), + score: z.number().nullable(), + severityCounts: severityCountsSchema.nullable(), + policyCompliant: z.boolean().nullable(), +}); + +const failedRuleSchema = z.object({ + policy: z.string(), + enforcement: z.string(), + rule: z.string(), + actual: z.unknown(), + limit: z.unknown(), + message: z.string(), +}); + +const vulnerabilitySchema = z.object({ + id: z.string(), + package: z.string(), + installedVersion: z.string(), + fixedVersion: z.string().nullable(), + severity: z.string(), + kev: z.boolean(), + title: z.string(), +}); + +/** "2 críticas, 5 altas" (only the non-zero ones, in severity order). */ +export function describeCounts(counts: Partial | null | undefined): string { + if (!counts) return ''; + return SEVERITIES.filter((s) => (counts[s] ?? 0) > 0) + .map((s) => `${counts[s]} ${SEVERITY_ES[s][counts[s] === 1 ? 0 : 1]}`) + .join(', '); +} + +const policyText = (compliant: boolean | null, failed: number | null): string => + compliant === null + ? 'sin política evaluada' + : compliant + ? 'política CUMPLIDA' + : `política INCUMPLIDA${failed ? ` (${failed} ${failed === 1 ? 'regla' : 'reglas'})` : ''}`; + export function registerCodeReportTools(server: McpServer, ctx: ToolContext): void { server.registerTool( 'list_projects', @@ -49,5 +118,177 @@ export function registerCodeReportTools(server: McpServer, ctx: ToolContext): vo }), ); - // TODO(#129): list_services, get_service_report, list_service_vulnerabilities + server.registerTool( + 'list_services', + { + title: 'List services of a project', + description: + 'Lists the services (code repositories) of a project with the summary of their last Code Report analysis: ' + + 'risk score, vulnerability counts by severity and whether the security policy is met. ' + + 'The score is a RISK: higher is worse. Services never analysed have null analysis fields. ' + + 'Use it to see which services of a project are in the worst shape or to discover service slugs ' + + '(services are referred to as org/project/service).', + inputSchema: { + project: z.string().describe('Project as "org/project", "project" (if unique) or its id.'), + limit: z.number().int().min(1).max(100).optional().describe('Page size (default 25).'), + cursor: z.string().optional().describe('nextCursor from a previous call.'), + }, + outputSchema: { + project: z.string(), + services: z.array(serviceSummarySchema), + nextCursor: z.string().nullable(), + }, + annotations: { readOnlyHint: true, openWorldHint: false }, + }, + ({ project, limit, cursor }) => + runTool(ctx, 'list_services', async () => { + const proj = await resolveProject(ctx.client, project); + const label = projectLabel(proj); + const page = await ctx.client.get>('/api/code-report/services', { + projectId: proj.id, + limit, + cursor, + }); + const lines = page.items.map((s) => { + const name = s.slug ?? s.name; + if (s.score === null) return `${name}: sin análisis`; + const counts = describeCounts(s.severityCounts); + return `${name}: riesgo ${s.score}${counts ? `, ${counts}` : ''} · ${policyText(s.policyCompliant, null)}`; + }); + const summary = page.items.length + ? `${label}: ${page.items.length} ${page.items.length === 1 ? 'servicio' : 'servicios'} (riesgo: más alto = peor).\n` + + lines.join('\n') + + (page.nextCursor ? '\n(hay más: usa cursor)' : '') + : `${label} no tiene servicios.`; + return toolResult(summary, { + project: label, + services: page.items, + nextCursor: page.nextCursor, + }); + }), + ); + + server.registerTool( + 'get_code_report', + { + title: 'Get the Code Report of a service', + description: + 'Returns the latest Code Report analysis of one service: date, commit and branch, risk score, ' + + 'vulnerabilities by severity, security policy compliance (with the failed rules) and, when ' + + 'monitoring is enabled, the monitors linked to the service. ' + + 'IMPORTANT: score is a RISK (higher is worse), not a quality grade. ' + + 'Use it to answer "how is the code report of X?". For the list of CVEs use list_service_cves.', + inputSchema: { + service: z + .string() + .describe('Service as "org/project/service" (slugs or names) or its id.'), + }, + outputSchema: { + service: z.string(), + report: serviceSummarySchema.extend({ + projectId: z.string(), + commit: z.string().nullable(), + branch: z.string().nullable(), + securityPolicy: z + .object({ + status: z.string().nullable(), + compliant: z.boolean().nullable(), + failedRules: z.array(failedRuleSchema), + }) + .nullable(), + monitors: z + .array(z.object({ id: z.string(), name: z.string(), status: z.string() })) + .optional(), + }), + }, + annotations: { readOnlyHint: true, openWorldHint: false }, + }, + ({ service }) => + runTool(ctx, 'get_code_report', async () => { + const svc = await resolveService(ctx.client, service); + const report = await ctx.client.get( + `/api/code-report/services/${encodeURIComponent(svc.id)}`, + ); + const label = svc.project + ? `${projectLabel(svc.project)}/${svc.slug ?? svc.name}` + : (report.slug ?? report.name); + let summary: string; + if (report.score === null) { + summary = `${label}: sin análisis de Code Report todavía.`; + } else { + const counts = describeCounts(report.severityCounts); + const failed = report.securityPolicy?.failedRules.length ?? 0; + summary = + `${label}: riesgo ${report.score} (más alto = peor)` + + (counts ? `, ${counts}` : ', sin vulnerabilidades') + + ` · ${policyText(report.policyCompliant, failed)}`; + if (report.lastAnalysisAt) summary += `\nÚltimo análisis: ${report.lastAnalysisAt}`; + if (report.branch || report.commit) { + summary += ` (${[report.branch, report.commit?.slice(0, 7)].filter(Boolean).join('@')})`; + } + const down = (report.monitors ?? []).filter((m) => m.status === 'down'); + if (down.length) summary += `\nMonitores caídos: ${down.map((m) => m.name).join(', ')}.`; + } + return toolResult(summary, { service: label, report }); + }), + ); + + server.registerTool( + 'list_service_cves', + { + title: 'List the CVEs of a service', + description: + 'Lists the vulnerabilities (CVEs) found in the latest Code Report analysis of a service, worst first ' + + '(severity, then KEV): package, installed and fixed version, severity and title. ' + + 'kev=true means the CVE is actively exploited, but it is only flagged when the CVE is in the ' + + 'CVE feed of the organization (otherwise it shows false). ' + + 'Use it for "what critical CVEs affect X?". For CVEs of a technology across the organization use list_technology_cves.', + inputSchema: { + service: z + .string() + .describe('Service as "org/project/service" (slugs or names) or its id.'), + severity: z + .array(z.enum(SEVERITIES)) + .min(1) + .optional() + .describe('Only these severities, e.g. ["critical","high"]. Omit for all.'), + fixable: z + .boolean() + .optional() + .describe('true: only CVEs with a fixed version available; false: only those without.'), + limit: z.number().int().min(1).max(100).optional().describe('Page size (default 25).'), + cursor: z.string().optional().describe('nextCursor from a previous call.'), + }, + outputSchema: { + service: z.string(), + vulnerabilities: z.array(vulnerabilitySchema), + nextCursor: z.string().nullable(), + }, + annotations: { readOnlyHint: true, openWorldHint: false }, + }, + ({ service, severity, fixable, limit, cursor }) => + runTool(ctx, 'list_service_cves', async () => { + const svc = await resolveService(ctx.client, service); + const label = svc.project ? `${projectLabel(svc.project)}/${svc.slug ?? svc.name}` : svc.id; + const page = await ctx.client.get>( + `/api/code-report/services/${encodeURIComponent(svc.id)}/vulnerabilities`, + { severity: severity?.join(','), fixable, limit, cursor }, + ); + const counts: Partial = {}; + for (const v of page.items) { + counts[v.severity as Severity] = (counts[v.severity as Severity] ?? 0) + 1; + } + const kev = page.items.filter((v) => v.kev).length; + const summary = page.items.length + ? `${label}: ${page.items.length} ${page.items.length === 1 ? 'CVE' : 'CVEs'}` + + ` (${[describeCounts(counts), kev ? `${kev} en KEV` : ''].filter(Boolean).join(', ')})` + + (page.nextCursor ? ' · hay más: usa cursor' : '') + : `${label}: ninguna vulnerabilidad con esos filtros (o sin análisis todavía).`; + return toolResult(summary, { + service: label, + vulnerabilities: page.items, + nextCursor: page.nextCursor, + }); + }), + ); } diff --git a/src/tools/cves.ts b/src/tools/cves.ts index 6cde488..3548190 100644 --- a/src/tools/cves.ts +++ b/src/tools/cves.ts @@ -1,6 +1,223 @@ import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; -import type { ToolContext } from './context.js'; +import * as z from 'zod'; +import type { ApiCveDetail, ApiCveFeed, ApiCveWatchlist } from '../api/types.js'; +import { resolveOrganization } from '../resolve.js'; +import { runTool, type ToolContext } from './context.js'; +import { toolResult } from './result.js'; -export function registerCveTools(_server: McpServer, _ctx: ToolContext): void { - // TODO(#129): get_cve_watchlist, list_cve_feed, get_cve +const FEED_DISABLED = 'El feed de CVEs por tecnología está desactivado en esta instancia.'; +const SEVERITIES = ['low', 'medium', 'high', 'critical'] as const; +const MAX_REFERENCES = 10; +const MAX_DETAILS = 1000; + +const cveItemSchema = z.object({ + id: z.string(), + aliases: z.array(z.string()), + severity: z.string(), + cvss: z.number().nullable(), + epss: z.number().nullable(), + kev: z.boolean(), + technologies: z.array(z.string()), + summary: z.string(), + publishedAt: z.string().nullable(), + modifiedAt: z.string().nullable(), + affectsMe: z.boolean().optional(), +}); + +const orgField = z.string().describe('Organization slug or id.'); + +export function registerCveTools(server: McpServer, ctx: ToolContext): void { + server.registerTool( + 'list_technology_cves', + { + title: 'List CVEs of the technologies an organization watches', + description: + 'Lists the CVEs of the organization CVE feed (the technologies it watches, e.g. Node.js, PostgreSQL), ' + + 'newest/most relevant first, with severity, CVSS, EPSS, KEV (actively exploited) and a short summary. ' + + 'Use affects_me=true to keep only the CVEs that affect services scanned in the organization projects ' + + '(needs permission to read the organization projects, otherwise it fails with a permission error). ' + + 'The severity filter is a MINIMUM: "high" returns high and critical. ' + + 'If the feed is disabled on this instance it says so, without error. ' + + 'To see the CVEs of one service use list_service_cves; for one CVE in detail use get_cve.', + inputSchema: { + organization: orgField, + technology: z + .string() + .optional() + .describe('Technology id from the watchlist (see get_cve_watchlist), e.g. "nodejs".'), + severity: z.enum(SEVERITIES).optional().describe('Minimum severity.'), + kev: z + .boolean() + .optional() + .describe('true: only CVEs in the CISA KEV catalog (known exploited).'), + affects_me: z + .boolean() + .optional() + .describe('true: only CVEs that affect your scanned services.'), + limit: z.number().int().min(1).max(100).optional().describe('Page size (default 25).'), + cursor: z.string().optional().describe('nextCursor from a previous call.'), + }, + outputSchema: { + feedEnabled: z.boolean(), + cves: z.array(cveItemSchema), + total: z.number(), + nextCursor: z.string().nullable(), + }, + annotations: { readOnlyHint: true, openWorldHint: false }, + }, + ({ organization, technology, severity, kev, affects_me, limit, cursor }) => + runTool(ctx, 'list_technology_cves', async () => { + const org = await resolveOrganization(ctx.client, organization); + const feed = await ctx.client.get('/api/cves/feed', { + organizationId: org.id, + technology, + severity, + kev, + affectsMe: affects_me, + limit, + cursor, + }); + if (!feed.feedEnabled) { + return toolResult(FEED_DISABLED, { + feedEnabled: false, + cves: [], + total: 0, + nextCursor: null, + }); + } + const items = feed.items; + const critical = items.filter((c) => c.severity === 'critical').length; + const inKev = items.filter((c) => c.kev).length; + const mine = items.filter((c) => c.affectsMe).length; + const details = [ + critical ? `${critical} ${critical === 1 ? 'crítica' : 'críticas'}` : '', + inKev ? `${inKev} en KEV` : '', + mine ? `${mine} te ${mine === 1 ? 'afecta' : 'afectan'}` : '', + ].filter(Boolean); + const summary = + `${feed.total} ${feed.total === 1 ? 'CVE' : 'CVEs'} en ${org.slug}` + + (items.length && details.length ? ` (${details.join(', ')} en esta página)` : '') + + (feed.nextCursor ? ' · hay más: usa cursor' : ''); + return toolResult(summary, { + feedEnabled: true, + cves: items, + total: feed.total, + nextCursor: feed.nextCursor, + }); + }), + ); + + server.registerTool( + 'get_cve', + { + title: 'Get a CVE in detail', + description: + 'Returns one CVE from the organization CVE feed: severity, CVSS (with vector), EPSS, KEV, CWE, ' + + 'affected packages, fixed versions, references and, when you can read the projects, which of ' + + 'your services are affected (as org/project/service). ' + + 'Use it after list_technology_cves or list_service_cves to answer "what is CVE-X and does it affect me?". ' + + 'The CVE must be in the feed of the organization (404 otherwise).', + inputSchema: { + id: z.string().describe('CVE id, e.g. "CVE-2026-12345" (or an alias such as a GHSA id).'), + organization: orgField, + }, + outputSchema: { + feedEnabled: z.boolean(), + cve: z + .object({ + id: z.string(), + title: z.string(), + aliases: z.array(z.string()), + severity: z.string(), + cvss: z.number().nullable(), + cvssVector: z.string().nullable(), + epss: z.number().nullable(), + epssPercentile: z.number().nullable(), + kev: z.boolean(), + kevAddedAt: z.string().nullable(), + cwe: z.array(z.string()), + technologies: z.array(z.string()), + summary: z.string(), + details: z.string(), + fixedVersions: z.array(z.string()), + affected: z.array(z.unknown()), + references: z.array(z.unknown()), + publishedAt: z.string().nullable(), + modifiedAt: z.string().nullable(), + affectsMe: z.boolean().optional(), + affectedServices: z.array(z.object({ service: z.string(), id: z.string() })).optional(), + }) + .nullable(), + }, + annotations: { readOnlyHint: true, openWorldHint: false }, + }, + ({ id, organization }) => + runTool(ctx, 'get_cve', async () => { + const org = await resolveOrganization(ctx.client, organization); + const detail = await ctx.client.get( + `/api/cves/${encodeURIComponent(id.trim())}`, + { organizationId: org.id }, + ); + if (!detail.feedEnabled) { + return toolResult(FEED_DISABLED, { feedEnabled: false, cve: null }); + } + const { feedEnabled: _enabled, affectedServices, references, details, ...rest } = detail; + const services = affectedServices?.map((s) => ({ + service: `${org.slug}/${s.projectSlug}/${s.serviceSlug}`, + id: s.serviceId, + })); + const cve = { + ...rest, + details: details.length > MAX_DETAILS ? `${details.slice(0, MAX_DETAILS - 1)}…` : details, + references: references.slice(0, MAX_REFERENCES), + ...(services ? { affectedServices: services } : {}), + }; + const parts = [ + `${detail.id}: severidad ${detail.severity}`, + detail.cvss !== null ? `CVSS ${detail.cvss}` : '', + detail.kev ? 'en KEV (explotada activamente)' : '', + detail.fixedVersions.length ? `arreglada en ${detail.fixedVersions.join(', ')}` : '', + ].filter(Boolean); + let summary = `${parts.join(' · ')}\n${detail.title}`; + if (services) { + summary += services.length + ? `\nAfecta a: ${services.map((s) => s.service).join(', ')}.` + : '\nNo afecta a ningún servicio escaneado.'; + } + return toolResult(summary, { feedEnabled: true, cve }); + }), + ); + + server.registerTool( + 'get_cve_watchlist', + { + title: 'Get the CVE watchlist of an organization', + description: + 'Returns which technologies the organization watches for CVEs (and the minimum severity / KEV settings). ' + + 'Use it to know the technology ids accepted by list_technology_cves.', + inputSchema: { organization: orgField }, + outputSchema: { + feedEnabled: z.boolean(), + technologies: z.array(z.object({ id: z.string(), name: z.string() }).passthrough()), + minSeverity: z.string().nullable(), + includeKev: z.boolean(), + }, + annotations: { readOnlyHint: true, openWorldHint: false }, + }, + ({ organization }) => + runTool(ctx, 'get_cve_watchlist', async () => { + const org = await resolveOrganization(ctx.client, organization); + const list = await ctx.client.get('/api/cves/watchlist', { + organizationId: org.id, + }); + const names = list.technologies.map((t) => `${t.name} (${t.id})`); + const summary = + (names.length + ? `${org.slug} vigila ${names.length} ${names.length === 1 ? 'tecnología' : 'tecnologías'}: ${names.join(', ')}.` + : `${org.slug} no vigila ninguna tecnología.`) + + (list.minSeverity ? ` Severidad mínima: ${list.minSeverity}.` : '') + + (list.feedEnabled ? '' : ` ${FEED_DISABLED}`); + return toolResult(summary, list); + }), + ); } diff --git a/test/code-report-cves.test.ts b/test/code-report-cves.test.ts new file mode 100644 index 0000000..205c8c8 --- /dev/null +++ b/test/code-report-cves.test.ts @@ -0,0 +1,312 @@ +import { Client } from '@modelcontextprotocol/sdk/client/index.js'; +import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'; +import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'; +import { IDS, startFakeApi, VALID_TOKEN, type FakeApi } from './fake-api.js'; +import { startMcp, type TestMcp } from './helpers.js'; + +let api: FakeApi; +let mcp: TestMcp; +let client: Client; +beforeAll(async () => { + api = await startFakeApi(); + mcp = await startMcp(api); + client = new Client({ name: 'test', version: '1' }); + await client.connect( + new StreamableHTTPClientTransport(new URL(`${mcp.url}/mcp`), { + requestInit: { headers: { Authorization: `Bearer ${VALID_TOKEN}` } }, + }), + ); +}); +afterAll(async () => { + await client.close(); + await mcp.close(); + await api.close(); +}); +beforeEach(() => api.reset()); + +const call = async (name: string, args: Record) => { + const result = await client.callTool({ name, arguments: args }); + return { + isError: Boolean(result.isError), + text: (result.content as { text: string }[])[0]!.text, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + data: result.structuredContent as Record | undefined, + }; +}; +const apiPaths = () => + api.requests.map((r) => r.path).filter((p) => !p.startsWith('/api/projects')); + +describe('Code Report and CVE tools', () => { + it('are listed as read-only', async () => { + const { tools } = await client.listTools(); + for (const name of [ + 'list_projects', + 'list_services', + 'get_code_report', + 'list_service_cves', + 'list_technology_cves', + 'get_cve', + 'get_cve_watchlist', + ]) { + const tool = tools.find((t) => t.name === name); + expect(tool, name).toBeDefined(); + expect(tool!.annotations?.readOnlyHint, name).toBe(true); + expect(tool!.annotations?.openWorldHint, name).toBe(false); + expect(tool!.title, name).toBeTruthy(); + } + }); + + describe('list_services', () => { + it('resolves org/project and summarises risk', async () => { + const r = await call('list_services', { project: 'acme/billing' }); + expect(r.isError).toBe(false); + expect(r.text).toContain('acme/billing: 2 servicios'); + expect(r.text).toContain('billing-api: riesgo 72, 2 críticas, 3 altas, 5 medias, 1 baja'); + expect(r.text).toContain('billing-worker: sin análisis'); + expect(apiPaths()).toEqual([`/api/code-report/services?projectId=${IDS.acmeBilling}`]); + }); + + it('accepts an id, paginates and passes limit/cursor', async () => { + const first = await call('list_services', { project: IDS.acmeBilling, limit: 1 }); + expect(first.data!.services).toHaveLength(1); + expect(first.data!.nextCursor).toBeTruthy(); + expect(first.text).toContain('hay más: usa cursor'); + const second = await call('list_services', { + project: IDS.acmeBilling, + limit: 1, + cursor: first.data!.nextCursor, + }); + expect(second.data!.services[0].name).toBe('billing-worker'); + expect(second.data!.nextCursor).toBeNull(); + expect(api.requests.at(-1)!.path).toContain('limit=1&cursor='); + }); + + it('reports an ambiguous slug and an unknown project', async () => { + const ambiguous = await call('list_services', { project: 'billing' }); + expect(ambiguous.isError).toBe(true); + expect(ambiguous.text).toMatch(/ambiguous/); + expect(ambiguous.text).toContain('acme/billing'); + const unknown = await call('list_services', { project: 'acme/nope' }); + expect(unknown.isError).toBe(true); + expect(unknown.text).toMatch(/not found/); + }); + }); + + describe('get_code_report', () => { + it('summarises score, severities, policy and monitors by slug', async () => { + const r = await call('get_code_report', { service: 'acme/billing/billing-api' }); + expect(r.isError).toBe(false); + expect(r.text).toContain( + 'acme/billing/billing-api: riesgo 72 (más alto = peor), 2 críticas, 3 altas, 5 medias, 1 baja · política INCUMPLIDA (1 regla)', + ); + expect(r.text).toContain('main@abc1234'); + expect(r.text).toContain('Monitores caídos: billing-api'); + expect(r.data!.report.securityPolicy.failedRules[0].rule).toBe('critical'); + expect(apiPaths()).toEqual([ + `/api/code-report/services?projectId=${IDS.acmeBilling}&limit=100`, + `/api/code-report/services/${IDS.svcBillingApi}`, + ]); + }); + + it('accepts an id without resolving', async () => { + const r = await call('get_code_report', { service: IDS.svcWebFront }); + expect(r.text).toContain('web-front: riesgo 95'); + expect(r.text).toContain('política CUMPLIDA'); + expect(apiPaths()).toEqual([`/api/code-report/services/${IDS.svcWebFront}`]); + }); + + it('handles a service never analysed', async () => { + const r = await call('get_code_report', { service: 'acme/billing/billing-worker' }); + expect(r.isError).toBe(false); + expect(r.text).toContain('sin análisis'); + }); + + it('errors: unknown service, 403, 404, 429', async () => { + const unknown = await call('get_code_report', { service: 'acme/billing/nope' }); + expect(unknown.isError).toBe(true); + expect(unknown.text).toContain('billing-api'); + const bad = await call('get_code_report', { service: 'billing-api' }); + expect(bad.isError).toBe(true); + expect(bad.text).toMatch(/org\/project\/service/); + + api.failNext({ status: 403, code: 'forbidden', error: 'Forbidden' }); + expect((await call('get_code_report', { service: IDS.svcWebFront })).text).toMatch( + /^Sin permiso/, + ); + const notFound = await call('get_code_report', { service: IDS.acmeBilling }); + expect(notFound.isError).toBe(true); + expect(notFound.text).toMatch(/No encontrado o sin acceso/); + api.failNext({ status: 429, code: 'rate_limited', headers: { 'Retry-After': '3' } }); + expect((await call('get_code_report', { service: IDS.svcWebFront })).text).toMatch( + /reintenta en 3 s/, + ); + }); + }); + + describe('list_service_cves', () => { + it('sends severity and fixable as query and summarises', async () => { + const r = await call('list_service_cves', { + service: 'acme/billing/billing-api', + severity: ['critical', 'high'], + fixable: true, + }); + expect(r.isError).toBe(false); + const req = api.requests.at(-1)!; + expect(req.path).toBe( + `/api/code-report/services/${IDS.svcBillingApi}/vulnerabilities?severity=critical%2Chigh&fixable=true`, + ); + expect(r.data!.vulnerabilities.map((v: { id: string }) => v.id)).toEqual(['CVE-2026-0001']); + expect(r.text).toContain('1 CVE (1 crítica, 1 en KEV)'); + }); + + it('paginates', async () => { + const first = await call('list_service_cves', { service: IDS.svcBillingApi, limit: 1 }); + expect(first.data!.nextCursor).toBeTruthy(); + expect(first.text).toContain('hay más: usa cursor'); + const second = await call('list_service_cves', { + service: IDS.svcBillingApi, + limit: 1, + cursor: first.data!.nextCursor, + }); + expect(second.data!.vulnerabilities[0].id).toBe('CVE-2026-0003'); + }); + + it('empty result and invalid severity', async () => { + const empty = await call('list_service_cves', { service: IDS.svcWebFront }); + expect(empty.text).toContain('ninguna vulnerabilidad'); + const invalid = await client.callTool({ + name: 'list_service_cves', + arguments: { service: IDS.svcWebFront, severity: ['nope'] }, + }); + expect(invalid.isError).toBe(true); + }); + }); + + describe('list_technology_cves', () => { + it('resolves the organization and sends the filters', async () => { + const r = await call('list_technology_cves', { + organization: 'acme', + technology: 'nodejs', + severity: 'high', + kev: true, + affects_me: true, + limit: 5, + }); + expect(r.isError).toBe(false); + expect(api.requests.at(-1)!.path).toBe( + `/api/cves/feed?organizationId=${IDS.orgAcme}&technology=nodejs&severity=high&kev=true&affectsMe=true&limit=5`, + ); + expect(r.text).toContain('1 CVE en acme (1 crítica, 1 en KEV, 1 te afecta en esta página)'); + expect(r.data!.cves[0].id).toBe('CVE-2026-0001'); + }); + + it('paginates with total', async () => { + const first = await call('list_technology_cves', { organization: IDS.orgAcme, limit: 1 }); + expect(first.text).toContain('2 CVEs en acme'); + expect(first.text).toContain('hay más: usa cursor'); + const second = await call('list_technology_cves', { + organization: 'acme', + limit: 1, + cursor: first.data!.nextCursor, + }); + expect(second.data!.cves[0].id).toBe('CVE-2026-0002'); + expect(second.data!.nextCursor).toBeNull(); + }); + + it('feed disabled is not an error', async () => { + api.route('GET', /^\/api\/cves\/feed$/, () => ({ + body: { feedEnabled: false, items: [], nextCursor: null, total: 0 }, + })); + const r = await call('list_technology_cves', { organization: 'acme' }); + expect(r.isError).toBe(false); + expect(r.text).toContain('El feed de CVEs por tecnología está desactivado en esta instancia'); + expect(r.data!.feedEnabled).toBe(false); + }); + + it('affects_me without permission gives a useful 403', async () => { + api.route('GET', /^\/api\/cves\/feed$/, () => ({ + status: 403, + body: { + error: 'affectsMe requires organization:projects:read', + code: 'forbidden', + }, + })); + const r = await call('list_technology_cves', { organization: 'acme', affects_me: true }); + expect(r.isError).toBe(true); + expect(r.text).toBe('Sin permiso: affectsMe requires organization:projects:read'); + }); + + it('unknown organization and 429', async () => { + const unknown = await call('list_technology_cves', { organization: 'nope' }); + expect(unknown.isError).toBe(true); + expect(unknown.text).toContain('Known organizations: acme, globex'); + api.failNext({ status: 429, code: 'rate_limited' }); + const limited = await call('list_technology_cves', { organization: 'acme' }); + expect(limited.text).toMatch(/Límite de peticiones/); + }); + }); + + describe('get_cve', () => { + it('returns the detail', async () => { + const r = await call('get_cve', { id: 'CVE-2026-0001', organization: 'acme' }); + expect(r.isError).toBe(false); + expect(api.requests.at(-1)!.path).toBe( + `/api/cves/CVE-2026-0001?organizationId=${IDS.orgAcme}`, + ); + expect(r.text).toContain('CVE-2026-0001: severidad critical · CVSS 9.8 · en KEV'); + expect(r.data!.cve.id).toBe('CVE-2026-0001'); + }); + + it('lists affected services as org/project/service and trims references', async () => { + const base = api.db.cves[0]!; + api.db.cveDetails['CVE-2026-0001'] = { + feedEnabled: true, + ...base, + title: 'Prototype pollution', + cvssVector: null, + epssPercentile: null, + kevAddedAt: null, + cwe: [], + fixedVersions: ['4.17.21'], + affected: [], + references: Array.from({ length: 30 }, (_, i) => ({ url: `https://x/${i}` })), + details: 'x'.repeat(5000), + affectedServices: [ + { + projectId: IDS.acmeBilling, + projectSlug: 'billing', + projectName: 'Billing', + serviceId: IDS.svcBillingApi, + serviceSlug: 'billing-api', + serviceName: 'billing-api', + }, + ], + }; + const r = await call('get_cve', { id: 'CVE-2026-0001', organization: 'acme' }); + expect(r.text).toContain('Afecta a: acme/billing/billing-api'); + expect(r.text).toContain('arreglada en 4.17.21'); + expect(r.data!.cve.references).toHaveLength(10); + expect(r.data!.cve.details.length).toBeLessThanOrEqual(1000); + }); + + it('404 and feed disabled', async () => { + const missing = await call('get_cve', { id: 'CVE-1999-0', organization: 'acme' }); + expect(missing.isError).toBe(true); + expect(missing.text).toMatch(/No encontrado/); + api.route('GET', /^\/api\/cves\/([^/]+)$/, () => ({ + body: { feedEnabled: false, cve: null }, + })); + const off = await call('get_cve', { id: 'CVE-2026-0001', organization: 'acme' }); + expect(off.isError).toBe(false); + expect(off.text).toContain('desactivado'); + }); + }); + + describe('get_cve_watchlist', () => { + it('lists watched technologies', async () => { + const r = await call('get_cve_watchlist', { organization: 'acme' }); + expect(r.text).toContain('acme vigila 1 tecnología: Node.js (nodejs)'); + expect(api.requests.at(-1)!.path).toBe(`/api/cves/watchlist?organizationId=${IDS.orgAcme}`); + }); + }); +}); From ffeb524909346a5b9f0079057e731a187def7cbb Mon Sep 17 00:00:00 2001 From: Carlos Lopez Date: Mon, 30 Nov 2026 15:50:33 +0100 Subject: [PATCH 5/5] feat: Monitoring tools (#130) Co-Authored-By: Claude Opus 5.5 --- README.md | 23 +- src/tools/context.ts | 5 +- src/tools/monitoring.ts | 586 +++++++++++++++++++++++++++++++++++++++- src/tools/result.ts | 16 +- test/fake-api.ts | 28 +- test/monitoring.test.ts | 336 +++++++++++++++++++++++ 6 files changed, 984 insertions(+), 10 deletions(-) create mode 100644 test/monitoring.test.ts diff --git a/README.md b/README.md index e67a6d7..e2a1f56 100644 --- a/README.md +++ b/README.md @@ -93,7 +93,28 @@ Todas devuelven primero un resumen corto y después JSON compacto (sin nulls). L | --------------- | ------------------- | --------------------------------------------------------------------- | | `list_projects` | `GET /api/projects` | Proyectos visibles (`organization?` por slug/id, `limit?`, `cursor?`) | -Pendientes: Code Report y CVEs (#129), Monitoring (#130). +Pendientes: Code Report y CVEs (#129). + +## Monitoring + +| Tool | API | Descripción | +| ----------------------- | ------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------ | +| `get_monitoring_status` | `GET /api/monitoring/status`, `GET /api/monitoring/monitors` | "¿Está todo bien?": `project` **o** `service` (exactamente uno) | +| `list_monitors` | `GET /api/monitoring/monitors` | `project`, `service?`, `limit?`, `cursor?` | +| `get_monitor` | `GET /api/monitoring/monitors/[id]` | Uptime 24h/7d/30d, incidente abierto y últimos incidentes | +| `create_monitor` | `POST /api/monitoring/monitors` | `project`, `url`, `name?`, `method?`, `interval?` (30-3600 s), `timeout?` (1-30 s), `expected_status?`, `service?` | +| `test_monitor` | `POST /api/monitoring/monitors/[id]/test` | Un chequeo inmediato; no se guarda en el historial | + +Ejemplos: + +- "¿Está todo bien en acme/billing?" → `acme/billing: 5 up, 1 down (api-health desde hace 12 min: timeout) · 0 degradados` +- "Crea un monitor para https://api.acme.com/health en el proyecto acme/billing" → `Monitor creado: api.acme.com/health (GET https://api.acme.com/health cada 60 s) en acme/billing. Empezará a chequearse en breve.` + +Notas: + +- `create_monitor` **no admite cabeceras ni body** en v1 (el schema no los acepta y la API los rechaza para claves MCP). Las respuestas solo incluyen nombres de cabeceras y si hay body, nunca sus valores. +- Los errores de validación de la API se traducen al nombre de cada input (`intervalSeconds` → `interval`, `timeoutMs` → `timeout`…) con una explicación para que el agente pueda corregirlo. Si Monitoring no está activado en el proyecto, el error lo indica. +- `create_monitor` y `test_monitor` no son de solo lectura: el cliente suele pedir confirmación. ## Licencia diff --git a/src/tools/context.ts b/src/tools/context.ts index e1044b8..7c6fdb8 100644 --- a/src/tools/context.ts +++ b/src/tools/context.ts @@ -1,7 +1,7 @@ import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js'; import { GitOpsApiError, type GitOpsApiClient } from '../api/client.js'; import type { Logger } from '../log.js'; -import { toolError } from './result.js'; +import { ToolMessageError, toolError } from './result.js'; /** What every tool gets. One per MCP request; `client` already carries the caller's token. */ export interface ToolContext { @@ -26,10 +26,11 @@ export async function runTool( ctx.log.info('tool ok', { ...base, durationMs: Date.now() - started }); return result; } catch (err) { + const api = err instanceof ToolMessageError ? err.api : err; ctx.log.warn('tool error', { ...base, durationMs: Date.now() - started, - ...(err instanceof GitOpsApiError ? { apiStatus: err.status, code: err.code } : {}), + ...(api instanceof GitOpsApiError ? { apiStatus: api.status, code: api.code } : {}), }); return toolError(err); } diff --git a/src/tools/monitoring.ts b/src/tools/monitoring.ts index 302edd6..b282f00 100644 --- a/src/tools/monitoring.ts +++ b/src/tools/monitoring.ts @@ -1,6 +1,586 @@ import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; -import type { ToolContext } from './context.js'; +import * as z from 'zod'; +import { fetchAll, GitOpsApiError } from '../api/client.js'; +import type { + ApiIncident, + ApiMonitorDetail, + ApiMonitoringStatus, + ApiMonitorSummary, + ApiMonitorTestResult, + ApiOpenIncident, + CreateMonitorBody, + Page, +} from '../api/types.js'; +import { + projectLabel, + ResolveError, + resolveProject, + resolveService, + type ResolvedService, +} from '../resolve.js'; +import { runTool, type ToolContext } from './context.js'; +import { ToolMessageError, toolResult } from './result.js'; -export function registerMonitoringTools(_server: McpServer, _ctx: ToolContext): void { - // TODO(#130): get_monitoring_status, list_monitors, get_monitor, create_monitor, test_monitor +// ---- Error translation ------------------------------------------------------------------------- + +/** API field name -> name of the tool input the agent has to fix. */ +const FIELD_TO_INPUT: Record = { + projectId: 'project', + serviceId: 'service', + intervalSeconds: 'interval', + timeoutMs: 'timeout', + expectedStatus: 'expected_status', + name: 'name', + url: 'url', + method: 'method', +}; + +const NO_SECRETS = + 'En v1 el MCP no admite cabeceras ni body en los monitores; créalo desde la UI de GitOps ' + + 'o con una clave de API normal.'; + +/** Explanation (Spanish) of each `monitoring.errors.*` code, with the tool input in context. */ +function explainCode(code: string, input: string): string { + switch (code) { + case 'required': + return 'es obligatorio'; + case 'too_long': + return input === 'name' + ? 'es demasiado largo (máximo 120 caracteres)' + : 'es demasiado largo (máximo 2048 caracteres)'; + case 'invalid_url': + return 'debe ser una URL http o https válida (p. ej. https://api.acme.com/health)'; + case 'private_target': + return 'no puede apuntar a direcciones privadas, locales o internas (localhost, 10.x, 192.168.x…)'; + case 'invalid_method': + return 'método HTTP no válido; usa GET, HEAD, POST, PUT, PATCH, DELETE u OPTIONS'; + case 'out_of_range': + if (input === 'interval') return 'fuera de rango; el intervalo va de 30 a 3600 segundos'; + if (input === 'timeout') return 'fuera de rango; el timeout va de 1 a 30 segundos'; + return 'valor fuera del rango permitido'; + case 'invalid_expected_status': + return 'usa códigos HTTP 100-599 o rangos separados por comas, p. ej. "200", "200-299,301"'; + case 'service_not_found': + return 'el servicio no existe en este proyecto'; + case 'too_many_headers': + case 'invalid_header': + case 'duplicate_header': + return NO_SECRETS; + default: + return `no válido (${code})`; + } +} + +const stripPrefix = (code: string) => code.replace(/^monitoring\.errors\./, ''); + +/** Turns the API's per-field validation failure into one message the agent can act on. */ +export function describeValidation(errors: Record): string { + const lines: string[] = []; + const seen = new Set(); + for (const [field, raw] of Object.entries(errors)) { + const secret = field === 'headers' || field.startsWith('headers.') || field === 'body'; + const input = secret ? field : (FIELD_TO_INPUT[field] ?? field); + const text = secret ? NO_SECRETS : explainCode(stripPrefix(raw), input); + const line = secret ? text : `${input}: ${text}`; + if (!seen.has(line)) lines.push(line); + seen.add(line); + } + return `Monitor no válido. Corrige: ${lines.join('; ')}.`; +} + +/** Runs an API call, translating the monitoring-specific failures into agent-friendly messages. */ +async function api(call: () => Promise): Promise { + try { + return await call(); + } catch (err) { + if (err instanceof GitOpsApiError) { + if (err.code === 'module_disabled') { + throw new ToolMessageError( + 'Monitoring no está activado en este proyecto; actívalo en Ajustes del proyecto.', + err, + ); + } + if (err.code === 'mcp_monitor_secrets_not_allowed') { + throw new ToolMessageError(NO_SECRETS, err); + } + if (err.code === 'validation_failed' && err.fieldErrors) { + throw new ToolMessageError(describeValidation(err.fieldErrors), err); + } + } + throw err; + } +} + +// ---- Formatting helpers -------------------------------------------------------------------------- + +function ago(since: string, now = Date.now()): string { + const minutes = Math.max(0, Math.round((now - Date.parse(since)) / 60_000)); + if (Number.isNaN(minutes)) return 'hace un tiempo'; + if (minutes < 1) return 'hace menos de 1 min'; + if (minutes < 60) return `hace ${minutes} min`; + const hours = Math.round(minutes / 60); + if (hours < 48) return `hace ${hours} h`; + return `hace ${Math.round(hours / 24)} días`; +} + +/** The API sends uptime as a 0..1 ratio. */ +function percent(ratio: number | null | undefined): string { + if (ratio == null) return 'n/d'; + return `${(Math.round(ratio * 10_000) / 100).toString()}%`; +} + +const short = (text: string | null | undefined, max = 120) => + !text ? '' : text.length > max ? `${text.slice(0, max - 1)}…` : text; + +function incidentNote(i: ApiOpenIncident): string { + const cause = short(i.cause, 80); + return `${i.name} desde ${ago(i.since)}${cause ? `: ${cause}` : ''}`; +} + +/** "acme/billing: 5 up, 1 down (api-health desde hace 12 min: timeout) · 0 degradados" */ +function statusSummary(label: string, s: ApiMonitoringStatus): string { + if (s.total === 0) return `${label}: no hay monitores configurados.`; + const notes = (status: string) => { + const list = s.openIncidents.filter((i) => i.status === status).map(incidentNote); + return list.length ? ` (${list.join('; ')})` : ''; + }; + const extras = [ + s.paused ? `${s.paused} en pausa` : '', + s.pending ? `${s.pending} pendientes de primer chequeo` : '', + ].filter(Boolean); + return ( + `${label}: ${s.up} up, ${s.down} down${notes('down')} · ${s.degraded} degradados${notes('degraded')}` + + (extras.length ? ` · ${extras.join(', ')}` : '') + ); +} + +/** Same derivation the API does for a whole project, but over an already-filtered list. */ +function countStatuses(monitors: ApiMonitorSummary[]) { + const counts = { up: 0, degraded: 0, down: 0, paused: 0, pending: 0 }; + for (const m of monitors) counts[m.status]++; + return { ...counts, total: monitors.length }; +} + +const intervalText = (seconds: number) => `${seconds} s`; + +// ---- Output schemas ------------------------------------------------------------------------------ + +const statusEnum = z.enum(['up', 'degraded', 'down', 'paused', 'pending']); + +const incidentSchema = z.object({ + id: z.string(), + status: z.string(), + cause: z.string().nullable(), + httpStatus: z.number().nullable(), + error: z.string().nullable(), + startedAt: z.string(), + endedAt: z.string().nullable(), + failedChecks: z.number(), +}); + +const monitorSummarySchema = z.object({ + id: z.string(), + name: z.string(), + method: z.string(), + url: z.string(), + serviceId: z.string().nullable(), + enabled: z.boolean(), + status: statusEnum, + uptime24h: z.number().nullable(), + hasHeaders: z.boolean(), + hasBody: z.boolean(), +}); + +const monitorDetailSchema = monitorSummarySchema.extend({ + headerNames: z.array(z.string()), + intervalSeconds: z.number(), + timeoutMs: z.number(), + expectedStatus: z.union([z.string(), z.number()]), + uptime: z.object({ + h24: z.number().nullable(), + d7: z.number().nullable(), + d30: z.number().nullable(), + }), + openIncident: incidentSchema.nullable(), + incidents: z.array(incidentSchema), +}); + +/** Only the fields we know are safe: never header values or the body. */ +function pickSummary(m: ApiMonitorSummary): ApiMonitorSummary { + return { + id: m.id, + name: m.name, + method: m.method, + url: m.url, + serviceId: m.serviceId, + enabled: m.enabled, + status: m.status, + uptime24h: m.uptime24h, + hasHeaders: m.hasHeaders, + hasBody: m.hasBody, + }; +} + +const pickIncident = (i: ApiIncident): ApiIncident => ({ + id: i.id, + status: i.status, + cause: i.cause ? short(i.cause, 200) : null, + httpStatus: i.httpStatus, + error: i.error ? short(i.error, 200) : null, + startedAt: i.startedAt, + endedAt: i.endedAt, + failedChecks: i.failedChecks, +}); + +function pickDetail(m: ApiMonitorDetail): ApiMonitorDetail { + return { + ...pickSummary(m), + headerNames: m.headerNames ?? [], + intervalSeconds: m.intervalSeconds, + timeoutMs: m.timeoutMs, + expectedStatus: m.expectedStatus, + uptime: { h24: m.uptime?.h24 ?? null, d7: m.uptime?.d7 ?? null, d30: m.uptime?.d30 ?? null }, + openIncident: m.openIncident ? pickIncident(m.openIncident) : null, + incidents: (m.incidents ?? []).slice(0, 10).map(pickIncident), + }; +} + +// ---- Create helpers ----------------------------------------------------------------------------- + +/** Name derived from host + path: `https://api.acme.com/health` -> `api.acme.com/health`. */ +export function deriveMonitorName(url: string): string { + try { + const parsed = new URL(url); + const path = parsed.pathname.replace(/\/+$/, ''); + return `${parsed.host}${path}`.slice(0, 120); + } catch { + return url.slice(0, 120); + } +} + +async function projectOfService(ctx: ToolContext, service: ResolvedService, project?: string) { + if (service.project) { + if (project) { + const given = await resolveProject(ctx.client, project); + if (given.id !== service.project.id) { + throw new ResolveError( + `El servicio ${service.name} pertenece a ${projectLabel(service.project)}, no a ${projectLabel(given)}.`, + ); + } + } + return service.project; + } + if (project) return resolveProject(ctx.client, project); + throw new ResolveError( + 'Con un id de servicio no puedo saber su proyecto. Usa org/proyecto/servicio o indica también el proyecto.', + ); +} + +// ---- Tools --------------------------------------------------------------------------------------- + +export function registerMonitoringTools(server: McpServer, ctx: ToolContext): void { + server.registerTool( + 'get_monitoring_status', + { + title: 'Monitoring status', + description: + 'Answers "is everything OK?": how many monitors are up, degraded, down, paused or pending, and ' + + 'which ones have an open incident (since when and why). Pass exactly one of `project` ' + + '("org/project" or id) for a whole project, or `service` ("org/project/service" or id) to ' + + 'look only at the monitors linked to that service.', + inputSchema: { + project: z.string().optional().describe('Project as "org/project" or id.'), + service: z + .string() + .optional() + .describe('Service as "org/project/service" or id. Alternative to `project`.'), + }, + outputSchema: { + scope: z.string(), + up: z.number(), + degraded: z.number(), + down: z.number(), + paused: z.number(), + pending: z.number(), + total: z.number(), + openIncidents: z.array( + z.object({ + monitorId: z.string(), + name: z.string(), + status: z.string(), + since: z.string(), + cause: z.string().nullable(), + }), + ), + }, + annotations: { readOnlyHint: true, openWorldHint: false }, + }, + ({ project, service }) => + runTool(ctx, 'get_monitoring_status', async () => { + if (!project && !service) { + throw new ResolveError('Indica `project` o `service` (exactamente uno de los dos).'); + } + if (project && service) { + throw new ResolveError( + 'Indica solo uno: `project` (todo el proyecto) o `service` (solo ese servicio), no ambos.', + ); + } + if (project) { + const p = await resolveProject(ctx.client, project); + const status = await api(() => + ctx.client.get('/api/monitoring/status', { projectId: p.id }), + ); + const label = projectLabel(p); + return toolResult(statusSummary(label, status), { scope: label, ...status }); + } + + const svc = await resolveService(ctx.client, service!); + const p = await projectOfService(ctx, svc); + const label = `${projectLabel(p)}/${svc.slug ?? svc.name}`; + const monitors = await api(() => + fetchAll(ctx.client, '/api/monitoring/monitors', { + projectId: p.id, + serviceId: svc.id, + }), + ); + // The list has no incident info: fetch the detail of the (few) failing monitors. + const failing = monitors.filter((m) => m.status === 'down' || m.status === 'degraded'); + const details = await Promise.all( + failing + .slice(0, 10) + .map((m) => ctx.client.get(`/api/monitoring/monitors/${m.id}`)), + ); + const openIncidents: ApiOpenIncident[] = details.flatMap((d) => + d.openIncident + ? [ + { + monitorId: d.id, + name: d.name, + status: d.openIncident.status, + since: d.openIncident.startedAt, + cause: d.openIncident.cause, + }, + ] + : [], + ); + const status: ApiMonitoringStatus = { ...countStatuses(monitors), openIncidents }; + return toolResult(statusSummary(label, status), { scope: label, ...status }); + }), + ); + + server.registerTool( + 'list_monitors', + { + title: 'List monitors', + description: + 'Lists the uptime monitors of a project (optionally only those linked to a service) with ' + + 'status and 24h uptime. Use get_monitor for uptime 7d/30d and incidents.', + inputSchema: { + project: z.string().describe('Project as "org/project" or id.'), + service: z + .string() + .optional() + .describe('Only monitors linked to this service ("org/project/service" or id).'), + limit: z.number().int().min(1).max(100).optional().describe('Page size (default 25).'), + cursor: z.string().optional().describe('nextCursor from a previous call.'), + }, + outputSchema: { monitors: z.array(monitorSummarySchema), nextCursor: z.string().nullable() }, + annotations: { readOnlyHint: true, openWorldHint: false }, + }, + ({ project, service, limit, cursor }) => + runTool(ctx, 'list_monitors', async () => { + const p = await resolveProject(ctx.client, project); + let serviceId: string | undefined; + if (service) { + const svc = await resolveService(ctx.client, service); + if (svc.project && svc.project.id !== p.id) { + throw new ResolveError( + `El servicio ${svc.name} pertenece a ${projectLabel(svc.project)}, no a ${projectLabel(p)}.`, + ); + } + serviceId = svc.id; + } + const page = await api(() => + ctx.client.get>('/api/monitoring/monitors', { + projectId: p.id, + serviceId, + limit, + cursor, + }), + ); + const monitors = page.items.map(pickSummary); + const label = projectLabel(p); + const summary = monitors.length + ? `${monitors.length} ${monitors.length === 1 ? 'monitor' : 'monitores'} en ${label}: ` + + monitors + .map((m) => `${m.name} (${m.status}, uptime 24h ${percent(m.uptime24h)})`) + .join(', ') + + (page.nextCursor ? ' (hay más, usa cursor)' : '') + : `No hay monitores en ${label}.`; + return toolResult(summary, { monitors, nextCursor: page.nextCursor }); + }), + ); + + server.registerTool( + 'get_monitor', + { + title: 'Get monitor', + description: + 'Details of one monitor: configuration, uptime 24h/7d/30d (as percentages in the summary), ' + + 'the open incident if any and the latest incidents. Header values and body are never ' + + 'returned, only header names and whether a body exists.', + inputSchema: { id: z.string().describe('Monitor id (from list_monitors).') }, + outputSchema: monitorDetailSchema.shape, + annotations: { readOnlyHint: true, openWorldHint: false }, + }, + ({ id }) => + runTool(ctx, 'get_monitor', async () => { + const raw = await api(() => + ctx.client.get(`/api/monitoring/monitors/${encodeURIComponent(id)}`), + ); + const m = pickDetail(raw); + const parts = [ + `${m.name}: ${m.status}`, + `${m.method} ${m.url} cada ${intervalText(m.intervalSeconds)}`, + `uptime 24h ${percent(m.uptime.h24)} · 7d ${percent(m.uptime.d7)} · 30d ${percent(m.uptime.d30)}`, + ]; + if (m.openIncident) { + const cause = short(m.openIncident.cause ?? m.openIncident.error, 80); + parts.push( + `incidente abierto (${m.openIncident.status}) desde ${ago(m.openIncident.startedAt)}${cause ? `: ${cause}` : ''}`, + ); + } else { + parts.push('sin incidente abierto'); + } + parts.push(`${m.incidents.length} incidentes recientes`); + if (m.hasHeaders) parts.push(`cabeceras: ${m.headerNames.join(', ')} (valores ocultos)`); + if (m.hasBody) parts.push('con body (oculto)'); + return toolResult(parts.join(' · '), m); + }), + ); + + server.registerTool( + 'create_monitor', + { + title: 'Create monitor', + description: + 'Creates an HTTP uptime monitor for a URL in a project. It does NOT support request headers ' + + 'or body (not allowed through MCP in v1). Defaults: GET, every 60 s, timeout 10 s, expects ' + + 'a 2xx status. Private/internal addresses are rejected. Monitoring must be enabled in the ' + + 'project. This writes data: confirm the details with the user first.', + inputSchema: { + project: z.string().describe('Project as "org/project" or id.'), + url: z.string().describe('Public http(s) URL to check, e.g. https://api.acme.com/health.'), + name: z + .string() + .optional() + .describe('Monitor name (max 120). Defaults to host + path of the URL.'), + method: z + .string() + .optional() + .describe('HTTP method: GET (default), HEAD, POST, PUT, PATCH, DELETE or OPTIONS.'), + interval: z + .number() + .int() + .optional() + .describe('Seconds between checks, 30 to 3600 (default 60).'), + timeout: z + .number() + .int() + .optional() + .describe('Seconds to wait for a response, 1 to 30 (default 10).'), + expected_status: z + .union([z.string(), z.number()]) + .optional() + .describe('Expected HTTP status: a code or ranges, e.g. 200 or "200-299,301".'), + service: z + .string() + .optional() + .describe('Link the monitor to this service ("org/project/service" or id).'), + }, + outputSchema: monitorDetailSchema.shape, + annotations: { + readOnlyHint: false, + destructiveHint: false, + idempotentHint: false, + openWorldHint: false, + }, + }, + ({ project, url, name, method, interval, timeout, expected_status, service }) => + runTool(ctx, 'create_monitor', async () => { + const p = await resolveProject(ctx.client, project); + let serviceId: string | undefined; + if (service) { + const svc = await resolveService(ctx.client, service); + if (svc.project && svc.project.id !== p.id) { + throw new ResolveError( + `El servicio ${svc.name} pertenece a ${projectLabel(svc.project)}, no a ${projectLabel(p)}.`, + ); + } + serviceId = svc.id; + } + // Explicit allowlist: nothing else (headers, body…) can ever reach the API from here. + const body: CreateMonitorBody = { + projectId: p.id, + name: name?.trim() || deriveMonitorName(url.trim()), + url: url.trim(), + ...(method ? { method } : {}), + ...(serviceId ? { serviceId } : {}), + ...(interval !== undefined ? { intervalSeconds: interval } : {}), + ...(timeout !== undefined ? { timeoutMs: timeout * 1000 } : {}), + ...(expected_status !== undefined ? { expectedStatus: expected_status } : {}), + }; + const raw = await api(() => + ctx.client.post('/api/monitoring/monitors', body), + ); + const m = pickDetail(raw); + return toolResult( + `Monitor creado: ${m.name} (${m.method} ${m.url} cada ${intervalText(m.intervalSeconds)}) en ${projectLabel(p)}. ` + + `Empezará a chequearse en breve. Id: ${m.id}`, + m, + ); + }), + ); + + server.registerTool( + 'test_monitor', + { + title: 'Test monitor', + description: + 'Runs one check of an existing monitor right now and returns the outcome (status, HTTP ' + + 'status, latency, error). Nothing is saved to its history.', + inputSchema: { id: z.string().describe('Monitor id (from list_monitors).') }, + outputSchema: { + status: z.string(), + httpStatus: z.number().nullable(), + latencyMs: z.number().nullable(), + error: z.string().nullable(), + }, + annotations: { + readOnlyHint: false, + destructiveHint: false, + idempotentHint: true, + openWorldHint: true, + }, + }, + ({ id }) => + runTool(ctx, 'test_monitor', async () => { + const r = await api(() => + ctx.client.post( + `/api/monitoring/monitors/${encodeURIComponent(id)}/test`, + ), + ); + const result = { + status: r.status, + httpStatus: r.httpStatus, + latencyMs: r.latencyMs, + error: r.error ? short(r.error, 200) : null, + }; + const parts = [`Chequeo de prueba: ${result.status}`]; + if (result.httpStatus != null) parts.push(`HTTP ${result.httpStatus}`); + if (result.latencyMs != null) parts.push(`${result.latencyMs} ms`); + if (result.error) parts.push(`error: ${result.error}`); + return toolResult(parts.join(' · '), result); + }), + ); } diff --git a/src/tools/result.ts b/src/tools/result.ts index 39d9705..f3a6fc6 100644 --- a/src/tools/result.ts +++ b/src/tools/result.ts @@ -23,6 +23,20 @@ export function toolResult(summary: string, data: object): CallToolResult { }; } +/** + * A failure whose message is already written for the agent (e.g. translated API validation + * errors). `api` keeps the original API error so `runTool` can still log its status and code. + */ +export class ToolMessageError extends Error { + constructor( + message: string, + readonly api?: GitOpsApiError, + ) { + super(message); + this.name = 'ToolMessageError'; + } +} + function describe(err: GitOpsApiError): string { switch (err.status) { case 401: @@ -58,7 +72,7 @@ function describe(err: GitOpsApiError): string { export function toolError(err: unknown): CallToolResult { let text: string; if (err instanceof GitOpsApiError) text = describe(err); - else if (err instanceof ResolveError) text = err.message; + else if (err instanceof ResolveError || err instanceof ToolMessageError) text = err.message; else text = 'Error interno del servidor MCP.'; return { isError: true, content: [{ type: 'text', text }] }; } diff --git a/test/fake-api.ts b/test/fake-api.ts index b5e4cb0..381b7b1 100644 --- a/test/fake-api.ts +++ b/test/fake-api.ts @@ -87,14 +87,14 @@ export function seed(): FakeDb { serviceId, enabled: true, status, - uptime24h: status === 'down' ? 91.5 : 100, + uptime24h: status === 'down' ? 0.915 : 1, hasHeaders: false, hasBody: false, headerNames: [], intervalSeconds: 60, timeoutMs: 10000, expectedStatus: 200, - uptime: { h24: status === 'down' ? 91.5 : 100, d7: 99.9, d30: 99.95 }, + uptime: { h24: status === 'down' ? 0.915 : 1, d7: 0.999, d30: 0.9995 }, openIncident: status === 'down' ? { @@ -407,7 +407,10 @@ export function defaultRoutes(): Route[] { handler: ({ url, db }) => { const projectId = url.searchParams.get('projectId'); if (!projectId) return err(400, 'invalid_request', 'projectId is required'); - if (!db.projects.some((p) => p.id === projectId)) return notFound('Project'); + const statusProject = db.projects.find((p) => p.id === projectId); + if (!statusProject) return notFound('Project'); + if (!statusProject.modules.includes('monitoring')) + return err(409, 'module_disabled', 'Monitoring is not enabled in this project'); const rows = db.monitors.filter((m) => m.projectId === projectId); const status: ApiMonitoringStatus = { up: 0, @@ -446,10 +449,29 @@ export function defaultRoutes(): Route[] { ); const project = db.projects.find((p) => p.id === b.projectId); if (!project) return notFound('Project'); + if (!project.modules.includes('monitoring')) + return err(409, 'module_disabled', 'Monitoring is not enabled in this project'); const errors: Record = {}; if (typeof b.name !== 'string' || !b.name) errors.name = 'monitoring.errors.required'; if (typeof b.url !== 'string' || !/^https?:\/\//.test(b.url)) errors.url = 'monitoring.errors.invalid_url'; + const interval = b.intervalSeconds; + if ( + interval !== undefined && + (typeof interval !== 'number' || interval < 30 || interval > 3600) + ) + errors.intervalSeconds = 'monitoring.errors.out_of_range'; + const timeoutMs = b.timeoutMs; + if ( + timeoutMs !== undefined && + (typeof timeoutMs !== 'number' || timeoutMs < 1000 || timeoutMs > 30000) + ) + errors.timeoutMs = 'monitoring.errors.out_of_range'; + if ( + typeof b.method === 'string' && + !/^(GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS)$/i.test(b.method) + ) + errors.method = 'monitoring.errors.invalid_method'; if (Object.keys(errors).length) return err(400, 'validation_failed', 'Invalid monitor', errors); const created = { diff --git a/test/monitoring.test.ts b/test/monitoring.test.ts new file mode 100644 index 0000000..54c79b0 --- /dev/null +++ b/test/monitoring.test.ts @@ -0,0 +1,336 @@ +import { Client } from '@modelcontextprotocol/sdk/client/index.js'; +import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'; +import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'; +import { IDS, startFakeApi, VALID_TOKEN, type FakeApi } from './fake-api.js'; +import { startMcp, type TestMcp } from './helpers.js'; +import { deriveMonitorName } from '../src/tools/monitoring.js'; + +let api: FakeApi; +let mcp: TestMcp; +let client: Client; +beforeAll(async () => { + api = await startFakeApi(); + mcp = await startMcp(api); + client = new Client({ name: 'test', version: '1' }); + await client.connect( + new StreamableHTTPClientTransport(new URL(`${mcp.url}/mcp`), { + requestInit: { headers: { Authorization: `Bearer ${VALID_TOKEN}` } }, + }), + ); +}); +afterAll(async () => { + await client.close(); + await mcp.close(); + await api.close(); +}); +beforeEach(() => { + api.reset(); +}); + +type Data = Record; // eslint-disable-line @typescript-eslint/no-explicit-any + +const call = async (name: string, args: Record) => { + const r = await client.callTool({ name, arguments: args }); + return { + isError: Boolean(r.isError), + text: (r.content as { text: string }[])[0]!.text, + data: r.structuredContent as Data | undefined, + }; +}; +const failOnCreate = (f: { status: number; code: string; errors?: Record }) => + api.route('POST', /^\/api\/monitoring\/monitors$/, () => ({ + status: f.status, + body: { error: 'x', code: f.code, ...(f.errors ? { errors: f.errors } : {}) }, + })); +const posts = () => api.requests.filter((r) => r.method === 'POST'); + +describe('monitoring tools: listing', () => { + it('has the right annotations', async () => { + const { tools } = await client.listTools(); + const by = (n: string) => tools.find((t) => t.name === n)!; + for (const n of ['get_monitoring_status', 'list_monitors', 'get_monitor']) { + expect(by(n).annotations?.readOnlyHint).toBe(true); + } + expect(by('create_monitor').annotations).toMatchObject({ + readOnlyHint: false, + destructiveHint: false, + idempotentHint: false, + openWorldHint: false, + }); + expect(by('test_monitor').annotations).toMatchObject({ + readOnlyHint: false, + destructiveHint: false, + idempotentHint: true, + }); + const props = Object.keys( + (by('create_monitor').inputSchema as { properties: Record }).properties, + ); + expect(props).toEqual( + expect.arrayContaining([ + 'project', + 'url', + 'name', + 'method', + 'interval', + 'timeout', + 'expected_status', + 'service', + ]), + ); + expect(props).not.toContain('headers'); + expect(props).not.toContain('body'); + }); +}); + +describe('get_monitoring_status', () => { + it('summarises a project', async () => { + const r = await call('get_monitoring_status', { project: 'acme/billing' }); + expect(r.isError).toBe(false); + expect(r.text).toMatch( + /^acme\/billing: 0 up, 1 down \(billing-api desde hace .+: HTTP 503\) · 0 degradados/, + ); + expect(r.data).toMatchObject({ down: 1, total: 1 }); + expect( + api.requests.some((q) => + q.path.startsWith(`/api/monitoring/status?projectId=${IDS.acmeBilling}`), + ), + ).toBe(true); + }); + + it('summarises a service by filtering the monitors', async () => { + const r = await call('get_monitoring_status', { service: 'acme/billing/billing-api' }); + expect(r.isError).toBe(false); + expect(r.text).toContain('acme/billing/billing-api: 0 up, 1 down (billing-api desde hace'); + expect( + api.requests.some( + (q) => + q.path.includes(`/api/monitoring/monitors?`) && + q.path.includes(`serviceId=${IDS.svcBillingApi}`), + ), + ).toBe(true); + }); + + it('service without monitors', async () => { + const r = await call('get_monitoring_status', { service: 'acme/billing/billing-worker' }); + expect(r.text).toContain('no hay monitores'); + }); + + it('requires exactly one of project or service', async () => { + const none = await call('get_monitoring_status', {}); + expect(none.isError).toBe(true); + expect(none.text).toMatch(/project.*service/); + const both = await call('get_monitoring_status', { + project: 'acme/billing', + service: 'acme/billing/billing-api', + }); + expect(both.isError).toBe(true); + expect(both.text).toMatch(/solo uno/); + expect(api.requests.filter((q) => q.path.includes('/monitoring/'))).toHaveLength(0); + }); + + it('module_disabled gives an actionable message', async () => { + const r = await call('get_monitoring_status', { project: 'globex/billing' }); + expect(r.isError).toBe(true); + expect(r.text).toBe( + 'Monitoring no está activado en este proyecto; actívalo en Ajustes del proyecto.', + ); + }); +}); + +describe('list_monitors / get_monitor', () => { + it('lists the monitors of a project', async () => { + const r = await call('list_monitors', { project: 'acme/web' }); + expect(r.text).toContain('1 monitor en acme/web: web (up, uptime 24h 100%)'); + expect(r.data?.monitors).toHaveLength(1); + expect(r.data?.nextCursor).toBeNull(); + }); + + it('filters by service', async () => { + const r = await call('list_monitors', { + project: 'acme/billing', + service: 'acme/billing/billing-api', + }); + expect(r.data?.monitors).toHaveLength(1); + const none = await call('list_monitors', { + project: 'acme/billing', + service: 'acme/billing/billing-worker', + }); + expect(none.text).toContain('No hay monitores'); + const wrong = await call('list_monitors', { + project: 'acme/web', + service: 'acme/billing/billing-api', + }); + expect(wrong.isError).toBe(true); + }); + + it('gets a monitor with uptime percentages and the open incident', async () => { + const r = await call('get_monitor', { id: IDS.monBillingApi }); + expect(r.isError).toBe(false); + expect(r.text).toContain('uptime 24h 91.5% · 7d 99.9% · 30d 99.95%'); + expect(r.text).toContain('incidente abierto (down) desde hace'); + expect(r.data?.openIncident?.cause).toBe('HTTP 503'); + }); + + it('never exposes header values or body, only names/flags', async () => { + const m = api.db.monitors[1]!; + Object.assign(m, { hasHeaders: true, headerNames: ['Authorization'], hasBody: true }); + Object.assign(m, { + headers: [{ name: 'Authorization', value: 'SECRET-VALUE' }], + body: 'SECRET-BODY', + }); + const r = await call('get_monitor', { id: m.id }); + expect(r.text).toContain('cabeceras: Authorization (valores ocultos)'); + expect(r.text).not.toContain('SECRET'); + expect(JSON.stringify(r.data)).not.toContain('SECRET'); + Object.assign(m, { hasHeaders: false, headerNames: [], hasBody: false }); + }); + + it('404 is readable', async () => { + const r = await call('get_monitor', { id: 'nope' }); + expect(r.isError).toBe(true); + expect(r.text).toMatch(/No encontrado/); + }); +}); + +describe('create_monitor', () => { + it('maps inputs to the API field names', async () => { + const r = await call('create_monitor', { + project: 'acme/billing', + url: 'https://api.acme.com/health/', + method: 'HEAD', + interval: 120, + timeout: 5, + expected_status: '200-299', + service: 'acme/billing/billing-worker', + }); + expect(r.isError).toBe(false); + expect(r.text).toContain( + 'Monitor creado: api.acme.com/health (HEAD https://api.acme.com/health/ cada 120 s) en acme/billing.', + ); + expect(r.text).toContain('Empezará a chequearse en breve'); + expect(r.text).toContain(r.data!.id); + expect(posts()).toHaveLength(1); + expect(posts()[0]!.body).toEqual({ + projectId: IDS.acmeBilling, + name: 'api.acme.com/health', + url: 'https://api.acme.com/health/', + method: 'HEAD', + serviceId: IDS.svcBillingWorker, + intervalSeconds: 120, + timeoutMs: 5000, + expectedStatus: '200-299', + }); + }); + + it('uses the given name and omits unset optionals', async () => { + await call('create_monitor', { + project: 'acme/web', + url: 'https://web.acme.com', + name: 'home', + }); + expect(posts()[0]!.body).toEqual({ + projectId: IDS.acmeWeb, + name: 'home', + url: 'https://web.acme.com', + }); + }); + + it('never forwards headers or body, even if the client sends them', async () => { + const r = await call('create_monitor', { + project: 'acme/web', + url: 'https://web.acme.com/x', + headers: [{ name: 'Authorization', value: 'SECRET' }], + body: 'SECRET', + }); + if (!r.isError) { + expect(posts()).toHaveLength(1); + expect(Object.keys(posts()[0]!.body as object)).not.toEqual( + expect.arrayContaining(['headers']), + ); + } + for (const p of posts()) { + expect(JSON.stringify(p.body)).not.toContain('SECRET'); + expect(p.body).not.toHaveProperty('headers'); + expect(p.body).not.toHaveProperty('body'); + } + }); + + it('translates per-field validation errors to input names', async () => { + const r = await call('create_monitor', { + project: 'acme/billing', + url: 'ftp://nope', + interval: 5, + timeout: 99, + method: 'FETCH', + }); + expect(r.isError).toBe(true); + expect(r.text).toContain('url: debe ser una URL http o https válida'); + expect(r.text).toContain('interval: fuera de rango; el intervalo va de 30 a 3600 segundos'); + expect(r.text).toContain('timeout: fuera de rango; el timeout va de 1 a 30 segundos'); + expect(r.text).toContain('method: método HTTP no válido'); + expect(r.text).not.toContain('intervalSeconds'); + expect(r.text).not.toContain('monitoring.errors'); + }); + + it('explains other known codes and unknown ones', async () => { + failOnCreate({ + status: 400, + code: 'validation_failed', + errors: { + expectedStatus: 'monitoring.errors.invalid_expected_status', + serviceId: 'monitoring.errors.service_not_found', + name: 'monitoring.errors.weird_code', + }, + }); + const r = await call('create_monitor', { project: 'acme/web', url: 'https://web.acme.com' }); + expect(r.text).toContain('expected_status: usa códigos HTTP 100-599'); + expect(r.text).toContain('service: el servicio no existe en este proyecto'); + expect(r.text).toContain('name: no válido (weird_code)'); + }); + + it('module_disabled', async () => { + const r = await call('create_monitor', { + project: 'globex/billing', + url: 'https://x.example.com', + }); + expect(r.isError).toBe(true); + expect(r.text).toContain('Monitoring no está activado en este proyecto'); + }); + + it('mcp_monitor_secrets_not_allowed explains v1', async () => { + failOnCreate({ status: 400, code: 'mcp_monitor_secrets_not_allowed' }); + const r = await call('create_monitor', { project: 'acme/web', url: 'https://web.acme.com' }); + expect(r.isError).toBe(true); + expect(r.text).toMatch(/no admite cabeceras ni body/); + }); +}); + +describe('test_monitor', () => { + it('runs the check and sends a JSON body', async () => { + const r = await call('test_monitor', { id: IDS.monWeb }); + expect(r.isError).toBe(false); + expect(r.text).toContain('Chequeo de prueba: up · HTTP 200 · 42 ms'); + expect(r.data).toMatchObject({ status: 'up', httpStatus: 200, latencyMs: 42 }); + expect(posts()[0]).toMatchObject({ + path: `/api/monitoring/monitors/${IDS.monWeb}/test`, + contentType: expect.stringContaining('application/json'), + body: {}, + }); + }); + + it('down result and 404', async () => { + expect((await call('test_monitor', { id: IDS.monBillingApi })).text).toContain( + 'down · HTTP 503', + ); + const r = await call('test_monitor', { id: 'nope' }); + expect(r.isError).toBe(true); + }); +}); + +describe('deriveMonitorName', () => { + it('uses host and path', () => { + expect(deriveMonitorName('https://api.acme.com/v1/health')).toBe('api.acme.com/v1/health'); + expect(deriveMonitorName('https://acme.com/')).toBe('acme.com'); + expect(deriveMonitorName('nonsense')).toBe('nonsense'); + }); +});