diff --git a/.github/workflows/e2e.yaml b/.github/workflows/e2e.yaml index 68a9ea58752..e21c8374ce6 100644 --- a/.github/workflows/e2e.yaml +++ b/.github/workflows/e2e.yaml @@ -996,7 +996,13 @@ jobs: fi export OPENSHELL_BIN "$OPENSHELL_BIN" --version - npx tsx tools/e2e/live-vitest-invocation.mts run --test-path test/e2e/live/mcp-bridge.test.ts + case "$NEMOCLAW_MCP_BRIDGE_AGENT" in + openclaw) mcp_test_selector='^mcp-bridge$' ;; + hermes) mcp_test_selector='^mcp-bridge-hermes$' ;; + deepagents) mcp_test_selector='^mcp-bridge-deepagents$' ;; + *) echo "::error::Unsupported MCP bridge agent: $NEMOCLAW_MCP_BRIDGE_AGENT" >&2; exit 1 ;; + esac + npx tsx tools/e2e/live-vitest-invocation.mts run --test-path test/e2e/live/mcp-bridge.test.ts --selector "$mcp_test_selector" if [[ "$NEMOCLAW_MCP_BRIDGE_AGENT" == "deepagents" ]]; then npx vitest run --project e2e-live \ test/e2e/live/openshell-credential-generation-window.test.ts \ @@ -1124,7 +1130,13 @@ jobs: fi export OPENSHELL_BIN "$OPENSHELL_BIN" --version - npx tsx tools/e2e/live-vitest-invocation.mts run --test-path test/e2e/live/mcp-bridge.test.ts + case "$NEMOCLAW_MCP_BRIDGE_AGENT" in + openclaw) mcp_test_selector='^mcp-bridge$' ;; + hermes) mcp_test_selector='^mcp-bridge-hermes$' ;; + deepagents) mcp_test_selector='^mcp-bridge-deepagents$' ;; + *) echo "::error::Unsupported MCP bridge agent: $NEMOCLAW_MCP_BRIDGE_AGENT" >&2; exit 1 ;; + esac + npx tsx tools/e2e/live-vitest-invocation.mts run --test-path test/e2e/live/mcp-bridge.test.ts --selector "$mcp_test_selector" - id: mcp_artifact_secret_scan name: Scan MCP artifacts for fixture credentials diff --git a/Dockerfile b/Dockerfile index 47b4769c6d9..bc68e3d19d7 100644 --- a/Dockerfile +++ b/Dockerfile @@ -10,6 +10,7 @@ # Global ARG — must be declared before the first FROM to be visible # to all FROM directives. Can be overridden via --build-arg. ARG BASE_IMAGE=ghcr.io/nvidia/nemoclaw/sandbox-base:latest +ARG NEMOCLAW_CORPORATE_CA_B64= # Stage 1: Build TypeScript plugin from source FROM node:22-trixie-slim@sha256:e6d9a389d34ff9678438af985c9913fbd1eb6ed36e80fea56644f4b4f6dd70ba AS builder @@ -38,6 +39,20 @@ COPY src/lib/messaging/channels/ /opt/nemoclaw-root/src/lib/messaging/channels/ RUN ln -s /opt/nemoclaw/node_modules /opt/nemoclaw-root/node_modules \ && /opt/nemoclaw/node_modules/.bin/tsc -p tsconfig.runtime-preloads.json +# Build the agent-neutral, names-only MCP diagnostic once from a committed +# production lock. The final image copies only the bundled runtime, not its +# build-time dependency tree. +FROM node:22-trixie-slim@sha256:e6d9a389d34ff9678438af985c9913fbd1eb6ed36e80fea56644f4b4f6dd70ba AS mcp-tool-discovery-runtime +ARG NEMOCLAW_CORPORATE_CA_B64 +ENV AWS_EC2_METADATA_DISABLED=true \ + NPM_CONFIG_AUDIT=false \ + NPM_CONFIG_FUND=false \ + NPM_CONFIG_UPDATE_NOTIFIER=false +WORKDIR /opt/mcp-tool-discovery-runtime +COPY tools/mcp-tool-discovery-runtime/package.json tools/mcp-tool-discovery-runtime/package-lock.json tools/mcp-tool-discovery-runtime/tsconfig.json tools/mcp-tool-discovery-runtime/install-reviewed-runtime.sh tools/mcp-tool-discovery-runtime/*.ts ./ +RUN ./install-reviewed-runtime.sh \ + && rm -f ./install-reviewed-runtime.sh + # Group repository-owned files outside the final image so BuildKit can collapse # related payloads without invalidating earlier final-image work. FROM scratch AS openclaw-dependency-payload @@ -90,17 +105,23 @@ COPY scripts/validate-openclaw-tool-search.mts /scripts/validate-openclaw-tool-s COPY src/lib/tool-disclosure.ts /src/lib/tool-disclosure.ts COPY src/lib/messaging/ /src/lib/messaging/ COPY nemoclaw-blueprint/openclaw-plugins/ /usr/local/share/nemoclaw/openclaw-plugins/ +COPY --from=mcp-tool-discovery-runtime /opt/mcp-tool-discovery-runtime/dist/ /usr/local/lib/nemoclaw/mcp-tool-discovery-runtime/ # Stage 3: Runtime image — pull cached base from GHCR # hadolint ignore=DL3006 FROM ${BASE_IMAGE} ARG BASE_IMAGE +# OpenShell blocks the link-local EC2 Instance Metadata Service. Keep AWS SDK +# credential chains from attempting an impossible metadata discovery path. +ENV AWS_EC2_METADATA_DISABLED=true + # Upgrade the final runtime even when an install or rebuild starts from a # published sandbox base with Node 22.22.2. OpenClaw 2026.7.1 requires the # SQLite WAL fix in Node 22.22.3 or newer. The trusted managed-image staging # path removes this one instruction when it has just built Dockerfile.base from # the same Node image, avoiding a redundant 125 MB layer in that local-only case. COPY --from=builder /usr/local/bin/node /usr/local/bin/node + # Dependency review evidence for this runtime pin lives in # docs/security/openclaw-2026.7.1-dependency-review.md. ARG OPENCLAW_VERSION=2026.7.1 @@ -125,10 +146,6 @@ ARG MCPORTER_VERSION=0.7.3 ARG MCPORTER_0_7_3_INTEGRITY=sha512-egoPVYqTnWb3NjRIxo+xc8OrAI0dlPrJm9pAiZx0pImuNIV5rKhGtTnIfH/Y1ldGPVu74ibj3KR5c9U/QSdQFA== ARG MCPORTER_0_7_3_TARBALL=https://registry.npmjs.org/mcporter/-/mcporter-0.7.3.tgz -# OpenShell blocks the link-local EC2 Instance Metadata Service. Keep AWS SDK -# credential chains from attempting an impossible metadata discovery path. -ENV AWS_EC2_METADATA_DISABLED=true - RUN --mount=type=bind,from=openclaw-dependency-payload,source=/,target=/run/nemoclaw-payload \ /bin/bash -euo pipefail -c ' \ payload_metadata_before="$(stat -c "%u:%g:%a:%n" / /usr /usr/local /usr/local/lib)"; \ @@ -155,7 +172,7 @@ ENV JITI_FS_CACHE=false # here; the RUN below decodes it to a root-owned file that the entrypoint # appends to the OpenShell trust bundle at runtime. The CA is a public # certificate, not a secret, so baking it into an image layer is acceptable. -ARG NEMOCLAW_CORPORATE_CA_B64= +ARG NEMOCLAW_CORPORATE_CA_B64 # Decode the host corporate-proxy CA (#6210) to a root-owned, read-only file # when onboard baked one in. No-op when NEMOCLAW_CORPORATE_CA_B64 is empty. The @@ -938,7 +955,11 @@ RUN --mount=type=bind,from=openclaw-runtime-payload,source=/,target=/run/nemocla stat -c "%u:%g:%a:%n" / /usr /usr/local /usr/local/bin /usr/local/lib /usr/local/lib/nemoclaw /usr/local/share /usr/local/share/nemoclaw /scripts \ )"; \ [[ "$payload_metadata_before" == "$payload_metadata_after" ]] \ - || { echo "ERROR: runtime payload changed parent directory ownership or mode" >&2; exit 1; } \ + || { echo "ERROR: runtime payload changed parent directory ownership or mode" >&2; exit 1; }; \ + discovery_contract="$(node /usr/local/lib/nemoclaw/mcp-tool-discovery-runtime/mcp-tool-discovery.mjs)" \ + && node -e "const result = JSON.parse(process.argv[1]); if (result.protocol !== 1 || result.ok !== false || result.detail !== \"tool discovery received invalid runtime arguments\") process.exit(1);" "$discovery_contract" \ + && discovery_unsafe="$(find -L /usr/local/lib/nemoclaw/mcp-tool-discovery-runtime \( ! -user root -o -perm /022 \) -print -quit)" \ + && test -z "$discovery_unsafe" \ ' # Copy startup script and shared sandbox initialisation library diff --git a/agents/hermes/Dockerfile b/agents/hermes/Dockerfile index c7d67d7a909..7d8de600ed5 100644 --- a/agents/hermes/Dockerfile +++ b/agents/hermes/Dockerfile @@ -7,6 +7,19 @@ # pre-built Hermes base image. Mirrors the OpenClaw Dockerfile structure. ARG BASE_IMAGE=ghcr.io/nvidia/nemoclaw/hermes-sandbox-base@sha256:fa05221f5c7bcafea7e263c84e5d06f87e37d1ccb78dc28c113f1a4066aa544c +ARG NEMOCLAW_CORPORATE_CA_B64= + +FROM node:22-trixie-slim@sha256:e6d9a389d34ff9678438af985c9913fbd1eb6ed36e80fea56644f4b4f6dd70ba AS mcp-tool-discovery-runtime +ARG NEMOCLAW_CORPORATE_CA_B64 +ENV NPM_CONFIG_AUDIT=false \ + NPM_CONFIG_FUND=false \ + NPM_CONFIG_UPDATE_NOTIFIER=false +WORKDIR /opt/mcp-tool-discovery-runtime +COPY tools/mcp-tool-discovery-runtime/package.json tools/mcp-tool-discovery-runtime/package-lock.json tools/mcp-tool-discovery-runtime/tsconfig.json tools/mcp-tool-discovery-runtime/install-reviewed-runtime.sh tools/mcp-tool-discovery-runtime/*.ts ./ +RUN ./install-reviewed-runtime.sh \ + && rm -f ./install-reviewed-runtime.sh +RUN chown -R root:root /opt/mcp-tool-discovery-runtime \ + && chmod -R a=rX /opt/mcp-tool-discovery-runtime # Group repository-owned files outside the final image so BuildKit can collapse # related files without invalidating earlier final-image work. @@ -27,6 +40,7 @@ COPY scripts/lib/openclaw-npm-remediation.mts /scripts/lib/openclaw-npm-remediat FROM scratch AS hermes-runtime-payload +COPY --from=mcp-tool-discovery-runtime /opt/mcp-tool-discovery-runtime/dist/ /usr/local/lib/nemoclaw/mcp-tool-discovery-runtime/ COPY nemoclaw-blueprint/ /opt/nemoclaw-blueprint/ COPY scripts/lib/sandbox-init.sh /usr/local/lib/nemoclaw/sandbox-init.sh COPY scripts/lib/gateway-supervisor.sh /usr/local/lib/nemoclaw/gateway-supervisor.sh @@ -197,6 +211,11 @@ RUN --mount=type=bind,from=hermes-runtime-payload,source=/,target=/run/nemoclaw- || { echo "ERROR: runtime payload changed parent directory ownership or mode" >&2; exit 1; } \ ' +RUN discovery_contract="$(node /usr/local/lib/nemoclaw/mcp-tool-discovery-runtime/mcp-tool-discovery.mjs)" \ + && node -e 'const result = JSON.parse(process.argv[1]); if (result.protocol !== 1 || result.ok !== false || result.detail !== "tool discovery received invalid runtime arguments") process.exit(1);' "$discovery_contract" \ + && discovery_unsafe="$(find -L /usr/local/lib/nemoclaw/mcp-tool-discovery-runtime \( ! -user root -o -perm /022 \) -print -quit)" \ + && test -z "$discovery_unsafe" + # Ensure sandbox user can read blueprint files copied as root RUN chmod -R a+rX /opt/nemoclaw-blueprint/ @@ -414,7 +433,7 @@ ARG NEMOCLAW_DARWIN_VM_COMPAT=0 # here; the RUN below decodes it to a root-owned file that the entrypoint # appends to the OpenShell trust bundle at runtime. The CA is a public # certificate, not a secret, so baking it into an image layer is acceptable. -ARG NEMOCLAW_CORPORATE_CA_B64= +ARG NEMOCLAW_CORPORATE_CA_B64 # Total model context window (input + output tokens). Empty by default so # Hermes auto-detects from the endpoint's /v1/models max_model_len; onboard # rewrites this ARG (via dockerfile-patch) when it probes a runtime value or diff --git a/agents/langchain-deepagents-code/Dockerfile b/agents/langchain-deepagents-code/Dockerfile index 5f9ca9a9748..04214c4a77d 100644 --- a/agents/langchain-deepagents-code/Dockerfile +++ b/agents/langchain-deepagents-code/Dockerfile @@ -6,10 +6,29 @@ # NemoClaw staging supplies a resolved base image reference. Direct Docker builds # must pass --build-arg BASE_IMAGE=... rather than falling back to a mutable tag. ARG BASE_IMAGE +ARG NEMOCLAW_CORPORATE_CA_B64= + +FROM node:22-trixie-slim@sha256:e6d9a389d34ff9678438af985c9913fbd1eb6ed36e80fea56644f4b4f6dd70ba AS mcp-tool-discovery-runtime +ARG NEMOCLAW_CORPORATE_CA_B64 +ENV NPM_CONFIG_AUDIT=false \ + NPM_CONFIG_FUND=false \ + NPM_CONFIG_UPDATE_NOTIFIER=false +WORKDIR /opt/mcp-tool-discovery-runtime +COPY tools/mcp-tool-discovery-runtime/package.json tools/mcp-tool-discovery-runtime/package-lock.json tools/mcp-tool-discovery-runtime/tsconfig.json tools/mcp-tool-discovery-runtime/install-reviewed-runtime.sh tools/mcp-tool-discovery-runtime/*.ts ./ +RUN ./install-reviewed-runtime.sh \ + && rm -f ./install-reviewed-runtime.sh +RUN chown -R root:root /opt/mcp-tool-discovery-runtime \ + && chmod -R a=rX /opt/mcp-tool-discovery-runtime # hadolint ignore=DL3006 FROM ${BASE_IMAGE} +COPY --from=mcp-tool-discovery-runtime /opt/mcp-tool-discovery-runtime/dist/ /usr/local/lib/nemoclaw/mcp-tool-discovery-runtime/ +RUN discovery_contract="$(node /usr/local/lib/nemoclaw/mcp-tool-discovery-runtime/mcp-tool-discovery.mjs)" \ + && node -e 'const result = JSON.parse(process.argv[1]); if (result.protocol !== 1 || result.ok !== false || result.detail !== "tool discovery received invalid runtime arguments") process.exit(1);' "$discovery_contract" \ + && discovery_unsafe="$(find -L /usr/local/lib/nemoclaw/mcp-tool-discovery-runtime \( ! -user root -o -perm /022 \) -print -quit)" \ + && test -z "$discovery_unsafe" + USER root COPY scripts/lib/reviewed-npm-archive.mts /scripts/lib/reviewed-npm-archive.mts diff --git a/docs/manage-sandboxes/manage-mcp-servers.mdx b/docs/manage-sandboxes/manage-mcp-servers.mdx index f8a07a20edc..a51646f9545 100644 --- a/docs/manage-sandboxes/manage-mcp-servers.mdx +++ b/docs/manage-sandboxes/manage-mcp-servers.mdx @@ -3,9 +3,9 @@ # SPDX-License-Identifier: Apache-2.0 title: "Manage MCP Servers" sidebar-title: "Manage MCP Servers" -description: "Inspect, probe, rotate, restart, remove, rebuild, and destroy NemoClaw-managed MCP servers." -description-agent: "Explains managed MCP status and credential-resolution probes, credential rotation, restart, removal, rebuild restoration, destroy recovery, and lifecycle locking. Use after an MCP server is registered." -keywords: ["nemoclaw mcp status", "nemoclaw mcp restart", "nemoclaw mcp remove", "mcp credential rotation"] +description: "Inspect advertised tools, probe, rotate, restart, remove, rebuild, and destroy NemoClaw-managed MCP servers." +description-agent: "Explains managed MCP status, advertised tool discovery, credential-resolution probes, credential rotation, restart, removal, rebuild restoration, destroy recovery, and lifecycle locking. Use after an MCP server is registered." +keywords: ["nemoclaw mcp status", "mcp tool discovery", "nemoclaw mcp restart", "nemoclaw mcp remove", "mcp credential rotation"] content: type: "how_to" skill: @@ -29,6 +29,54 @@ The `env.missing` field lists recorded host variable names that are currently un An existing valid provider can remain ready when a host variable is unset because OpenShell retains the credential. The JSON value `support.mode: "bridge"` identifies the agent's config-adapter capability, not a host-side traffic bridge. +## Discover Advertised Tools + +Pass `--tools` with one server name to request the server's advertised tool names: + +```bash +$$nemoclaw my-sandbox mcp status github --tools +$$nemoclaw my-sandbox mcp status github --tools --json +``` + +The shared discovery runtime uses the managed registration's existing OpenShell credential provider and generated policy. +OpenShell injects the credential at the policy boundary; it is not passed to the runtime through arguments, environment values, or an authorization option. +The same runtime and thin adapter ancestry are used across OpenClaw, Hermes, and LangChain Deep Agents Code sandboxes. + +Run discovery only against a configured endpoint you trust to advertise names while authenticated. +The endpoint controls every returned tool name and can derive those names from the request or credential it receives; NemoClaw validates and bounds the returned text but cannot prove that an authenticated endpoint did not encode credential-derived data in an otherwise valid name. + +A discovery result is a point-in-time list from the configured MCP server, not an attestation of the exact tools visible to the model in an active agent session. +Agent configuration, progressive disclosure, runtime filters, and session state can further limit model-visible tools. + +NemoClaw runs the standard MCP `initialize`, `notifications/initialized`, and paginated `tools/list` lifecycle. +It retains and returns tool names only, never prints the other tool-definition fields returned by `tools/list`, and never calls a tool. +The client bounds total time, per-request time, cumulative response bytes, pages, tool count, cursor length, and tool-name length. +It attempts to close the MCP session and transport on both success and failure. +Cleanup errors do not replace the bounded discovery result. + +JSON output adds a per-server `toolDiscovery` object without changing the existing status fields: + +```json +{ + "toolDiscovery": { + "ok": true, + "count": 2, + "tools": ["createJiraIssue", "getJiraIssue"], + "truncated": false + } +} +``` + +Discovery is opt-in and sends authenticated network traffic to the configured endpoint. +`--tools` requires one server name and suppresses the named-server credential-resolution probe that would otherwise run by default. +Pass `--probe --tools` when you intentionally want both live checks. + +An older sandbox image that does not contain the shared discovery client reports that a rebuild is required. +Run `$$nemoclaw my-sandbox rebuild` and retry the command. + +A discovery failure sets `toolDiscovery.ok` to `false` and leaves the ordinary provider, policy, environment, and adapter status available. +Bounded partial results set `truncated` to `true` and include a redacted `detail` value. + ## Verify Credential Resolution Provider presence and metadata cannot prove that OpenShell rewrites `openshell:resolve:env:KEY` when a request leaves the sandbox. diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index dec5a606516..31741250507 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -2115,8 +2115,27 @@ Identical HTTP 400, 401, or 403 rejections raise a warning that names the hypoth For HTTP 401 or 403, a confirmed-valid credential means the host is not rewriting placeholders and agent runtimes receive the same auth failure and skip the server; HTTP 400 remains inconclusive because the endpoint may reject the probe request itself. Every other outcome — differing rejections (an endpoint may reject two different literal bearers differently), endpoints that skip authentication, endpoint outages, policy denials, and unreachable sandboxes — reports as `unknown` rather than blaming the credential rewrite, and a persisted URL that fails the current authenticated-endpoint boundary is never probed. +Pass `--tools` with one server name to request a live tool inventory. +The shared client runs through the managed registration's existing OpenShell credential provider and policy; OpenShell injects the credential at that boundary, and the runtime never accepts it as an argument, environment value, or authorization option. +It performs `initialize`, `notifications/initialized`, and paginated `tools/list`, then attempts to close the MCP session and transport. +Cleanup errors do not replace the bounded discovery result. +It retains and returns deterministic tool names only, never prints the other tool-definition fields returned by `tools/list`, and never calls a tool. +The operation is bounded by total and per-request timeouts plus response-byte, page, tool-count, cursor-length, and tool-name limits. + +Use `--tools` only with a configured endpoint you trust to advertise names while authenticated. +The endpoint controls its returned names and can derive them from the request or credential it receives; NemoClaw validates and bounds the text but cannot prove that the endpoint did not encode credential-derived data in an otherwise valid name. + +The `toolDiscovery` JSON field contains `ok`, `count`, `tools`, and `truncated`, plus a redacted `detail` on failure or a bounded partial result. +These names are the server's point-in-time advertised tools, not an attestation of the exact tools visible to the model after agent filters, progressive disclosure, or session state. +An older sandbox image without the shared client reports that the sandbox must be rebuilt. + +Tool discovery is opt-in and sends authenticated network traffic to the configured endpoint. +Passing `--tools` suppresses the named-server credential-resolution probe that otherwise runs by default. +Pass `--probe --tools` to request both checks explicitly. +An unsuccessful discovery does not remove the ordinary provider, policy, environment, or adapter status from the result. + ```bash -$$nemoclaw my-assistant mcp status [server] [--json] [--probe|--no-probe] +$$nemoclaw my-assistant mcp status [server] [--json] [--probe|--no-probe] [--tools] ``` | Flag | Description | @@ -2124,6 +2143,7 @@ $$nemoclaw my-assistant mcp status [server] [--json] [--probe|--no-probe] | `--json` | Emit status as JSON without credential values | | `--probe` | Request the wire-level credential-resolution probe for every listed server; entries that fail readiness checks are skipped | | `--no-probe` | Skip the probe; it defaults on only when a single server is named | +| `--tools` | Request advertised tool names from one trusted configured endpoint through its managed credential provider; suppresses the implicit credential probe unless `--probe` is also passed | ### `$$nemoclaw mcp restart` diff --git a/scripts/check-dcode-profile-import-gate.sh b/scripts/check-dcode-profile-import-gate.sh index 2e9b3cc76f5..b65b31b8be9 100755 --- a/scripts/check-dcode-profile-import-gate.sh +++ b/scripts/check-dcode-profile-import-gate.sh @@ -29,15 +29,16 @@ cd "${repo_root}" # agents/langchain-deepagents-code/Dockerfile.base, # test/Dockerfile.dcode-profile-missing-dependencies, and # agents/langchain-deepagents-code/Dockerfile. Those three reviewed Dockerfiles -# contain no secret-bearing ARGs. Only BASE_IMAGE is passed via --build-arg, -# always as a public, non-secret image reference. +# contain no secret-bearing ARGs. NEMOCLAW_CORPORATE_CA_B64 carries public trust +# anchors and is not passed to this gate. Only BASE_IMAGE is passed via +# --build-arg, always as a public, non-secret image reference. for dockerfile in \ agents/langchain-deepagents-code/Dockerfile.base \ test/Dockerfile.dcode-profile-missing-dependencies \ agents/langchain-deepagents-code/Dockerfile; do while IFS= read -r arg_name; do case "${arg_name}" in - BASE_IMAGE | NEMOCLAW_MODEL | NEMOCLAW_INFERENCE_PROVIDER_ID | NEMOCLAW_PROVIDER_KEY | NEMOCLAW_UPSTREAM_PROVIDER | NEMOCLAW_UPSTREAM_ENDPOINT_URL | NEMOCLAW_INFERENCE_BASE_URL | NEMOCLAW_INFERENCE_API | NEMOCLAW_TOOL_DISCLOSURE | NEMOCLAW_DCODE_AUTO_APPROVAL | NEMOCLAW_BUILD_ID | NEMOCLAW_DARWIN_VM_COMPAT | NEMOCLAW_PROXY_HOST | NEMOCLAW_PROXY_PORT) ;; + BASE_IMAGE | NEMOCLAW_CORPORATE_CA_B64 | NEMOCLAW_MODEL | NEMOCLAW_INFERENCE_PROVIDER_ID | NEMOCLAW_PROVIDER_KEY | NEMOCLAW_UPSTREAM_PROVIDER | NEMOCLAW_UPSTREAM_ENDPOINT_URL | NEMOCLAW_INFERENCE_BASE_URL | NEMOCLAW_INFERENCE_API | NEMOCLAW_TOOL_DISCLOSURE | NEMOCLAW_DCODE_AUTO_APPROVAL | NEMOCLAW_BUILD_ID | NEMOCLAW_DARWIN_VM_COMPAT | NEMOCLAW_PROXY_HOST | NEMOCLAW_PROXY_PORT) ;; *) echo "ERROR: plain-progress build refuses unreviewed ARG ${arg_name} in ${dockerfile}" >&2 exit 1 diff --git a/src/lib/actions/sandbox/mcp-bridge-contracts.ts b/src/lib/actions/sandbox/mcp-bridge-contracts.ts index 01d38063b2e..a19e5480de2 100644 --- a/src/lib/actions/sandbox/mcp-bridge-contracts.ts +++ b/src/lib/actions/sandbox/mcp-bridge-contracts.ts @@ -71,6 +71,14 @@ export interface McpBridgeStatus { registered: boolean | null; detail?: string; }; + /** Names advertised by the MCP endpoint when live discovery is requested. */ + toolDiscovery?: { + ok: boolean; + count: number; + tools: string[]; + truncated: boolean; + detail?: string; + }; addState?: "prepared" | "preflighted"; addedAt?: string; updatedAt?: string; diff --git a/src/lib/actions/sandbox/mcp-bridge-render.ts b/src/lib/actions/sandbox/mcp-bridge-render.ts index b565b2e80e8..1589d9e5068 100644 --- a/src/lib/actions/sandbox/mcp-bridge-render.ts +++ b/src/lib/actions/sandbox/mcp-bridge-render.ts @@ -90,6 +90,18 @@ export function renderMcpBridgeStatus( }`, ); } + const discovery = status.toolDiscovery; + if (discovery) { + console.log( + ` tool discovery: ${ + discovery.ok ? "successful" : `FAILED${discovery.detail ? ` (${discovery.detail})` : ""}` + }`, + ); + console.log( + ` tools discovered: ${discovery.count}${discovery.truncated ? " (partial)" : ""}`, + ); + for (const tool of discovery.tools) console.log(` - ${tool}`); + } for (const warning of status.warnings) console.log(` warning: ${warning}`); } console.log(""); diff --git a/src/lib/actions/sandbox/mcp-bridge-resolution-probe-security.test.ts b/src/lib/actions/sandbox/mcp-bridge-resolution-probe-security.test.ts index 09be5d55ac9..120a46d402a 100644 --- a/src/lib/actions/sandbox/mcp-bridge-resolution-probe-security.test.ts +++ b/src/lib/actions/sandbox/mcp-bridge-resolution-probe-security.test.ts @@ -85,8 +85,8 @@ describe("MCP credential-resolution probe command security", () => { buildCredentialResolutionProbeCommand(baseEntry, "deepagents-config")?.command ?? ""; expect(mcporter).toContain("nemoclaw-start node -e"); - expect(hermes).toContain("/opt/hermes/.venv/bin/python -c"); - expect(deepagents).toContain("/opt/venv/bin/python3 -c"); + expect(hermes).toContain("/opt/hermes/.venv/bin/python -I -c"); + expect(deepagents).toContain("/opt/venv/bin/python3 -I -c"); for (const command of [mcporter, hermes, deepagents]) { expect(command).toContain("'/dev/null'"); expect(command).not.toContain("head -c"); diff --git a/src/lib/actions/sandbox/mcp-bridge-resolution-probe.ts b/src/lib/actions/sandbox/mcp-bridge-resolution-probe.ts index caf40f3f34a..95eb4a17d86 100644 --- a/src/lib/actions/sandbox/mcp-bridge-resolution-probe.ts +++ b/src/lib/actions/sandbox/mcp-bridge-resolution-probe.ts @@ -49,7 +49,6 @@ */ import type { AgentMcpAdapter } from "../../agent/defs"; -import { shellQuote } from "../../core/shell-quote"; import type { McpBridgeEntry } from "../../state/registry"; import { authorizationValue } from "./mcp-bridge-adapter-status"; import { redactBridgeSecretsForDisplay } from "./mcp-bridge-output"; @@ -57,6 +56,10 @@ import { type CredentialResolutionProbeReadiness, credentialResolutionReadinessSkipDetail, } from "./mcp-bridge-resolution-readiness"; +import { + MCP_RUNTIME_SANITIZED_ENV_VARS, + wrapMcpRuntimeCommand, +} from "./mcp-bridge-runtime-command"; import { normalizeMcpServerUrl } from "./mcp-bridge-validation"; import { executeSandboxCommand, type SandboxCommandResult } from "./process-recovery"; import { @@ -90,13 +93,7 @@ const PROBE_CURL_MAX_TIME_SECONDS = 6; * first child process, so neither the adapter runtime nor curl inherits them * (same sanitize set nemoclaw-start uses for un-managed openclaw children). */ -export const PROBE_SANITIZED_ENV_VARS = [ - "OPENCLAW_GATEWAY_URL", - "OPENCLAW_GATEWAY_PORT", - "OPENCLAW_GATEWAY_TOKEN", - "OPENCLAW_ALLOW_INSECURE_PRIVATE_WS", - "NEMOCLAW_OPENCLAW_ALLOW_INSECURE_PRIVATE_WS", -] as const; +export const PROBE_SANITIZED_ENV_VARS = MCP_RUNTIME_SANITIZED_ENV_VARS; export interface CredentialResolutionProbe { /** @@ -151,28 +148,8 @@ const MCP_INITIALIZE_BODY = JSON.stringify({ * so the curl child must keep the adapter's runtime binary as an ancestor. * Same construction as the live E2E DNS-rebinding probe. */ -function runtimeWrappedCommand(adapter: AgentMcpAdapter, quotedCurl: string): string { - switch (adapter) { - case "mcporter": { - const runner = - 'const { spawnSync } = require("node:child_process"); const result = spawnSync(process.argv[1], process.argv.slice(2), { stdio: "inherit" }); process.exit(result.status ?? 1);'; - return `nemoclaw-start node -e ${shellQuote(runner)} ${quotedCurl}`; - } - case "hermes-config": { - const runner = - "import subprocess, sys; raise SystemExit(subprocess.run(sys.argv[1:], check=False).returncode)"; - return `/opt/hermes/.venv/bin/python -c ${shellQuote(runner)} ${quotedCurl}`; - } - case "deepagents-config": { - const runner = - "import subprocess, sys; raise SystemExit(subprocess.run(sys.argv[1:], check=False).returncode)"; - return `/opt/venv/bin/python3 -c ${shellQuote(runner)} ${quotedCurl}`; - } - } -} - -function quotedCurlCommand(url: string, authorization: string, httpMarker: string): string { - const curlArgs = [ +function curlCommand(url: string, authorization: string, httpMarker: string): string[] { + return [ "curl", "-sS", "--max-time", @@ -196,7 +173,6 @@ function quotedCurlCommand(url: string, authorization: string, httpMarker: strin "--data-binary", MCP_INITIALIZE_BODY, ]; - return curlArgs.map(shellQuote).join(" "); } export function buildCredentialResolutionProbeCommand( @@ -215,17 +191,17 @@ export function buildCredentialResolutionProbeCommand( } const resultMarker = createSandboxExecMarker(); const markers = probeOutputMarkers(resultMarker); - const placeholderCurl = quotedCurlCommand(entry.url, authorization, markers.placeholderHttp); - const controlCurl = quotedCurlCommand( + const placeholderCurl = curlCommand(entry.url, authorization, markers.placeholderHttp); + const controlCurl = curlCommand( entry.url, `Bearer ${MCP_PROBE_CONTROL_BEARER}`, markers.controlHttp, ); const probeBody = [ - runtimeWrappedCommand(adapter, placeholderCurl), + wrapMcpRuntimeCommand(adapter, placeholderCurl), "rc=$?", `printf '\\n${markers.placeholderExit}%s\\n' "$rc"`, - runtimeWrappedCommand(adapter, controlCurl), + wrapMcpRuntimeCommand(adapter, controlCurl), "crc=$?", `printf '\\n${markers.controlExit}%s\\n' "$crc"`, // Always exit 0 so a nonzero SSH status unambiguously means transport diff --git a/src/lib/actions/sandbox/mcp-bridge-runtime-command.ts b/src/lib/actions/sandbox/mcp-bridge-runtime-command.ts new file mode 100644 index 00000000000..a1f34bcc710 --- /dev/null +++ b/src/lib/actions/sandbox/mcp-bridge-runtime-command.ts @@ -0,0 +1,54 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import type { AgentMcpAdapter } from "../../agent/defs"; +import { shellQuote } from "../../core/shell-quote"; + +/** + * Variables sourced for sandbox proxy access that must not leak into a child + * diagnostic process. OpenShell injects the managed MCP credential at the + * policy boundary; the discovery runtime never accepts a credential or + * Authorization header as input. + */ +export const MCP_RUNTIME_SANITIZED_ENV_VARS = [ + "OPENCLAW_GATEWAY_URL", + "OPENCLAW_GATEWAY_PORT", + "OPENCLAW_GATEWAY_TOKEN", + "OPENCLAW_ALLOW_INSECURE_PRIVATE_WS", + "NEMOCLAW_OPENCLAW_ALLOW_INSECURE_PRIVATE_WS", +] as const; + +function unsupportedAdapter(adapter: never): never { + throw new Error(`Unsupported MCP adapter: ${String(adapter)}`); +} + +/** + * OpenShell binds generated MCP policies to the configured adapter executable + * and its process ancestry. Keep that runtime as the parent of a shared child + * command instead of implementing the wire operation separately per adapter. + */ +export function wrapMcpRuntimeCommand( + adapter: AgentMcpAdapter, + command: readonly string[], +): string { + const quotedCommand = command.map(shellQuote).join(" "); + switch (adapter) { + case "mcporter": { + const runner = + 'const { spawnSync } = require("node:child_process"); const result = spawnSync(process.argv[1], process.argv.slice(2), { stdio: "inherit" }); process.exit(result.status ?? 1);'; + return `nemoclaw-start node -e ${shellQuote(runner)} ${quotedCommand}`; + } + case "hermes-config": { + const runner = + "import subprocess, sys; raise SystemExit(subprocess.run(sys.argv[1:], check=False).returncode)"; + return `/opt/hermes/.venv/bin/python -I -c ${shellQuote(runner)} ${quotedCommand}`; + } + case "deepagents-config": { + const runner = + "import subprocess, sys; raise SystemExit(subprocess.run(sys.argv[1:], check=False).returncode)"; + return `/opt/venv/bin/python3 -I -c ${shellQuote(runner)} ${quotedCommand}`; + } + default: + return unsupportedAdapter(adapter); + } +} diff --git a/src/lib/actions/sandbox/mcp-bridge-status-resolution.test.ts b/src/lib/actions/sandbox/mcp-bridge-status-resolution.test.ts index 3543b0161cf..52e3689f1a4 100644 --- a/src/lib/actions/sandbox/mcp-bridge-status-resolution.test.ts +++ b/src/lib/actions/sandbox/mcp-bridge-status-resolution.test.ts @@ -44,9 +44,13 @@ gatewayRuntime.recoverNamedGatewayRuntime = async () => ({ after: { state: "healthy_named" }, }); let providerAttachmentState = "attached"; +let providerInspectionState = "present"; let providerCredentialKey = "GITHUB_TOKEN"; globalActions.runOpenshellProviderCommand = (args) => { if (args[0] === "provider" && args[1] === "get") { + if (providerInspectionState === "absent") { + return { status: 1, stdout: "", stderr: "provider not found" }; + } return { status: 0, stdout: "Id: 11111111-2222-4333-8444-555555555555\nType: generic\nResource version: 4\nCredential keys: " + providerCredentialKey + "\n", @@ -89,6 +93,21 @@ processRecovery.executeSandboxCommand = (sandboxName, command) => { stderr: "", }; } + if (command.includes("mcp-tool-discovery-runtime")) { + const resultMarker = command.match(/__NEMOCLAW_SANDBOX_EXEC_STARTED___[0-9a-f]{32}/)?.[0]; + if (!resultMarker) throw new Error("tool discovery result marker missing"); + return { + status: 0, + stdout: resultMarker + "\n" + JSON.stringify({ + protocol: 1, + ok: true, + count: 2, + tools: ["alpha", "zeta"], + truncated: false, + }), + stderr: "", + }; + } return { status: 0, stdout: "registered", stderr: "" }; }; registry.registerSandbox({ @@ -364,6 +383,190 @@ describe("MCP status wire-level credential-resolution probe", { timeout: 15_000 expect(payload.exitCode).toBe(2); expect(payload.errorLines.join("\n")).toContain("at most one of --probe / --no-probe"); }); + + it("runs authenticated discovery without duplicating the implicit probe (#6901)", () => { + const home = createTempHome("nemoclaw-mcp-tools-single-"); + const { stdout } = runHarness( + home, + String.raw` + await bridge.dispatchMcpBridgeCommand("alpha", ["status", "github", "--tools", "--json"]); + const status = JSON.parse(logLines.join("\n")); + process.stdout.write(JSON.stringify({ + status, + probed: executedSandboxCommands.some((c) => c.includes("NEMOCLAW_MCP_PROBE")), + discovered: executedSandboxCommands.some((c) => c.includes("mcp-tool-discovery-runtime")), + })); +`, + ); + const payload = JSON.parse(stdout) as { + status: { + provider: { credentialResolution?: unknown }; + toolDiscovery: { ok: boolean; count: number; tools: string[]; truncated: boolean }; + }; + probed: boolean; + discovered: boolean; + }; + expect(payload.probed).toBe(false); + expect(payload.discovered).toBe(true); + expect(payload.status.provider.credentialResolution).toBeUndefined(); + expect(payload.status.toolDiscovery).toMatchObject({ + ok: true, + count: 2, + tools: ["alpha", "zeta"], + truncated: false, + }); + }); + + it("skips authenticated discovery until provider readiness is verified (#6901)", () => { + const home = createTempHome("nemoclaw-mcp-tools-provider-readiness-"); + const { stdout } = runHarness( + home, + String.raw` + activePolicyState = "match"; + const outcomes = []; + for (const attachmentState of ["absent", "unknown"]) { + providerInspectionState = "present"; + providerAttachmentState = attachmentState; + providerCredentialKey = "GITHUB_TOKEN"; + executedSandboxCommands.length = 0; + const [status] = await bridge.statusMcpBridge("alpha", "github", { + discoverTools: true, + }); + outcomes.push({ + case: "attachment:" + attachmentState, + discovery: status.toolDiscovery, + discoveryCommands: executedSandboxCommands.filter( + (command) => command.includes("mcp-tool-discovery-runtime"), + ).length, + }); + } + providerAttachmentState = "attached"; + providerInspectionState = "absent"; + providerCredentialKey = "GITHUB_TOKEN"; + executedSandboxCommands.length = 0; + const [absentProvider] = await bridge.statusMcpBridge("alpha", "github", { + discoverTools: true, + }); + outcomes.push({ + case: "provider:absent", + discovery: absentProvider.toolDiscovery, + discoveryCommands: executedSandboxCommands.filter( + (command) => command.includes("mcp-tool-discovery-runtime"), + ).length, + }); + providerInspectionState = "present"; + providerCredentialKey = "WRONG_TOKEN"; + executedSandboxCommands.length = 0; + const [wrongProvider] = await bridge.statusMcpBridge("alpha", "github", { + discoverTools: true, + }); + outcomes.push({ + case: "provider:wrong-shape", + discovery: wrongProvider.toolDiscovery, + discoveryCommands: executedSandboxCommands.filter( + (command) => command.includes("mcp-tool-discovery-runtime"), + ).length, + }); + process.stdout.write(JSON.stringify(outcomes)); +`, + ); + expect(JSON.parse(stdout)).toEqual([ + { + case: "attachment:absent", + discovery: { + ok: false, + count: 0, + tools: [], + truncated: false, + detail: "tool discovery skipped: the credential provider is not attached to the sandbox", + }, + discoveryCommands: 0, + }, + { + case: "attachment:unknown", + discovery: { + ok: false, + count: 0, + tools: [], + truncated: false, + detail: "tool discovery skipped: provider attachment could not be inspected", + }, + discoveryCommands: 0, + }, + { + case: "provider:absent", + discovery: { + ok: false, + count: 0, + tools: [], + truncated: false, + detail: "tool discovery skipped: provider attachment could not be inspected", + }, + discoveryCommands: 0, + }, + { + case: "provider:wrong-shape", + discovery: { + ok: false, + count: 0, + tools: [], + truncated: false, + detail: + "tool discovery skipped: the OpenShell provider is absent or does not match the recorded credential binding", + }, + discoveryCommands: 0, + }, + ]); + }); + + it("runs both diagnostics only when --probe is explicit with --tools (#6901)", () => { + const home = createTempHome("nemoclaw-mcp-tools-explicit-probe-"); + const { stdout } = runHarness( + home, + String.raw` + await bridge.dispatchMcpBridgeCommand("alpha", ["status", "github", "--tools", "--probe", "--json"]); + const status = JSON.parse(logLines.join("\n")); + process.stdout.write(JSON.stringify({ + hasResolution: !!status.provider.credentialResolution, + hasDiscovery: !!status.toolDiscovery, + probeCommands: executedSandboxCommands.filter((c) => c.includes("NEMOCLAW_MCP_PROBE")).length, + discoveryCommands: executedSandboxCommands.filter((c) => c.includes("mcp-tool-discovery-runtime")).length, + })); +`, + ); + expect(JSON.parse(stdout)).toEqual({ + hasResolution: true, + hasDiscovery: true, + probeCommands: 1, + discoveryCommands: 1, + }); + }); + + it("requires a named server for --tools and renders the discovered names (#6901)", () => { + const home = createTempHome("nemoclaw-mcp-tools-validation-"); + const { stdout } = runHarness( + home, + String.raw` + await bridge.dispatchMcpBridgeCommand("alpha", ["status", "--tools"]); + const rejectedExitCode = process.exitCode ?? 0; + process.exitCode = 0; + const rejection = [...errorLines]; + errorLines.length = 0; + logLines.length = 0; + await bridge.dispatchMcpBridgeCommand("alpha", ["status", "github", "--tools"]); + process.stdout.write(JSON.stringify({ rejectedExitCode, rejection, rendered: logLines })); +`, + ); + const payload = JSON.parse(stdout) as { + rejectedExitCode: number; + rejection: string[]; + rendered: string[]; + }; + expect(payload.rejectedExitCode).toBe(2); + expect(payload.rejection.join("\n")).toContain("one MCP server name"); + expect(payload.rendered.some((line) => line.includes("tool discovery: successful"))).toBe(true); + expect(payload.rendered.some((line) => line.includes("alpha"))).toBe(true); + }); }); describe("MCP add post-add credential-resolution probe", () => { diff --git a/src/lib/actions/sandbox/mcp-bridge-status.ts b/src/lib/actions/sandbox/mcp-bridge-status.ts index 0c092c6a7f3..eb952413680 100644 --- a/src/lib/actions/sandbox/mcp-bridge-status.ts +++ b/src/lib/actions/sandbox/mcp-bridge-status.ts @@ -31,6 +31,7 @@ import { getSandboxAgent, getSandboxOrThrow, } from "./mcp-bridge-state"; +import { discoverMcpTools } from "./mcp-bridge-tool-discovery"; import { assertAuthenticatedBridgeEntry, normalizeMcpServerUrl, @@ -128,6 +129,11 @@ export interface McpBridgeStatusOptions { * the dispatch layer enables it only where the operator asked for it. */ probeCredentialResolution?: boolean; + /** + * Enumerate names advertised by one managed MCP endpoint. The dispatch + * layer restricts this live operation to an explicitly named server. + */ + discoverTools?: boolean; } export async function statusMcpBridge( @@ -168,6 +174,17 @@ export async function statusMcpBridge( }, policy: { registryPresent: false, gatewayPresent: false }, adapter: { registered: null }, + ...(options.discoverTools + ? { + toolDiscovery: { + ok: false, + count: 0, + tools: [], + truncated: false, + detail: "tool discovery skipped: MCP server is not registered", + }, + } + : {}), }, ]; } @@ -223,6 +240,11 @@ export async function statusMcpBridge( } const unsafeCredentialMayBeAttached = !!credentialWarning && !!entry?.providerName && attached !== false; + const readiness = { + policyGatewayPresent: policyPresence, + providerAttached: attached, + providerCredentialReady, + }; const credentialResolution = options.probeCredentialResolution && entry ? unsafeCredentialMayBeAttached @@ -231,16 +253,25 @@ export async function statusMcpBridge( detail: "probe skipped: the unsupported legacy credential may still be attached to fresh sandbox children", } - : probeCredentialResolution(sandboxName, entry, support.adapter, { - policyGatewayPresent: policyPresence, - providerAttached: attached, - providerCredentialReady, - }) + : probeCredentialResolution(sandboxName, entry, support.adapter, readiness) : undefined; const resolutionWarning = credentialResolution ? credentialResolutionWarning(entry?.env[0], credentialResolution) : undefined; if (resolutionWarning) warnings.push(resolutionWarning); + const toolDiscovery = + options.discoverTools && entry + ? unsafeCredentialMayBeAttached + ? { + ok: false, + count: 0, + tools: [], + truncated: false, + detail: + "tool discovery skipped: the unsupported legacy credential may still be attached to fresh sandbox children", + } + : discoverMcpTools(sandboxName, entry, support.adapter, readiness) + : undefined; return { server: name, agent: entry?.agent ?? agent.name, @@ -277,6 +308,7 @@ export async function statusMcpBridge( "Adapter inspection was skipped because the unsupported legacy credential may still be attached to fresh sandbox children.", } : getAdapterRegistration(sandboxName, support.adapter, entry, hermesReconciliation), + ...(toolDiscovery ? { toolDiscovery } : {}), ...(entry?.addedAt ? { addedAt: entry.addedAt } : {}), ...(entry?.updatedAt ? { updatedAt: entry.updatedAt } : {}), }; diff --git a/src/lib/actions/sandbox/mcp-bridge-tool-discovery.test.ts b/src/lib/actions/sandbox/mcp-bridge-tool-discovery.test.ts new file mode 100644 index 00000000000..66be9ece140 --- /dev/null +++ b/src/lib/actions/sandbox/mcp-bridge-tool-discovery.test.ts @@ -0,0 +1,250 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { spawnSync } from "node:child_process"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { describe, expect, it } from "vitest"; + +import type { AgentMcpAdapter } from "../../agent/defs"; +import type { McpBridgeEntry } from "../../state/registry"; +import { + buildMcpToolDiscoveryCommand, + classifyMcpToolDiscoveryResult, + MCP_TOOL_DISCOVERY_RUNTIME_PATH, + toolDiscoveryReadinessSkipDetail, +} from "./mcp-bridge-tool-discovery"; + +const marker = "__NEMOCLAW_SANDBOX_EXEC_STARTED___0123456789abcdef0123456789abcdef"; +const entry = { + server: "github", + url: "https://api.githubcopilot.com/mcp/", + env: ["GITHUB_TOKEN"], +} as McpBridgeEntry; +const unauthenticatedEntry = { ...entry, env: [] } as McpBridgeEntry; + +function framedResult(value: unknown) { + return { + status: 0, + stdout: `${marker}\n${JSON.stringify(value)}`, + stderr: "", + }; +} + +describe("MCP tool discovery host boundary (#6901)", () => { + it("launches the same shared runtime below every adapter policy ancestor", () => { + const expectedAncestor: Record = { + mcporter: "nemoclaw-start node -e", + "hermes-config": "/opt/hermes/.venv/bin/python -I -c", + "deepagents-config": "/opt/venv/bin/python3 -I -c", + }; + + for (const adapter of Object.keys(expectedAncestor) as AgentMcpAdapter[]) { + const built = buildMcpToolDiscoveryCommand(entry, adapter); + expect(built).not.toBeNull(); + expect(built?.command).toContain(expectedAncestor[adapter]); + expect(built?.command).toContain(MCP_TOOL_DISCOVERY_RUNTIME_PATH); + expect(MCP_TOOL_DISCOVERY_RUNTIME_PATH).toMatch(/\.mjs$/u); + expect(built?.command).not.toContain("--experimental-strip-types"); + expect(built?.command).not.toContain("node_modules"); + expect(built?.command).not.toContain("--authorization"); + expect(built?.command).not.toContain("openshell:resolve:env:GITHUB_TOKEN"); + expect(built?.command).toContain("--credential-env"); + expect(built?.command).toContain("GITHUB_TOKEN"); + expect(built?.command).not.toContain("tools/call"); + expect(built?.command).toContain("rebuild the sandbox"); + } + }); + + it("isolates Python adapter wrappers from a sandbox-controlled subprocess module", () => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-mcp-python-isolation-")); + const importedMarker = path.join(tmpDir, "shadow-imported"); + fs.writeFileSync( + path.join(tmpDir, "subprocess.py"), + `from pathlib import Path\nPath(${JSON.stringify(importedMarker)}).write_text("imported")\n`, + ); + const runner = + "import subprocess, sys; raise SystemExit(subprocess.run(sys.argv[1:], check=False).returncode)"; + + try { + const result = spawnSync("python3", ["-I", "-c", runner, process.execPath, "-e", ""], { + cwd: tmpDir, + encoding: "utf8", + }); + expect(result.status, `${result.stdout}${result.stderr}`).toBe(0); + expect(fs.existsSync(importedMarker)).toBe(false); + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } + }); + + it("passes only the credential key name and rejects missing or non-canonical inputs", () => { + const authenticated = buildMcpToolDiscoveryCommand(entry, "mcporter"); + expect(authenticated).not.toBeNull(); + expect(authenticated?.command).not.toContain("Authorization"); + expect(buildMcpToolDiscoveryCommand(unauthenticatedEntry, "mcporter")).toBeNull(); + expect( + buildMcpToolDiscoveryCommand( + { ...unauthenticatedEntry, url: "https://api.githubcopilot.com:443/mcp/" }, + "mcporter", + ), + ).toBeNull(); + }); + + it("accepts one framed, deterministic, names-only runtime result", () => { + expect( + classifyMcpToolDiscoveryResult( + framedResult({ + protocol: 1, + ok: true, + count: 2, + tools: ["alpha", "zeta"], + truncated: false, + }), + entry, + marker, + ), + ).toEqual({ + ok: true, + count: 2, + tools: ["alpha", "zeta"], + truncated: false, + }); + }); + + it("accepts the bounded inventory when valid names require maximum JSON escaping", () => { + const tools = Array.from( + { length: 500 }, + (_, index) => `${"\\".repeat(250)}${String(index).padStart(6, "0")}`, + ); + + expect( + classifyMcpToolDiscoveryResult( + framedResult({ + protocol: 1, + ok: true, + count: tools.length, + tools, + truncated: false, + }), + entry, + marker, + ), + ).toEqual({ + ok: true, + count: tools.length, + tools, + truncated: false, + }); + }); + + it("retains a strict host cap above the maximum compact runtime inventory", () => { + expect( + classifyMcpToolDiscoveryResult( + { + status: 0, + stdout: `${marker}\n${"x".repeat(256 * 1_024 + 1)}`, + stderr: "", + }, + entry, + marker, + ), + ).toEqual({ + ok: false, + count: 0, + tools: [], + truncated: false, + detail: "tool discovery returned an oversized result", + }); + }); + + it("fails closed on malformed, duplicate, unsorted, or unframed results", () => { + for (const result of [ + framedResult({ protocol: 1, ok: true, count: 1, tools: ["bad\nname"], truncated: false }), + framedResult({ + protocol: 1, + ok: true, + count: 1, + tools: ["safe\u202eevil"], + truncated: false, + }), + framedResult({ + protocol: 1, + ok: true, + count: 1, + tools: ["safe\u2066evil"], + truncated: false, + }), + framedResult({ + protocol: 1, + ok: true, + count: 1, + tools: ["safe\u2028evil"], + truncated: false, + }), + framedResult({ + protocol: 1, + ok: true, + count: 2, + tools: ["same", "same"], + truncated: false, + }), + framedResult({ + protocol: 1, + ok: true, + count: 2, + tools: ["zeta", "alpha"], + truncated: false, + }), + { status: 0, stdout: JSON.stringify({ protocol: 1 }), stderr: "" }, + ]) { + expect(classifyMcpToolDiscoveryResult(result, entry, marker)).toMatchObject({ + ok: false, + count: 0, + tools: [], + }); + } + }); + + it("does not surface process output when the image runtime cannot start", () => { + const result = classifyMcpToolDiscoveryResult( + { + status: 1, + stdout: `${marker}\nBearer should-not-leak`, + stderr: "authorization: should-not-leak", + }, + entry, + marker, + ); + expect(result.detail).toContain("rebuild the sandbox"); + expect(JSON.stringify(result)).not.toContain("should-not-leak"); + }); + + it("gates network traffic on the existing policy and provider readiness", () => { + const ready = { + policyGatewayPresent: true, + providerAttached: true, + providerCredentialReady: true, + }; + expect(toolDiscoveryReadinessSkipDetail({ ...ready, policyGatewayPresent: false })).toContain( + "policy does not match", + ); + expect(toolDiscoveryReadinessSkipDetail({ ...ready, policyGatewayPresent: null })).toContain( + "could not be inspected", + ); + expect(toolDiscoveryReadinessSkipDetail({ ...ready, providerAttached: null })).toContain( + "attachment could not be inspected", + ); + expect(toolDiscoveryReadinessSkipDetail({ ...ready, providerAttached: false })).toContain( + "provider is not attached", + ); + expect( + toolDiscoveryReadinessSkipDetail({ + ...ready, + providerCredentialReady: false, + }), + ).toContain("does not match the recorded credential binding"); + expect(toolDiscoveryReadinessSkipDetail(ready)).toBeUndefined(); + }); +}); diff --git a/src/lib/actions/sandbox/mcp-bridge-tool-discovery.ts b/src/lib/actions/sandbox/mcp-bridge-tool-discovery.ts new file mode 100644 index 00000000000..bc5e8cff13c --- /dev/null +++ b/src/lib/actions/sandbox/mcp-bridge-tool-discovery.ts @@ -0,0 +1,237 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import type { AgentMcpAdapter } from "../../agent/defs"; +import { shellQuote } from "../../core/shell-quote"; +import type { McpBridgeEntry } from "../../state/registry"; +import type { McpBridgeStatus } from "./mcp-bridge-contracts"; +import { redactBridgeSecretsForDisplay } from "./mcp-bridge-output"; +import type { CredentialResolutionProbeReadiness } from "./mcp-bridge-resolution-readiness"; +import { + MCP_RUNTIME_SANITIZED_ENV_VARS, + wrapMcpRuntimeCommand, +} from "./mcp-bridge-runtime-command"; +import { normalizeMcpServerUrl } from "./mcp-bridge-validation"; +import { executeSandboxCommand, type SandboxCommandResult } from "./process-recovery"; +import { + buildSandboxExecMarkedCommand, + createSandboxExecMarker, + extractSandboxExecCommandStdoutFromStreams, +} from "./sandbox-exec-output"; +import { buildTrustedProxyEnvSourceShell } from "./trusted-proxy-env"; + +export const MCP_TOOL_DISCOVERY_RUNTIME_PATH = + "/usr/local/lib/nemoclaw/mcp-tool-discovery-runtime/mcp-tool-discovery.mjs"; +export const MCP_TOOL_DISCOVERY_RESULT_PROTOCOL = 1; +export const MCP_TOOL_DISCOVERY_MAX_TOOLS = 500; +export const MCP_TOOL_DISCOVERY_MAX_NAME_BYTES = 256; +const MCP_TOOL_DISCOVERY_MAX_DETAIL_BYTES = 512; +// The compact runtime result may JSON-escape every byte in 500 valid 256-byte +// tool names. Keep that worst case inside the host boundary while retaining a +// strict cap on sandbox output. +const MCP_TOOL_DISCOVERY_MAX_OUTPUT_BYTES = 256 * 1_024; +const UNSAFE_TEXT = /[\p{Cc}\p{Cf}\u2028\u2029]/u; + +export type McpToolDiscoveryReadiness = CredentialResolutionProbeReadiness; + +export interface McpToolDiscoveryCommand { + command: string; + resultMarker: string; +} + +function failure(detail: string): NonNullable { + return { ok: false, count: 0, tools: [], truncated: false, detail }; +} + +export function toolDiscoveryReadinessSkipDetail( + readiness: McpToolDiscoveryReadiness, +): string | undefined { + if (readiness.policyGatewayPresent === null) { + return "tool discovery skipped: the effective generated MCP policy could not be inspected"; + } + if (!readiness.policyGatewayPresent) { + return "tool discovery skipped: the generated MCP policy does not match the effective gateway policy"; + } + if (readiness.providerAttached === null) { + return "tool discovery skipped: provider attachment could not be inspected"; + } + if (!readiness.providerAttached) { + return "tool discovery skipped: the credential provider is not attached to the sandbox"; + } + if (!readiness.providerCredentialReady) { + return "tool discovery skipped: the OpenShell provider is absent or does not match the recorded credential binding"; + } + return undefined; +} + +export function buildMcpToolDiscoveryCommand( + entry: Pick, + adapter: AgentMcpAdapter, +): McpToolDiscoveryCommand | null { + const credentialEnv = entry.env[0]; + if (!credentialEnv) return null; + // The runtime receives only the validated provider key name and constructs + // the OpenShell placeholder itself. OpenShell injects the real credential + // below this command boundary when the request crosses the policy boundary. + // Under the approved trusted-configured-endpoint contract, advertised names + // remain untrusted and bounded display text, but may be credential-derived; + // parser validation is not a confidentiality proof for a malicious server. + try { + if (normalizeMcpServerUrl(entry.url) !== entry.url) return null; + } catch { + return null; + } + + const resultMarker = createSandboxExecMarker(); + const missingRuntimeResult = JSON.stringify({ + protocol: MCP_TOOL_DISCOVERY_RESULT_PROTOCOL, + ok: false, + count: 0, + tools: [], + truncated: false, + detail: "sandbox image does not include the MCP tool discovery runtime; rebuild the sandbox", + }); + const runtimeCommand = wrapMcpRuntimeCommand(adapter, [ + "node", + MCP_TOOL_DISCOVERY_RUNTIME_PATH, + "--url", + entry.url, + "--credential-env", + credentialEnv, + ]); + const body = [ + `if [ ! -r ${shellQuote(MCP_TOOL_DISCOVERY_RUNTIME_PATH)} ]; then`, + ` printf '%s\\n' ${shellQuote(missingRuntimeResult)}`, + " exit 0", + "fi", + runtimeCommand, + ].join("\n"); + + return { + resultMarker, + command: [ + buildTrustedProxyEnvSourceShell(), + `unset ${MCP_RUNTIME_SANITIZED_ENV_VARS.join(" ")} || true`, + buildSandboxExecMarkedCommand(body, resultMarker), + ].join("\n"), + }; +} + +function utf8Bytes(value: string): number { + return Buffer.byteLength(value, "utf8"); +} + +function safeString(value: unknown, maxBytes: number): value is string { + return typeof value === "string" && utf8Bytes(value) <= maxBytes && !UNSAFE_TEXT.test(value); +} + +function compareNames(left: string, right: string): number { + return left < right ? -1 : left > right ? 1 : 0; +} + +export function classifyMcpToolDiscoveryResult( + result: SandboxCommandResult | null, + entry: Pick, + resultMarker: string, +): NonNullable { + if (result === null) return failure("sandbox unreachable"); + if (result.status !== 0) { + return failure( + "MCP tool discovery runtime failed to start; rebuild the sandbox if the image predates this diagnostic", + ); + } + const output = extractSandboxExecCommandStdoutFromStreams( + { stdout: result.stdout, stderr: result.stderr }, + resultMarker, + ); + if (output === null) return failure("tool discovery output missing trusted result frame"); + if (utf8Bytes(output) > MCP_TOOL_DISCOVERY_MAX_OUTPUT_BYTES) { + return failure("tool discovery returned an oversized result"); + } + + let parsed: unknown; + try { + parsed = JSON.parse(output); + } catch { + return failure("tool discovery returned an invalid result"); + } + if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) { + return failure("tool discovery returned an invalid result"); + } + const value = parsed as Record; + if ( + value.protocol !== MCP_TOOL_DISCOVERY_RESULT_PROTOCOL || + typeof value.ok !== "boolean" || + typeof value.count !== "number" || + !Number.isSafeInteger(value.count) || + value.count < 0 || + !Array.isArray(value.tools) || + value.tools.length !== value.count || + value.tools.length > MCP_TOOL_DISCOVERY_MAX_TOOLS || + typeof value.truncated !== "boolean" + ) { + return failure("tool discovery returned an invalid result"); + } + + const tools: string[] = []; + const seen = new Set(); + for (const tool of value.tools) { + if ( + !safeString(tool, MCP_TOOL_DISCOVERY_MAX_NAME_BYTES) || + tool.length === 0 || + seen.has(tool) + ) { + return failure("tool discovery returned an invalid tool name"); + } + seen.add(tool); + tools.push(tool); + } + const sortedTools = [...tools].sort(compareNames); + if (tools.some((tool, index) => tool !== sortedTools[index])) { + return failure("tool discovery returned a non-deterministic tool inventory"); + } + + const detail = value.detail; + if (detail !== undefined && !safeString(detail, MCP_TOOL_DISCOVERY_MAX_DETAIL_BYTES)) { + return failure("tool discovery returned an invalid detail"); + } + if ((value.ok && value.truncated) || (!value.ok && !detail)) { + return failure("tool discovery returned an inconsistent result"); + } + if (!value.ok && !value.truncated && tools.length > 0) { + return failure("tool discovery returned an inconsistent partial result"); + } + + const redactedDetail = detail ? redactBridgeSecretsForDisplay(detail, entry) : undefined; + if (redactedDetail && utf8Bytes(redactedDetail) > MCP_TOOL_DISCOVERY_MAX_DETAIL_BYTES) { + return failure("tool discovery returned an oversized detail after redaction"); + } + return { + ok: value.ok, + count: tools.length, + tools, + truncated: value.truncated, + ...(redactedDetail ? { detail: redactedDetail } : {}), + }; +} + +export function discoverMcpTools( + sandboxName: string, + entry: McpBridgeEntry, + adapter: AgentMcpAdapter | undefined, + readiness: McpToolDiscoveryReadiness, +): NonNullable { + if (!adapter) return failure("tool discovery skipped: MCP adapter is not declared"); + if (entry.addState) return failure("tool discovery skipped: add transaction is incomplete"); + const readinessSkipDetail = toolDiscoveryReadinessSkipDetail(readiness); + if (readinessSkipDetail) return failure(readinessSkipDetail); + const discoveryCommand = buildMcpToolDiscoveryCommand(entry, adapter); + if (!discoveryCommand) { + return failure("tool discovery skipped: no valid managed endpoint is available"); + } + return classifyMcpToolDiscoveryResult( + executeSandboxCommand(sandboxName, discoveryCommand.command), + entry, + discoveryCommand.resultMarker, + ); +} diff --git a/src/lib/actions/sandbox/mcp-bridge.ts b/src/lib/actions/sandbox/mcp-bridge.ts index d31fdfaae1b..6fa166f6c19 100644 --- a/src/lib/actions/sandbox/mcp-bridge.ts +++ b/src/lib/actions/sandbox/mcp-bridge.ts @@ -189,6 +189,13 @@ function parseProbeFlags(args: string[]): { probe?: boolean; rest: string[] } { return { probe, rest: args.filter((arg) => arg !== "--probe" && arg !== "--no-probe") }; } +function parseToolsFlag(args: string[]): { tools: boolean; rest: string[] } { + return { + tools: args.includes("--tools"), + rest: args.filter((arg) => arg !== "--tools"), + }; +} + /** * Post-add wire probe (#6379). Reports only — the add transaction committed * durably and a resolution failure is a host-side OpenShell defect, so a @@ -266,12 +273,13 @@ FLAGS return; case "status": console.log(`USAGE - nemoclaw mcp status [server] [--json] [--probe|--no-probe] + nemoclaw mcp status [server] [--json] [--probe|--no-probe] [--tools] FLAGS --json Emit MCP server status as JSON --probe Request the wire-level credential-resolution probe for every server - --no-probe Skip the probe (it defaults on only when a single server is named)`); + --no-probe Skip the probe (it defaults on only when a single server is named) + --tools Discover names advertised by one named MCP server`); return; case "restart": console.log(`USAGE @@ -331,15 +339,20 @@ export async function dispatchMcpBridgeCommand( } case "status": { const { json, rest: statusJsonRest } = parseJsonFlag(rest); - const { probe, rest: statusRest } = parseProbeFlags(statusJsonRest); + const { tools, rest: statusToolsRest } = parseToolsFlag(statusJsonRest); + const { probe, rest: statusRest } = parseProbeFlags(statusToolsRest); const server = requireAtMostOneArg( statusRest, - "Usage: nemoclaw mcp status [server] [--json] [--probe|--no-probe]", + "Usage: nemoclaw mcp status [server] [--json] [--probe|--no-probe] [--tools]", ); + if (tools && server === undefined) { + throw new McpBridgeError("Pass one MCP server name with --tools.", 2); + } const sandbox = getSandboxOrThrow(sandboxName); const agent = getSandboxAgent(sandbox); const statuses = await statusMcpBridge(sandboxName, server, { - probeCredentialResolution: probe ?? server !== undefined, + probeCredentialResolution: probe === true || (probe !== false && !tools && !!server), + discoverTools: tools, }); if (json) { console.log( diff --git a/src/lib/actions/sandbox/mcp-tool-discovery-runtime.test.ts b/src/lib/actions/sandbox/mcp-tool-discovery-runtime.test.ts new file mode 100644 index 00000000000..0b5cab2b33c --- /dev/null +++ b/src/lib/actions/sandbox/mcp-tool-discovery-runtime.test.ts @@ -0,0 +1,275 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { describe, expect, it, vi } from "vitest"; + +import { + buildMcpToolDiscoveryAuthorizationPlaceholder, + createBoundedMcpFetch, + enumerateMcpToolNames, + MCP_TOOL_DISCOVERY_LIMITS, + MCP_TOOL_DISCOVERY_PROTOCOL, + normalizeMcpToolPage, + parseMcpToolDiscoveryArguments, + runMcpToolDiscoverySession, + safeToolDiscoveryErrorDetail, + ToolDiscoveryRuntimeError, +} from "../../../../tools/mcp-tool-discovery-runtime/tool-discovery-core.ts"; +import { + MCP_TOOL_DISCOVERY_MAX_NAME_BYTES, + MCP_TOOL_DISCOVERY_MAX_TOOLS, + MCP_TOOL_DISCOVERY_RESULT_PROTOCOL, +} from "./mcp-bridge-tool-discovery"; +import { validateMcpCredentialEnvName } from "./mcp-bridge-validation"; + +describe("shared MCP tool discovery runtime", () => { + it("accepts canonical credential key names and rejects authorization values", () => { + expect(() => + parseMcpToolDiscoveryArguments([ + "--url", + "https://malicious.example.test/mcp", + "--authorization", + "arbitrary-format-secret-that-the-server-would-echo", + ]), + ).toThrow("invalid arguments"); + for (const credentialEnv of [ + "EXAMPLE_MCP_TOKEN", + "lowercase_token", + "_TOKEN", + `A${"a".repeat(127)}`, + ]) { + expect(() => validateMcpCredentialEnvName(credentialEnv)).not.toThrow(); + expect( + parseMcpToolDiscoveryArguments([ + "--url", + "https://example.test/mcp", + "--credential-env", + credentialEnv, + ]), + ).toEqual({ + url: new URL("https://example.test/mcp"), + credentialEnv, + }); + } + expect(buildMcpToolDiscoveryAuthorizationPlaceholder("EXAMPLE_MCP_TOKEN")).toBe( + "Bearer openshell:resolve:env:EXAMPLE_MCP_TOKEN", + ); + for (const credentialEnv of ["not-valid", "1TOKEN", `A${"a".repeat(128)}`]) { + expect(() => validateMcpCredentialEnvName(credentialEnv)).toThrow(); + expect(() => + parseMcpToolDiscoveryArguments([ + "--url", + "https://example.test/mcp", + "--credential-env", + credentialEnv, + ]), + ).toThrow("invalid arguments"); + } + }); + + it("enumerates every page and returns deterministic names only", async () => { + const loadPage = vi + .fn() + .mockResolvedValueOnce({ + tools: [{ name: "zeta", description: "discard me" }], + nextCursor: "next", + }) + .mockResolvedValueOnce({ tools: [{ name: "alpha" }] }); + + await expect(enumerateMcpToolNames(loadPage)).resolves.toEqual({ + ok: true, + count: 2, + tools: ["alpha", "zeta"], + truncated: false, + }); + expect(loadPage).toHaveBeenNthCalledWith(1, undefined); + expect(loadPage).toHaveBeenNthCalledWith(2, "next"); + }); + + it("fails closed on duplicate names and repeated cursors", async () => { + await expect( + enumerateMcpToolNames(async () => ({ + tools: [{ name: "same" }, { name: "same" }], + })), + ).rejects.toMatchObject({ code: "invalid-response" }); + + let page = 0; + await expect( + enumerateMcpToolNames(async () => { + page += 1; + return { tools: [{ name: `tool-${page}` }], nextCursor: "repeat" }; + }), + ).rejects.toMatchObject({ code: "invalid-response" }); + + await expect( + enumerateMcpToolNames(async () => normalizeMcpToolPage({ tools: [], nextCursor: "" })), + ).rejects.toMatchObject({ code: "invalid-response" }); + }); + + it("rejects empty, control-bearing, and overlong tool names", async () => { + for (const name of [ + "", + "bad\nname", + "x".repeat(MCP_TOOL_DISCOVERY_LIMITS.maxToolNameBytes + 1), + ]) { + await expect( + enumerateMcpToolNames(async () => ({ tools: [{ name }] })), + ).rejects.toMatchObject({ code: "invalid-response" }); + } + }); + + it("returns an explicit partial failure at tool and page safety limits", async () => { + const tools = Array.from({ length: MCP_TOOL_DISCOVERY_LIMITS.maxTools + 1 }, (_, index) => ({ + name: `tool-${String(index).padStart(3, "0")}`, + })); + await expect(enumerateMcpToolNames(async () => ({ tools }))).resolves.toMatchObject({ + ok: false, + count: MCP_TOOL_DISCOVERY_LIMITS.maxTools, + truncated: true, + detail: expect.stringContaining("tool safety limit"), + }); + + let page = 0; + await expect( + enumerateMcpToolNames(async () => { + page += 1; + return { tools: [], nextCursor: `cursor-${page}` }; + }), + ).resolves.toEqual({ + ok: false, + count: 0, + tools: [], + truncated: true, + detail: `tool discovery reached the ${MCP_TOOL_DISCOVERY_LIMITS.maxPages}-page safety limit`, + }); + }); + + it("attempts both cleanup operations after failed connected discovery", async () => { + const terminateSession = vi.fn(async () => { + throw new Error("untrusted terminate failure"); + }); + const close = vi.fn(async () => { + throw new Error("untrusted close failure"); + }); + const publishResult = vi.fn(); + + await runMcpToolDiscoverySession({ + connect: vi.fn(async () => undefined), + loadPage: vi.fn(async () => { + throw new Error("Bearer untrusted discovery failure"); + }), + hasSession: () => true, + terminateSession, + close, + publishResult, + }); + + expect(terminateSession).toHaveBeenCalledOnce(); + expect(close).toHaveBeenCalledOnce(); + expect(publishResult).toHaveBeenCalledOnce(); + const result = publishResult.mock.calls[0]?.[0]; + expect(result).toEqual({ + ok: false, + count: 0, + tools: [], + truncated: false, + detail: "MCP tool discovery request failed", + }); + expect(JSON.stringify(result)).not.toContain("Bearer"); + expect(JSON.stringify(result)).not.toContain("terminate failure"); + expect(JSON.stringify(result)).not.toContain("close failure"); + }); + + it("rejects redirects and declared oversized responses before reading bodies", async () => { + const deadline = AbortSignal.timeout(1_000); + const redirectFetch = createBoundedMcpFetch( + async () => new Response(null, { status: 307, headers: { location: "https://other/" } }), + deadline, + ); + await expect(redirectFetch("https://example.test/mcp")).rejects.toMatchObject({ + code: "redirect", + }); + + const oversizedFetch = createBoundedMcpFetch( + async () => + new Response("small", { + headers: { + "content-length": String(MCP_TOOL_DISCOVERY_LIMITS.maxResponseBytes + 1), + }, + }), + deadline, + ); + await expect(oversizedFetch("https://example.test/mcp")).rejects.toMatchObject({ + code: "response-too-large", + }); + }); + + it("cancels a chunked response after cumulative bytes cross the limit", async () => { + const sourceCancel = vi.fn(); + let chunk = 0; + const body = new ReadableStream({ + pull(controller) { + chunk += 1; + controller.enqueue( + new Uint8Array(chunk === 1 ? MCP_TOOL_DISCOVERY_LIMITS.maxResponseBytes : 1), + ); + }, + cancel: sourceCancel, + }); + const boundedFetch = createBoundedMcpFetch( + async () => new Response(body), + AbortSignal.timeout(1_000), + ); + + const response = await boundedFetch("https://example.test/mcp"); + expect(response.headers.get("content-length")).toBeNull(); + await expect(response.arrayBuffer()).rejects.toMatchObject({ + code: "response-too-large", + }); + expect(sourceCancel).toHaveBeenCalledOnce(); + }); + + it("bounds both total-deadline and per-request aborts with a credential-safe timeout", async () => { + for (const abortSource of ["deadline", "request"] as const) { + const deadline = new AbortController(); + const request = new AbortController(); + const blockingFetch = vi.fn( + (_input: string | URL, init?: RequestInit) => + new Promise((_resolve, reject) => { + const signal = init?.signal; + expect(signal).toBeDefined(); + const rejectAbort = () => + reject(new DOMException("Bearer untrusted-timeout-detail", "AbortError")); + signal?.addEventListener("abort", rejectAbort, { once: true }); + }), + ); + const boundedFetch = createBoundedMcpFetch(blockingFetch, deadline.signal); + const pending = boundedFetch("https://example.test/mcp", { signal: request.signal }); + (abortSource === "deadline" ? deadline : request).abort(); + const error = await pending.catch((caught: unknown) => caught); + expect(error).toMatchObject({ code: "timeout" }); + expect(safeToolDiscoveryErrorDetail(error)).toBe("tool discovery timed out after 10s"); + expect(safeToolDiscoveryErrorDetail(error)).not.toContain("untrusted-timeout-detail"); + } + }); + + it("maps failures to bounded details without echoing untrusted messages", () => { + expect(safeToolDiscoveryErrorDetail(new ToolDiscoveryRuntimeError("redirect"))).toBe( + "MCP endpoint redirect was rejected", + ); + expect( + safeToolDiscoveryErrorDetail( + Object.assign(new Error("remote body contains Bearer secret-value"), { code: 401 }), + ), + ).toBe("MCP endpoint rejected tool discovery (HTTP 401)"); + expect(safeToolDiscoveryErrorDetail(new Error("Bearer secret-value"))).toBe( + "MCP tool discovery request failed", + ); + }); + + it("keeps the host parser and image runtime on the same result limits", () => { + expect(MCP_TOOL_DISCOVERY_RESULT_PROTOCOL).toBe(MCP_TOOL_DISCOVERY_PROTOCOL); + expect(MCP_TOOL_DISCOVERY_MAX_TOOLS).toBe(MCP_TOOL_DISCOVERY_LIMITS.maxTools); + expect(MCP_TOOL_DISCOVERY_MAX_NAME_BYTES).toBe(MCP_TOOL_DISCOVERY_LIMITS.maxToolNameBytes); + }); +}); diff --git a/src/lib/cli/public-display-mcp.test.ts b/src/lib/cli/public-display-mcp.test.ts index 9d6eb9e6098..f394e2b731e 100644 --- a/src/lib/cli/public-display-mcp.test.ts +++ b/src/lib/cli/public-display-mcp.test.ts @@ -24,5 +24,9 @@ describe("sandbox MCP public display layout", () => { "MCP Servers", "MCP Servers", ]); + expect(SANDBOX_MCP_DISPLAY_LAYOUT["sandbox:mcp"]?.[2]).toMatchObject({ + description: "Inspect MCP server health and advertised tools", + flags: "[server] [--json] [--probe|--no-probe] [--tools]", + }); }); }); diff --git a/src/lib/cli/public-display-mcp.ts b/src/lib/cli/public-display-mcp.ts index 3f425a454c5..30e5541fdcc 100644 --- a/src/lib/cli/public-display-mcp.ts +++ b/src/lib/cli/public-display-mcp.ts @@ -23,8 +23,8 @@ export const SANDBOX_MCP_DISPLAY_LAYOUT: Record mcp status", - description: "Inspect MCP server health", - flags: "[server] [--json]", + description: "Inspect MCP server health and advertised tools", + flags: "[server] [--json] [--probe|--no-probe] [--tools]", }, { group: "MCP Servers", diff --git a/src/lib/sandbox/build-context.ts b/src/lib/sandbox/build-context.ts index 8780d02ddd5..dd67014c35f 100644 --- a/src/lib/sandbox/build-context.ts +++ b/src/lib/sandbox/build-context.ts @@ -52,6 +52,24 @@ function stageOpenClawRuntimeGraphs(rootDir: string, buildCtx: string): void { normalizeReadModesForDockerCopy(path.join(buildCtx, "agents")); } +function stageMcpToolDiscoveryRuntime(rootDir: string, buildCtx: string): void { + const sourceDir = path.join(rootDir, "tools", "mcp-tool-discovery-runtime"); + const stagedDir = path.join(buildCtx, "tools", "mcp-tool-discovery-runtime"); + fs.mkdirSync(stagedDir, { recursive: true }); + for (const fileName of [ + "package.json", + "package-lock.json", + "tsconfig.json", + "install-reviewed-runtime.sh", + "build-runtime.ts", + "mcp-tool-discovery.ts", + "tool-discovery-core.ts", + ]) { + fs.copyFileSync(path.join(sourceDir, fileName), path.join(stagedDir, fileName)); + } + normalizeReadModesForDockerCopy(path.join(buildCtx, "tools")); +} + function stageLegacySandboxBuildContext( rootDir: string, tmpDir: string = os.tmpdir(), @@ -63,6 +81,7 @@ function stageLegacySandboxBuildContext( path.join(buildCtx, "tsconfig.runtime-preloads.json"), ); stageOpenClawRuntimeGraphs(rootDir, buildCtx); + stageMcpToolDiscoveryRuntime(rootDir, buildCtx); fs.cpSync(path.join(rootDir, "nemoclaw"), path.join(buildCtx, "nemoclaw"), { recursive: true, }); @@ -115,6 +134,7 @@ function stageOptimizedSandboxBuildContext( path.join(buildCtx, "tsconfig.runtime-preloads.json"), ); stageOpenClawRuntimeGraphs(rootDir, buildCtx); + stageMcpToolDiscoveryRuntime(rootDir, buildCtx); fs.mkdirSync(stagedCiDir, { recursive: true }); fs.copyFileSync( diff --git a/test/e2e-risk-signal-reporter.test.ts b/test/e2e-risk-signal-reporter.test.ts index d591da3cef9..8c523bcec03 100644 --- a/test/e2e-risk-signal-reporter.test.ts +++ b/test/e2e-risk-signal-reporter.test.ts @@ -32,6 +32,7 @@ vi.mock("node:child_process", () => ({ const EXPECTED_SHA = "a".repeat(40); const PLAN_HASH = "b".repeat(64); const CORRELATION_ID = "12345678-1234-4123-8123-123456789abc"; +const ORIGINAL_PROCESS_EXIT_CODE = process.exitCode; function moduleWithStates(states: Array<"passed" | "failed" | "skipped" | "pending">): TestModule { return { @@ -86,6 +87,8 @@ function environment(artifactDir: string): RiskSignalEnvironment { describe("E2E risk signal reporter", () => { afterEach(() => { + process.exitCode = ORIGINAL_PROCESS_EXIT_CODE; + vi.restoreAllMocks(); vi.unstubAllEnvs(); }); @@ -247,6 +250,99 @@ describe("E2E risk signal reporter", () => { } }); + it("fails closed when the configured name pattern matches no tests", () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-risk-signal-")); + try { + vi.stubEnv("E2E_ARTIFACT_DIR", dir); + vi.stubEnv("E2E_TARGET_ID", "mcp-bridge"); + vi.stubEnv("NEMOCLAW_E2E_EXPECTED_SHA", EXPECTED_SHA); + vi.stubEnv("NEMOCLAW_E2E_PLAN_HASH", PLAN_HASH); + vi.stubEnv("NEMOCLAW_E2E_CORRELATION_ID", CORRELATION_ID); + vi.stubEnv("NEMOCLAW_E2E_SHARD", "openclaw"); + const error = vi.spyOn(console, "error").mockImplementation(() => undefined); + + const reporter = new E2eRiskSignalReporter(); + reporter.onInit({ + getGlobalTestNamePattern: () => /^mcp-bridge$/u, + } as Vitest); + reporter.onTestRunStart([{ testNamePattern: undefined } as TestSpecification]); + reporter.onTestRunEnd( + [moduleWithNamedStates([{ fullName: "mcp-bridge-hermes", state: "skipped" }])], + [], + "passed", + ); + + const signal = JSON.parse( + fs.readFileSync(path.join(dir, RISK_SIGNAL_FILE), "utf8"), + ) as Record; + expect(signal).toMatchObject({ + passed: 0, + failed: 0, + skipped: 0, + pending: 0, + runReason: "failed", + }); + expect(process.exitCode).toBe(1); + expect(error).toHaveBeenCalledWith(expect.stringContaining("matched no tests")); + + reporter.onTestRunEnd( + [moduleWithNamedStates([{ fullName: "mcp-bridge", state: "passed" }])], + [], + "passed", + ); + const mergedSignal = JSON.parse( + fs.readFileSync(path.join(dir, RISK_SIGNAL_FILE), "utf8"), + ) as Record; + expect(mergedSignal).toMatchObject({ + passed: 1, + failed: 0, + skipped: 0, + pending: 0, + runReason: "failed", + }); + expect(process.exitCode).toBe(1); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } + }); + + it("accepts a selected skipped test as matched evidence", () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-risk-signal-")); + try { + vi.stubEnv("E2E_ARTIFACT_DIR", dir); + vi.stubEnv("E2E_TARGET_ID", "mcp-bridge"); + vi.stubEnv("NEMOCLAW_E2E_EXPECTED_SHA", EXPECTED_SHA); + vi.stubEnv("NEMOCLAW_E2E_PLAN_HASH", PLAN_HASH); + vi.stubEnv("NEMOCLAW_E2E_CORRELATION_ID", CORRELATION_ID); + vi.stubEnv("NEMOCLAW_E2E_SHARD", "openclaw"); + + const reporter = new E2eRiskSignalReporter(); + reporter.onInit({ + getGlobalTestNamePattern: () => /^mcp-bridge$/u, + } as Vitest); + reporter.onTestRunStart([{ testNamePattern: undefined } as TestSpecification]); + reporter.onTestRunEnd( + [moduleWithNamedStates([{ fullName: "mcp-bridge", state: "skipped" }])], + [], + "passed", + ); + + const signal = JSON.parse( + fs.readFileSync(path.join(dir, RISK_SIGNAL_FILE), "utf8"), + ) as Record; + expect(signal).toMatchObject({ + passed: 0, + failed: 0, + skipped: 1, + pending: 0, + runReason: "passed", + }); + expect(process.exitCode).toBe(ORIGINAL_PROCESS_EXIT_CODE); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } + }); + it("refuses a symlinked prior signal without modifying its target", () => { const dir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-risk-signal-")); const target = path.join(dir, "target.json"); diff --git a/test/e2e/live/mcp-bridge-servers.ts b/test/e2e/live/mcp-bridge-servers.ts index c643a257e98..1c52afeaeb5 100644 --- a/test/e2e/live/mcp-bridge-servers.ts +++ b/test/e2e/live/mcp-bridge-servers.ts @@ -47,7 +47,7 @@ type TunnelCleanupRegistry = Pick; interface McpRequestPayload { id?: unknown; method?: unknown; - params?: { name?: unknown; arguments?: { challenge?: unknown } }; + params?: { name?: unknown; arguments?: { challenge?: unknown }; cursor?: unknown }; } const MCP_NOTIFICATION_METHODS = new Set([ @@ -668,20 +668,40 @@ export async function startFakeMcpHttpsServer(options: { serverInfo: { name: "fake", version: "1.0.0" }, }; } else if (parsedPayload.method === "tools/list") { - result = { - tools: [ - { - name: "fake_echo", - description: "Returns an authenticated MCP proof token", - inputSchema: { - type: "object", - properties: { challenge: { type: "string" } }, - required: ["challenge"], - additionalProperties: false, + if (parsedPayload.params?.cursor === undefined) { + result = { + tools: [ + { + name: "fake_echo", + description: "Returns an authenticated MCP proof token", + inputSchema: { + type: "object", + properties: { challenge: { type: "string" } }, + required: ["challenge"], + additionalProperties: false, + }, }, - }, - ], - }; + ], + nextCursor: "fake-page-2", + }; + } else if (parsedPayload.params.cursor === "fake-page-2") { + result = { + tools: [ + { + name: "fake_status", + description: "Returns fixture status", + inputSchema: { type: "object", properties: {}, additionalProperties: false }, + }, + ], + }; + } else { + jsonResponse(res, 200, { + jsonrpc: "2.0", + id: parsedPayload.id ?? 1, + error: { code: -32602, message: "invalid tools/list cursor" }, + }); + return; + } } else if (parsedPayload.method === "tools/call") { const challenge = parsedPayload.params?.arguments?.challenge; if ( diff --git a/test/e2e/live/mcp-bridge-tool-discovery.ts b/test/e2e/live/mcp-bridge-tool-discovery.ts new file mode 100644 index 00000000000..46a114f6361 --- /dev/null +++ b/test/e2e/live/mcp-bridge-tool-discovery.ts @@ -0,0 +1,116 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { expect } from "vitest"; + +import { buildAvailabilityProbeEnv } from "../fixtures/availability-env.ts"; +import { assertExitZero } from "../fixtures/clients/command.ts"; +import type { HostCliClient } from "../fixtures/clients/host.ts"; +import type { FakeMcpHttpsServer } from "./mcp-bridge-servers.ts"; + +export async function assertAuthenticatedMcpDiscovery( + fakeMcp: FakeMcpHttpsServer, + options: { + requestOffset: number; + expectedSecret: string; + label: string; + }, +): Promise { + await expect + .poll( + () => { + const requests = fakeMcp.requests.slice(options.requestOffset); + const observed = (rpcMethod: "initialize" | "tools/list") => + requests.some( + (request) => + request.method === "POST" && + request.path === "/mcp" && + request.rpcMethod === rpcMethod && + request.auth === `Bearer ${options.expectedSecret}`, + ); + return { + initialized: observed("initialize"), + toolsListed: observed("tools/list"), + requests: requests.map((request) => ({ + method: request.method, + path: request.path, + rpcMethod: request.rpcMethod, + credentialRewritten: request.auth === `Bearer ${options.expectedSecret}`, + })), + }; + }, + { interval: 500, timeout: 90_000, message: options.label }, + ) + .toMatchObject({ initialized: true, toolsListed: true }); +} + +export async function assertAuthenticatedMcpToolDiscovery( + host: HostCliClient, + fakeMcp: FakeMcpHttpsServer, + options: { sandboxName: string; artifactPrefix: string; hostSecret: string }, +): Promise { + const requestOffset = fakeMcp.requests.length; + const status = await host.nemoclaw( + [options.sandboxName, "mcp", "status", "fake", "--tools", "--json"], + { + artifactName: `${options.artifactPrefix}-mcp-status-tools-json`, + env: { + ...buildAvailabilityProbeEnv(), + FAKE_MCP_SECRET: options.hostSecret, + }, + redactionValues: [options.hostSecret], + timeoutMs: 60_000, + }, + ); + assertExitZero(status, `${options.artifactPrefix} mcp status --tools --json`); + const statusJson = JSON.parse(status.stdout) as { + provider: { credentialResolution?: unknown }; + toolDiscovery: { + ok: boolean; + count: number; + tools: string[]; + truncated: boolean; + detail?: string; + }; + }; + expect(statusJson.provider.credentialResolution).toBeUndefined(); + expect(statusJson.toolDiscovery).toMatchObject({ + ok: true, + count: 2, + tools: ["fake_echo", "fake_status"], + truncated: false, + }); + expect(status.stdout).not.toContain(options.hostSecret); + const discoveryRequests = fakeMcp.requests.slice(requestOffset); + const authenticatedRpcMethods = discoveryRequests + .filter( + (request) => + request.method === "POST" && + request.path === "/mcp" && + request.auth === `Bearer ${options.hostSecret}`, + ) + .map((request) => request.rpcMethod); + const initializeIndex = authenticatedRpcMethods.indexOf("initialize"); + const initializedIndex = authenticatedRpcMethods.indexOf("notifications/initialized"); + const firstToolListIndex = authenticatedRpcMethods.indexOf("tools/list"); + expect(initializeIndex, "authenticated MCP discovery must initialize a session").toBeGreaterThan( + -1, + ); + expect( + initializedIndex, + "authenticated MCP discovery must notify the server after initialization", + ).toBeGreaterThan(initializeIndex); + expect( + firstToolListIndex, + "authenticated MCP discovery must finish initialization before listing tools", + ).toBeGreaterThan(initializedIndex); + + const toolListRequests = discoveryRequests.filter( + (request) => request.rpcMethod === "tools/list", + ); + expect(toolListRequests).toHaveLength(2); + expect(toolListRequests.every((request) => request.auth === `Bearer ${options.hostSecret}`)).toBe( + true, + ); + expect(fakeMcp.requests.some((request) => request.rpcMethod === "tools/call")).toBe(false); +} diff --git a/test/e2e/live/mcp-bridge.test.ts b/test/e2e/live/mcp-bridge.test.ts index 7e8045ae875..2aae46e106f 100644 --- a/test/e2e/live/mcp-bridge.test.ts +++ b/test/e2e/live/mcp-bridge.test.ts @@ -42,10 +42,15 @@ import { setupDnsRebindingHostsFixture, } from "./mcp-bridge-sandbox.ts"; import { + type FakeMcpHttpsServer, startCompatibleMock, startFakeMcpHttpsServer, startPublicMcpHttpsTunnel, } from "./mcp-bridge-servers.ts"; +import { + assertAuthenticatedMcpDiscovery, + assertAuthenticatedMcpToolDiscovery, +} from "./mcp-bridge-tool-discovery.ts"; import { MCP_PROVIDER_REWRITE_PROBE_SOURCE } from "./mcp-provider-rewrite-probe.ts"; import { assertRawOpenShellAllowedIpsRebindingDenied } from "./openshell-allowed-ips-rebinding.ts"; import { prepareExactMainMcpProof } from "./openshell-exact-main-mcp-proof.ts"; @@ -285,10 +290,8 @@ async function assertAdapterDnsRebindingDenied( `${options.artifactPrefix}-dns-rebinding-secret-absent-from-sandbox`, ); - // If OpenShell resolved a second time after validating allowed_ips, this - // reachable runner address would receive the request. The pinned v0.0.72 - // implementation instead returns the one resolved-and-validated SocketAddr - // list directly to connect; see the exact proxy.rs citation in the helper. + // A second resolution after allowed_ips validation would reach the runner address. + // The pinned implementation connects with the already validated SocketAddr list. const reboundAddress = await hostPrivateAddressForSandbox(host); expect(reboundAddress).not.toBe(REBIND_PUBLIC_IP); await remapDnsRebindingHostname( @@ -319,9 +322,7 @@ async function assertAdapterDnsRebindingDenied( `${options.artifactPrefix} rebound request must not reach the upstream MCP server`, ).toHaveLength(0); - // Restore while the current sandbox container is stable. Removing the MCP - // route reloads policy and can restart the container first; the registered - // cleanup remains an idempotent fallback. + // Restore before route removal can reload policy; registered cleanup remains a fallback. await restoreDnsRebindingHostsFixture(host, options.sandboxName, hostsFixture); const remove = await host.nemoclaw([options.sandboxName, "mcp", "remove", REBIND_SERVER_NAME], { artifactName: `${options.artifactPrefix}-mcp-dns-rebinding-remove`, @@ -338,6 +339,7 @@ async function addBridgeAndReadStatus( mcpUrl: string; expectedAdapter: McpAdapter; artifactPrefix: string; + fakeMcp: FakeMcpHttpsServer; }, ): Promise { const add = await host.nemoclaw( @@ -409,6 +411,12 @@ async function addBridgeAndReadStatus( expect(statusJson.provider.name).toMatch( new RegExp(`^${options.sandboxName}-mcp-${SERVER_NAME}-[a-f0-9]{16}$`), ); + + await assertAuthenticatedMcpToolDiscovery(host, options.fakeMcp, { + sandboxName: options.sandboxName, + artifactPrefix: options.artifactPrefix, + hostSecret: HOST_SECRET, + }); return statusJson.provider.name; } @@ -706,42 +714,6 @@ async function assertDeepAgentsConfig( expectExitZero(result, "Deep Agents MCP config contains placeholder and no raw host secret"); } -async function assertAuthenticatedMcpDiscovery( - fakeMcp: Awaited>, - options: { - requestOffset: number; - expectedSecret: string; - label: string; - }, -): Promise { - await expect - .poll( - () => { - const requests = fakeMcp.requests.slice(options.requestOffset); - const observed = (rpcMethod: "initialize" | "tools/list") => - requests.some( - (request) => - request.method === "POST" && - request.path === "/mcp" && - request.rpcMethod === rpcMethod && - request.auth === `Bearer ${options.expectedSecret}`, - ); - return { - initialized: observed("initialize"), - toolsListed: observed("tools/list"), - requests: requests.map((request) => ({ - method: request.method, - path: request.path, - rpcMethod: request.rpcMethod, - credentialRewritten: request.auth === `Bearer ${options.expectedSecret}`, - })), - }; - }, - { interval: 500, timeout: 90_000, message: options.label }, - ) - .toMatchObject({ initialized: true, toolsListed: true }); -} - async function assertRealAdapterToolCall( sandbox: SandboxClient, fakeMcp: Awaited>, @@ -880,10 +852,8 @@ test("mcp-bridge", { sandboxName: OPENCLAW_SANDBOX_NAME, artifactName: "onboard-openclaw-mcp-bridge", }); - // Exercise the raw OpenShell `allowed_ips` boundary before any NemoClaw MCP - // mutation. The helper uses a direct curl request with a /** binary grant, - // then restores this sandbox's exact base policy before returning, so this - // proof is independent of both the CLI implementation and adapter identity. + // Exercise the raw OpenShell `allowed_ips` boundary before any NemoClaw MCP mutation. + // The helper restores the base policy, keeping this proof independent of the CLI and adapter. await assertRawOpenShellAllowedIpsRebindingDenied({ artifacts, env: buildAvailabilityProbeEnv(), @@ -950,6 +920,7 @@ test("mcp-bridge", { mcpUrl, expectedAdapter: "mcporter", artifactPrefix: "openclaw", + fakeMcp, }); await assertBridgeInfrastructure(host, sandbox, { sandboxName: OPENCLAW_SANDBOX_NAME, @@ -1242,6 +1213,7 @@ mcpBridgeShardTest("hermes")( mcpUrl, expectedAdapter: "hermes-config", artifactPrefix: "hermes", + fakeMcp, }); await assertAuthenticatedMcpDiscovery(fakeMcp, { requestOffset: initialDiscoveryOffset, @@ -1414,6 +1386,7 @@ mcpBridgeShardTest("deepagents")( mcpUrl, expectedAdapter: "deepagents-config", artifactPrefix: "deepagents", + fakeMcp, }); await assertBridgeInfrastructure(host, sandbox, { sandboxName: DEEPAGENTS_SANDBOX_NAME, diff --git a/test/e2e/risk-signal-reporter.ts b/test/e2e/risk-signal-reporter.ts index 632339e6593..7189a5fe265 100644 --- a/test/e2e/risk-signal-reporter.ts +++ b/test/e2e/risk-signal-reporter.ts @@ -1,7 +1,6 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { execFileSync } from "node:child_process"; import fs from "node:fs"; import path from "node:path"; @@ -13,70 +12,22 @@ import { type LiveTestOutcome, writeLiveTestOutcome, } from "../../tools/e2e/live-test-outcome.mts"; -import { readPrivateRegularFile, writePrivateRegularFile } from "../../tools/e2e/private-file.mts"; -import type { E2eRiskSignal } from "../../tools/e2e/risk-signal.ts"; - -export const RISK_SIGNAL_FILE = "risk-signal.json"; - -export type RiskSignalEnvironment = { - artifactDir: string; - jobId: string; - shardId: string; - expectedSha: string; - testedSha: string; - planHash: string; - correlationId: string; -}; - -const SHA_PATTERN = /^[a-f0-9]{40}$/u; -const HASH_PATTERN = /^[a-f0-9]{64}$/u; -const CORRELATION_PATTERN = - /^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/u; -const JOB_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_-]*$/u; -const SHARD_PATTERN = /^(?:default|[A-Za-z0-9][A-Za-z0-9_-]*)$/u; - -function checkedOutSha(workspace: string): string { - return execFileSync("git", ["rev-parse", "--verify", "HEAD"], { - cwd: workspace, - encoding: "utf8", - killSignal: "SIGKILL", - stdio: ["ignore", "pipe", "pipe"], - timeout: 5_000, - }).trim(); -} +import { + configuredRiskSignalEnvironment, + type E2eRiskSignal, + RISK_SIGNAL_FILE, + type RiskSignalCounts, + type RiskSignalEnvironment, + writeRiskSignalCounts, +} from "../../tools/e2e/risk-signal.ts"; + +export { RISK_SIGNAL_FILE, type RiskSignalEnvironment }; export function configuredEnvironment( env: NodeJS.ProcessEnv, - resolveHead: (workspace: string) => string = checkedOutSha, + resolveHead?: (workspace: string) => string, ): RiskSignalEnvironment | null { - if (!env.NEMOCLAW_E2E_EXPECTED_SHA) return null; - const values = { - artifactDir: env.E2E_ARTIFACT_DIR ?? "", - jobId: env.E2E_TARGET_ID ?? "", - shardId: env.NEMOCLAW_E2E_SHARD ?? "", - expectedSha: env.NEMOCLAW_E2E_EXPECTED_SHA, - planHash: env.NEMOCLAW_E2E_PLAN_HASH ?? "", - correlationId: env.NEMOCLAW_E2E_CORRELATION_ID ?? "", - }; - if (!values.artifactDir) throw new Error("risk signal requires E2E_ARTIFACT_DIR"); - if (!JOB_PATTERN.test(values.jobId)) throw new Error("risk signal requires a safe E2E_TARGET_ID"); - if (!SHARD_PATTERN.test(values.shardId)) { - throw new Error("risk signal requires a safe shard id"); - } - if (!SHA_PATTERN.test(values.expectedSha)) { - throw new Error("risk signal requires a 40-character lowercase expected SHA"); - } - if (!HASH_PATTERN.test(values.planHash)) { - throw new Error("risk signal requires a 64-character lowercase plan hash"); - } - if (!CORRELATION_PATTERN.test(values.correlationId)) { - throw new Error("risk signal requires a lowercase UUIDv4 correlation id"); - } - const testedSha = resolveHead(env.GITHUB_WORKSPACE ?? process.cwd()); - if (!SHA_PATTERN.test(testedSha) || testedSha !== values.expectedSha) { - throw new Error("risk signal checked-out HEAD does not match the expected SHA"); - } - return { ...values, testedSha }; + return configuredRiskSignalEnvironment(env, resolveHead); } function matchesNamePattern(fullName: string, pattern: RegExp | undefined): boolean { @@ -123,6 +74,18 @@ function failedTestErrors(testModules: ReadonlyArray): unknown[] { return errors; } +function writeSelectedRiskSignal( + environment: RiskSignalEnvironment, + selectedCounts: RiskSignalCounts, + unhandledErrors: ReadonlyArray, + runReason: TestRunEndReason, +): E2eRiskSignal { + // Each call represents a separate Vitest command in the same job/shard; + // Vitest has already collapsed retries inside that command. The shared + // writer sums invocations and keeps failures sticky. + return writeRiskSignalCounts(environment, selectedCounts, unhandledErrors.length, runReason); +} + export function outcomeForRun( testModules: ReadonlyArray, unhandledErrors: ReadonlyArray, @@ -138,44 +101,6 @@ export function outcomeForRun( processTimedOut, }); } - -function mergeSignal(previous: E2eRiskSignal | null, current: E2eRiskSignal): E2eRiskSignal { - if (!previous) return current; - if ( - previous.version !== current.version || - previous.jobId !== current.jobId || - previous.shardId !== current.shardId || - previous.expectedSha !== current.expectedSha || - previous.testedSha !== current.testedSha || - previous.planHash !== current.planHash || - previous.correlationId !== current.correlationId - ) { - throw new Error("risk signal metadata changed between Vitest invocations"); - } - // Each call represents a separate Vitest command in the same job/shard; - // Vitest has already collapsed retries inside that command. Summing keeps - // failures sticky, because any failed or unhandled count makes the gate red. - return { - ...current, - passed: previous.passed + current.passed, - failed: previous.failed + current.failed, - skipped: previous.skipped + current.skipped, - pending: previous.pending + current.pending, - unhandledErrors: previous.unhandledErrors + current.unhandledErrors, - runReason: - previous.runReason === "failed" || current.runReason === "failed" - ? "failed" - : previous.runReason === "interrupted" || current.runReason === "interrupted" - ? "interrupted" - : "passed", - }; -} - -function readPrevious(file: string): E2eRiskSignal | null { - const contents = readPrivateRegularFile(file, { allowMissing: true, maxBytes: 64 * 1024 }); - return contents === null ? null : (JSON.parse(contents) as E2eRiskSignal); -} - export function writeRiskSignal( environment: RiskSignalEnvironment, testModules: ReadonlyArray, @@ -183,23 +108,12 @@ export function writeRiskSignal( runReason: TestRunEndReason, testNamePattern?: RegExp, ): E2eRiskSignal { - const signal: E2eRiskSignal = { - version: 1, - jobId: environment.jobId, - shardId: environment.shardId, - expectedSha: environment.expectedSha, - testedSha: environment.testedSha, - planHash: environment.planHash, - correlationId: environment.correlationId, - ...counts(testModules, testNamePattern), - unhandledErrors: unhandledErrors.length, + return writeSelectedRiskSignal( + environment, + counts(testModules, testNamePattern), + unhandledErrors, runReason, - }; - fs.mkdirSync(environment.artifactDir, { recursive: true }); - const file = path.join(environment.artifactDir, RISK_SIGNAL_FILE); - const merged = mergeSignal(readPrevious(file), signal); - writePrivateRegularFile(file, `${JSON.stringify(merged, null, 2)}\n`); - return merged; + ); } export default class E2eRiskSignalReporter implements Reporter { @@ -237,13 +151,29 @@ export default class E2eRiskSignalReporter implements Reporter { unhandledErrors: ReadonlyArray, reason: TestRunEndReason, ): void { + const selectedCounts = counts(testModules, this.testNamePattern); + const selectorMatchedNothing = + this.testNamePattern !== undefined && + selectedCounts.passed + + selectedCounts.failed + + selectedCounts.skipped + + selectedCounts.pending === + 0; + const effectiveReason: TestRunEndReason = selectorMatchedNothing ? "failed" : reason; + + if (selectorMatchedNothing) { + console.error( + `E2E test selector ${String(this.testNamePattern)} matched no tests; failing closed.`, + ); + process.exitCode = 1; + } if (this.environment) { - writeRiskSignal(this.environment, testModules, unhandledErrors, reason, this.testNamePattern); + writeSelectedRiskSignal(this.environment, selectedCounts, unhandledErrors, effectiveReason); } if (this.outcomeFile) { writeLiveTestOutcome( this.outcomeFile, - outcomeForRun(testModules, unhandledErrors, reason, this.processTimedOut), + outcomeForRun(testModules, unhandledErrors, effectiveReason, this.processTimedOut), ); } } diff --git a/test/e2e/support/live-vitest-invocation.test.ts b/test/e2e/support/live-vitest-invocation.test.ts index ae51ec2f5a0..27bdf61e909 100644 --- a/test/e2e/support/live-vitest-invocation.test.ts +++ b/test/e2e/support/live-vitest-invocation.test.ts @@ -9,8 +9,10 @@ import { describe, expect, it } from "vitest"; import { buildLiveVitestArgs, LIVE_VITEST_PROJECT, + MCP_BRIDGE_TEST_PATH, type LiveVitestSpawner, RISK_SIGNAL_REPORTER, + resolveLiveSelector, runLiveVitestCommand, validateLiveProject, validateLiveSelector, @@ -105,6 +107,50 @@ describe("validateLiveSelector (#6961)", () => { }); }); +describe("resolveLiveSelector (#6904)", () => { + it.each([ + ["openclaw", "^mcp-bridge$"], + ["hermes", "^mcp-bridge-hermes$"], + ["deepagents", "^mcp-bridge-deepagents$"], + ])("infers the reviewed %s selector for trusted base-workflow compatibility", (agent, expected) => { + expect( + resolveLiveSelector(MCP_BRIDGE_TEST_PATH, undefined, { + NEMOCLAW_MCP_BRIDGE_AGENT: agent, + }), + ).toBe(expected); + expect( + resolveLiveSelector(MCP_BRIDGE_TEST_PATH, expected, { + NEMOCLAW_MCP_BRIDGE_AGENT: agent, + }), + ).toBe(expected); + }); + + it("keeps the existing OpenClaw default for local MCP runs", () => { + expect(resolveLiveSelector(MCP_BRIDGE_TEST_PATH, undefined, {})).toBe("^mcp-bridge$"); + }); + + it("rejects an unsupported MCP agent or mismatched explicit selector", () => { + expect(() => + resolveLiveSelector(MCP_BRIDGE_TEST_PATH, undefined, { + NEMOCLAW_MCP_BRIDGE_AGENT: "all", + }), + ).toThrow(/unsupported NEMOCLAW_MCP_BRIDGE_AGENT/u); + expect(() => + resolveLiveSelector(MCP_BRIDGE_TEST_PATH, "^mcp-bridge-hermes$", { + NEMOCLAW_MCP_BRIDGE_AGENT: "openclaw", + }), + ).toThrow(/does not match agent/u); + }); + + it("does not infer selectors for unrelated live tests", () => { + expect( + resolveLiveSelector("test/e2e/live/diagnostics.test.ts", undefined, { + NEMOCLAW_MCP_BRIDGE_AGENT: "hermes", + }), + ).toBeUndefined(); + }); +}); + describe("buildLiveVitestArgs (#6961)", () => { it("builds the standard invocation with a selector", () => { expect( @@ -202,6 +248,22 @@ describe("runLiveVitestCommand (#6961)", () => { expect(() => runLiveVitestCommand(validArgs, spawn)).toThrow(launchError); }); + it("passes the inferred MCP selector to Vitest when trusted base YAML omits it", () => { + let spawned: Parameters | undefined; + const spawn: LiveVitestSpawner = (...args) => { + spawned = args; + return { status: 0 }; + }; + + expect( + runLiveVitestCommand(["run", "--test-path", MCP_BRIDGE_TEST_PATH], spawn, { + NEMOCLAW_MCP_BRIDGE_AGENT: "hermes", + }), + ).toBe(0); + expect(spawned?.[1]).toContain("-t"); + expect(spawned?.[1]).toContain("^mcp-bridge-hermes$"); + }); + it.each([ [ "unknown option", @@ -244,4 +306,32 @@ describe("runLiveVitestCommand (#6961)", () => { expect(result.status).toBe(1); expect(result.stderr).toContain('expected "run"'); }); + + it("fails closed when a selector matches no live tests", () => { + const env: NodeJS.ProcessEnv = { ...process.env, NEMOCLAW_RUN_LIVE_E2E: "1" }; + delete env.E2E_ARTIFACT_DIR; + delete env.E2E_TARGET_ID; + delete env.E2E_TEST_OUTCOME_FILE; + delete env.NEMOCLAW_E2E_CORRELATION_ID; + delete env.NEMOCLAW_E2E_EXPECTED_SHA; + delete env.NEMOCLAW_E2E_PLAN_HASH; + delete env.NEMOCLAW_E2E_SHARD; + + const result = spawnSync( + TSX, + [ + LIVE_VITEST_TOOL, + "run", + "--test-path", + "test/e2e/live/registry-targets.test.ts", + "--selector", + "^definitely-no-such-live-test$", + ], + { encoding: "utf8", env, timeout: 30_000 }, + ); + + expect(result.error).toBeUndefined(); + expect(result.status).toBe(1); + expect(result.stderr).toContain("matched no tests"); + }); }); diff --git a/test/e2e/support/mcp-bridge-runtime-compatibility-cli.test.ts b/test/e2e/support/mcp-bridge-runtime-compatibility-cli.test.ts index 4a1f73fb5bd..7ec658b5383 100644 --- a/test/e2e/support/mcp-bridge-runtime-compatibility-cli.test.ts +++ b/test/e2e/support/mcp-bridge-runtime-compatibility-cli.test.ts @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { spawnSync } from "node:child_process"; +import { execFileSync, spawnSync } from "node:child_process"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; @@ -34,6 +34,9 @@ function runCompatibilityCli(versionStdout: string, versionStderr = "") { { mode: 0o755 }, ); fs.chmodSync(openshellPath, 0o755); + const expectedSha = execFileSync("git", ["rev-parse", "--verify", "HEAD"], { + encoding: "utf8", + }).trim(); const result = spawnSync( process.execPath, @@ -49,8 +52,14 @@ function runCompatibilityCli(versionStdout: string, versionStderr = "") { NODE_NO_WARNINGS: "1", NEMOCLAW_OPENSHELL_BIN: openshellPath, E2E_ARTIFACT_DIR: artifactDirectory, + E2E_TARGET_ID: "mcp-bridge-dev", + GITHUB_WORKSPACE: process.cwd(), GITHUB_OUTPUT: githubOutputPath, GITHUB_STEP_SUMMARY: githubSummaryPath, + NEMOCLAW_E2E_CORRELATION_ID: "12345678-1234-4123-8123-123456789abc", + NEMOCLAW_E2E_EXPECTED_SHA: expectedSha, + NEMOCLAW_E2E_PLAN_HASH: "b".repeat(64), + NEMOCLAW_E2E_SHARD: "hermes", }, killSignal: "SIGKILL", timeout: 30_000, @@ -104,6 +113,18 @@ describe.skipIf(process.platform === "win32")("MCP bridge compatibility CLI", () fullLifecycle: "not-run", }); expect(artifact).not.toHaveProperty("guardMessage"); + expect( + JSON.parse(fs.readFileSync(path.join(run.artifactDirectory, "risk-signal.json"), "utf8")), + ).toMatchObject({ + jobId: "mcp-bridge-dev", + shardId: "hermes", + passed: 1, + failed: 0, + skipped: 0, + pending: 0, + unhandledErrors: 0, + runReason: "passed", + }); const summary = fs.readFileSync(run.githubSummaryPath, "utf8"); expect(summary).toContain( "the exact-version gate rejected the unsupported runtime as required", diff --git a/test/e2e/support/mcp-bridge-runtime-compatibility.test.ts b/test/e2e/support/mcp-bridge-runtime-compatibility.test.ts index e245183ae37..eebb1fb5c26 100644 --- a/test/e2e/support/mcp-bridge-runtime-compatibility.test.ts +++ b/test/e2e/support/mcp-bridge-runtime-compatibility.test.ts @@ -15,6 +15,7 @@ import { import { classifyMcpBridgeRuntimeCompatibility, MCP_BRIDGE_RUNTIME_COMPATIBILITY_ARTIFACT, + recordExpectedMismatchRiskSignal, recordMcpBridgeRuntimeCompatibility, } from "../../../tools/e2e/mcp-bridge-runtime-compatibility.mts"; @@ -113,11 +114,51 @@ describe("MCP bridge dev runtime compatibility", () => { expect(fs.readFileSync(summaryPath, "utf8")).toContain( "the exact-version gate rejected the unsupported runtime as required", ); + expect( + recordExpectedMismatchRiskSignal( + result, + { + E2E_ARTIFACT_DIR: directory, + E2E_TARGET_ID: "mcp-bridge-dev", + GITHUB_WORKSPACE: "/workspace", + NEMOCLAW_E2E_EXPECTED_SHA: "a".repeat(40), + NEMOCLAW_E2E_PLAN_HASH: "b".repeat(64), + NEMOCLAW_E2E_CORRELATION_ID: "12345678-1234-4123-8123-123456789abc", + NEMOCLAW_E2E_SHARD: "hermes", + }, + () => "a".repeat(40), + ), + ).toMatchObject({ + jobId: "mcp-bridge-dev", + shardId: "hermes", + passed: 1, + failed: 0, + skipped: 0, + pending: 0, + unhandledErrors: 0, + runReason: "passed", + }); + expect(JSON.parse(fs.readFileSync(path.join(directory, "risk-signal.json"), "utf8"))).toEqual( + expect.objectContaining({ + expectedSha: "a".repeat(40), + testedSha: "a".repeat(40), + planHash: "b".repeat(64), + correlationId: "12345678-1234-4123-8123-123456789abc", + }), + ); } finally { fs.rmSync(directory, { force: true, recursive: true }); } }); + it("leaves aligned runtimes to the full lifecycle risk reporter (#6426)", () => { + const result = classifyMcpBridgeRuntimeCompatibility( + assertRuntimeVersion(MCP_CREDENTIAL_BOUNDARY_OPENSHELL_VERSION), + ); + + expect(recordExpectedMismatchRiskSignal(result, {})).toBeNull(); + }); + it("keeps every result except an exact version mismatch fatal (#6426)", () => { const fatalAssertions = [ () => assertMcpCredentialBoundaryRuntimeVersion({ resolveOpenshell: () => null }), diff --git a/test/e2e/support/mcp-workflow-boundary.test.ts b/test/e2e/support/mcp-workflow-boundary.test.ts index 764a57c4134..76bb92052a9 100644 --- a/test/e2e/support/mcp-workflow-boundary.test.ts +++ b/test/e2e/support/mcp-workflow-boundary.test.ts @@ -41,6 +41,57 @@ describe("MCP workflow artifact boundary", () => { } }); + it.each([ + "mcp-bridge", + "mcp-bridge-dev", + ])("rejects an unscoped live test invocation in %s", (jobName) => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-mcp-workflow-")); + const workflowPath = path.join(directory, "e2e.yaml"); + try { + const workflow = YAML.parse(fs.readFileSync(".github/workflows/e2e.yaml", "utf8")) as { + jobs: Record }>; + }; + const run = workflow.jobs[jobName].steps.find( + (step) => step.name === "Run MCP OpenShell provider live test", + ); + requireFixture(run?.run, `${jobName} MCP live-test fixture is missing`); + const selector = ' --selector "$mcp_test_selector"'; + requireFixture(run.run.includes(selector), `${jobName} exact selector fixture is missing`); + run.run = run.run.replace(selector, ""); + fs.writeFileSync(workflowPath, YAML.stringify(workflow)); + + expect(validateMcpOpenShellWorkflowBoundary(workflowPath)).toContain( + `${jobName} must pass its exact MCP agent selector to the live test`, + ); + } finally { + fs.rmSync(directory, { force: true, recursive: true }); + } + }); + + it("rejects MCP agent-to-selector mapping drift", () => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-mcp-workflow-")); + const workflowPath = path.join(directory, "e2e.yaml"); + try { + const workflow = YAML.parse(fs.readFileSync(".github/workflows/e2e.yaml", "utf8")) as { + jobs: Record }>; + }; + const run = workflow.jobs["mcp-bridge"].steps.find( + (step) => step.name === "Run MCP OpenShell provider live test", + ); + requireFixture(run?.run, "MCP stable live-test fixture is missing"); + const expected = "hermes) mcp_test_selector='^mcp-bridge-hermes$' ;;"; + requireFixture(run.run.includes(expected), "MCP Hermes selector fixture is missing"); + run.run = run.run.replace(expected, "hermes) mcp_test_selector='^mcp-bridge$' ;;"); + fs.writeFileSync(workflowPath, YAML.stringify(workflow)); + + expect(validateMcpOpenShellWorkflowBoundary(workflowPath)).toContain( + "mcp-bridge must map each MCP agent shard to its exact live test selector", + ); + } finally { + fs.rmSync(directory, { force: true, recursive: true }); + } + }); + it("rejects missing, fail-fast, or in-process MCP agent shards", () => { const directory = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-mcp-workflow-")); const workflowPath = path.join(directory, "e2e.yaml"); diff --git a/test/langchain-deepagents-code-profile-build-gate.test.ts b/test/langchain-deepagents-code-profile-build-gate.test.ts index ec58bc35cc0..d890231c63c 100644 --- a/test/langchain-deepagents-code-profile-build-gate.test.ts +++ b/test/langchain-deepagents-code-profile-build-gate.test.ts @@ -105,11 +105,15 @@ describe("LangChain Deep Agents Code profile build gate", () => { expect(result.calls).not.toContain("--file"); }); - it("accepts NEMOCLAW_UPSTREAM_ENDPOINT_URL as a reviewed source-gate ARG", () => { - const result = runGateWithFakeDocker("expected-failure-with-marker"); + it.each([ + "NEMOCLAW_CORPORATE_CA_B64", + "NEMOCLAW_UPSTREAM_ENDPOINT_URL", + ])("accepts %s as a reviewed source-gate ARG (#6901)", (reviewedArg) => { + const result = runGateWithFakeDocker("expected-failure-with-marker", (fixtureRoot) => + fs.appendFileSync(path.join(fixtureRoot, reviewedDockerfiles[0]), `\nARG ${reviewedArg}\n`), + ); expect(result.status, result.stderr).toBe(0); - expect(fs.readFileSync(checkPath, "utf8")).toContain("NEMOCLAW_UPSTREAM_ENDPOINT_URL"); expect(result.calls).toContain("--file agents/langchain-deepagents-code/Dockerfile"); }); diff --git a/test/mcp-tool-discovery-image-contract.test.ts b/test/mcp-tool-discovery-image-contract.test.ts new file mode 100644 index 00000000000..2df1511c6be --- /dev/null +++ b/test/mcp-tool-discovery-image-contract.test.ts @@ -0,0 +1,28 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import path from "node:path"; +import { describe, expect, it } from "vitest"; + +const repoRoot = path.join(import.meta.dirname, ".."); +const runtimeRoot = "/usr/local/lib/nemoclaw/mcp-tool-discovery-runtime"; +const dockerfiles = [ + "Dockerfile", + "agents/hermes/Dockerfile", + "agents/langchain-deepagents-code/Dockerfile", +] as const; + +describe("MCP tool discovery image contract", () => { + it.each( + dockerfiles, + )("%s installs and probes the bundled runtime at its canonical path (#6901)", (relativePath) => { + const dockerfile = fs.readFileSync(path.join(repoRoot, relativePath), "utf8"); + + expect(dockerfile).toContain( + `COPY --from=mcp-tool-discovery-runtime /opt/mcp-tool-discovery-runtime/dist/ ${runtimeRoot}/`, + ); + expect(dockerfile).toContain(`node ${runtimeRoot}/mcp-tool-discovery.mjs`); + expect(dockerfile).not.toContain(`${runtimeRoot}/mcp-tool-discovery.ts`); + }); +}); diff --git a/test/onboard.test.ts b/test/onboard.test.ts index b929f1ef725..092af79bfc5 100644 --- a/test/onboard.test.ts +++ b/test/onboard.test.ts @@ -681,6 +681,11 @@ startGateway(null).catch(() => {}); expect(stagedDockerfile).toBe(path.join(buildCtx, "Dockerfile")); expect(fs.existsSync(path.join(buildCtx, "nemoclaw", "package-lock.json"))).toBe(true); expect(fs.existsSync(path.join(buildCtx, "nemoclaw", "src"))).toBe(true); + expect( + fs.existsSync( + path.join(buildCtx, "tools", "mcp-tool-discovery-runtime", "mcp-tool-discovery.ts"), + ), + ).toBe(true); expect(fs.existsSync(path.join(buildCtx, "nemoclaw-blueprint", ".venv"))).toBe(false); expect(fs.existsSync(path.join(buildCtx, "scripts", "nemoclaw-start.sh"))).toBe(true); expect(fs.existsSync(path.join(buildCtx, "scripts", "patch-openclaw-tool-catalog.mts"))).toBe( diff --git a/test/openclaw-final-image-layout.test.ts b/test/openclaw-final-image-layout.test.ts index fc2ac4acd14..fe139891c00 100644 --- a/test/openclaw-final-image-layout.test.ts +++ b/test/openclaw-final-image-layout.test.ts @@ -33,7 +33,7 @@ describe("OpenClaw final image layout", () => { }, { stage: "openclaw-runtime-payload", - copies: 19, + copies: 20, metadata: "/ /usr /usr/local /usr/local/bin /usr/local/lib /usr/local/lib/nemoclaw /usr/local/share /usr/local/share/nemoclaw /scripts", }, diff --git a/test/sandbox-build-context.test.ts b/test/sandbox-build-context.test.ts index 9fa7c6e4c06..aa84cdbfcd9 100644 --- a/test/sandbox-build-context.test.ts +++ b/test/sandbox-build-context.test.ts @@ -47,6 +47,21 @@ describe("sandbox build context staging", () => { ); } } + for (const fileName of [ + "package.json", + "package-lock.json", + "tsconfig.json", + "install-reviewed-runtime.sh", + "build-runtime.ts", + "mcp-tool-discovery.ts", + "tool-discovery-core.ts", + ]) { + writeFixture( + path.join("tools", "mcp-tool-discovery-runtime", fileName), + "fixture\n", + fileName === "install-reviewed-runtime.sh" ? 0o755 : 0o644, + ); + } for (const fileName of [ "package.json", "package-lock.json", @@ -209,6 +224,30 @@ describe("sandbox build context staging", () => { } } + function expectStagedMcpToolDiscoveryRuntime(buildCtx: string, sourceRoot: string) { + const runtimeDir = path.join(buildCtx, "tools", "mcp-tool-discovery-runtime"); + expect(fs.readdirSync(runtimeDir).sort()).toEqual([ + "build-runtime.ts", + "install-reviewed-runtime.sh", + "mcp-tool-discovery.ts", + "package-lock.json", + "package.json", + "tool-discovery-core.ts", + "tsconfig.json", + ]); + for (const fileName of fs.readdirSync(runtimeDir)) { + expect(fs.readFileSync(path.join(runtimeDir, fileName), "utf8")).toBe( + fs.readFileSync( + path.join(sourceRoot, "tools", "mcp-tool-discovery-runtime", fileName), + "utf8", + ), + ); + expect((fs.statSync(path.join(runtimeDir, fileName)).mode & 0o777).toString(8)).toBe( + fileName === "install-reviewed-runtime.sh" ? "755" : "644", + ); + } + } + function expectStagedToolDisclosureContract(buildCtx: string) { expect(fs.existsSync(path.join(buildCtx, "src", "lib", "tool-disclosure.ts"))).toBe(true); } @@ -290,6 +329,7 @@ describe("sandbox build context staging", () => { const { buildCtx } = stageOptimizedSandboxBuildContext(sourceRoot, tmpDir); expectStagedBlueprintModes(buildCtx); expectStagedOpenClawRuntimeGraphs(buildCtx, sourceRoot); + expectStagedMcpToolDiscoveryRuntime(buildCtx, sourceRoot); expectStagedToolDisclosureContract(buildCtx); } finally { fs.rmSync(sourceRoot, { recursive: true, force: true }); @@ -320,6 +360,7 @@ describe("sandbox build context staging", () => { const { buildCtx } = stageLegacySandboxBuildContext(sourceRoot, tmpDir); expectStagedBlueprintModes(buildCtx); expectStagedOpenClawRuntimeGraphs(buildCtx, sourceRoot); + expectStagedMcpToolDiscoveryRuntime(buildCtx, sourceRoot); expectStagedToolDisclosureContract(buildCtx); } finally { fs.rmSync(sourceRoot, { recursive: true, force: true }); @@ -427,6 +468,7 @@ describe("sandbox build context staging", () => { fs.readFileSync(path.join(repoRoot, "ci", "npm-audit-exceptions.json"), "utf8"), ); expectStagedOpenClawRuntimeGraphs(buildCtx, repoRoot); + expectStagedMcpToolDiscoveryRuntime(buildCtx, repoRoot); expect(fs.existsSync(path.join(buildCtx, "nemoclaw-blueprint", ".venv"))).toBe(false); expect(fs.existsSync(path.join(buildCtx, "nemoclaw-blueprint", "blueprint.yaml"))).toBe(true); expect( diff --git a/tools/e2e/live-vitest-invocation.mts b/tools/e2e/live-vitest-invocation.mts index 8fd72a6e871..64ccd7d7324 100644 --- a/tools/e2e/live-vitest-invocation.mts +++ b/tools/e2e/live-vitest-invocation.mts @@ -20,9 +20,15 @@ const { spawnExitCode } = processExit; export const LIVE_VITEST_PROJECT = "e2e-live"; export const LIVE_TEST_ROOT = "test/e2e/live/"; export const RISK_SIGNAL_REPORTER = "test/e2e/risk-signal-reporter.ts"; +export const MCP_BRIDGE_TEST_PATH = "test/e2e/live/mcp-bridge.test.ts"; const SHELL_METACHARACTER = /[^A-Za-z0-9_./^$=:@+-]/u; const TEST_PATH_PATTERN = /^[A-Za-z0-9_./-]+$/u; +const MCP_BRIDGE_SELECTOR_BY_AGENT = { + deepagents: "^mcp-bridge-deepagents$", + hermes: "^mcp-bridge-hermes$", + openclaw: "^mcp-bridge$", +} as const; export interface LiveVitestInvocation { testPath: string | undefined; @@ -120,6 +126,30 @@ export function validateLiveSelector(selector: string | undefined): string | und return value; } +export function resolveLiveSelector( + testPath: string, + selector: string | undefined, + env: NodeJS.ProcessEnv = process.env, +): string | undefined { + const validated = validateLiveSelector(selector); + if (testPath !== MCP_BRIDGE_TEST_PATH) return validated; + + // Exact-head E2E executes trusted base-branch YAML with this helper from the + // tested checkout, so keep the reviewed shard mapping effective pre-merge. + const agent = env.NEMOCLAW_MCP_BRIDGE_AGENT ?? "openclaw"; + const expected = + MCP_BRIDGE_SELECTOR_BY_AGENT[agent as keyof typeof MCP_BRIDGE_SELECTOR_BY_AGENT]; + if (!expected) { + throw new Error(`unsupported NEMOCLAW_MCP_BRIDGE_AGENT ${JSON.stringify(agent)}`); + } + if (validated && validated !== expected) { + throw new Error( + `MCP bridge selector ${JSON.stringify(validated)} does not match agent ${JSON.stringify(agent)}`, + ); + } + return expected; +} + export function buildLiveVitestArgs(invocation: LiveVitestInvocation): string[] { const project = validateLiveProject(invocation.project); const testPath = validateLiveTestPath(invocation.testPath); @@ -143,21 +173,30 @@ function spawnResultExitCode(result: LiveVitestSpawnResult): number { return spawnExitCode(result); } -export function runLiveVitestCli(cliArgs: string[], spawn: LiveVitestSpawner = spawnSync): number { +export function runLiveVitestCli( + cliArgs: string[], + spawn: LiveVitestSpawner = spawnSync, + env: NodeJS.ProcessEnv = process.env, +): number { const invocation = parseLiveVitestArgs(cliArgs); const testPath = validateLiveTestPath(invocation.testPath); - const argv = buildLiveVitestArgs({ ...invocation, testPath }); + const selector = resolveLiveSelector(testPath, invocation.selector, env); + const argv = buildLiveVitestArgs({ ...invocation, testPath, selector }); return spawnResultExitCode(spawn("npx", argv, { stdio: "inherit" })); } -export function runLiveVitestCommand(argv: string[], spawn: LiveVitestSpawner = spawnSync): number { +export function runLiveVitestCommand( + argv: string[], + spawn: LiveVitestSpawner = spawnSync, + env: NodeJS.ProcessEnv = process.env, +): number { const [command, ...cliArgs] = argv; if (command !== "run") { throw new Error( `unsupported live Vitest command ${JSON.stringify(command ?? "")}; expected "run"`, ); } - return runLiveVitestCli(cliArgs, spawn); + return runLiveVitestCli(cliArgs, spawn, env); } if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { diff --git a/tools/e2e/mcp-bridge-runtime-compatibility.mts b/tools/e2e/mcp-bridge-runtime-compatibility.mts index 3c4dd603931..ca5ecef9841 100644 --- a/tools/e2e/mcp-bridge-runtime-compatibility.mts +++ b/tools/e2e/mcp-bridge-runtime-compatibility.mts @@ -6,6 +6,8 @@ import path from "node:path"; import { pathToFileURL } from "node:url"; import * as importedMcpBridgeValidation from "../../src/lib/actions/sandbox/mcp-bridge-validation.ts"; +import type { E2eRiskSignal } from "./risk-signal.ts"; +import * as importedRiskSignal from "./risk-signal.ts"; // The root TypeScript package is exposed as CJS under the exact `node --import // tsx` / `npx tsx` workflow execution mode, but as an ESM namespace under @@ -22,6 +24,12 @@ const { MCP_CREDENTIAL_BOUNDARY_OPENSHELL_VERSION, McpCredentialBoundaryRuntimeVersionError, } = mcpBridgeValidation; +const riskSignal = ( + "default" in importedRiskSignal && importedRiskSignal.default + ? importedRiskSignal.default + : importedRiskSignal +) as typeof import("./risk-signal.ts"); +const { configuredRiskSignalEnvironment, writeRiskSignalCounts } = riskSignal; export const MCP_BRIDGE_RUNTIME_COMPATIBILITY_ARTIFACT = "openshell-runtime-compatibility.json"; @@ -129,6 +137,22 @@ export function recordMcpBridgeRuntimeCompatibility( } } +export function recordExpectedMismatchRiskSignal( + result: McpBridgeRuntimeCompatibilityResult, + env: NodeJS.ProcessEnv = process.env, + resolveHead?: (workspace: string) => string, +): E2eRiskSignal | null { + if (result.mode !== "expected-version-mismatch") return null; + const environment = configuredRiskSignalEnvironment(env, resolveHead); + if (!environment) return null; + return writeRiskSignalCounts( + environment, + { passed: 1, failed: 0, skipped: 0, pending: 0 }, + 0, + "passed", + ); +} + if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { try { const artifactDirectory = process.env.E2E_ARTIFACT_DIR; @@ -142,6 +166,7 @@ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) githubOutputPath, githubStepSummaryPath: process.env.GITHUB_STEP_SUMMARY, }); + recordExpectedMismatchRiskSignal(result); if (result.mode === "expected-version-mismatch") { console.log( "::notice title=OpenShell dev compatibility::The installed OpenShell runtime is outside the reviewed credential boundary; full MCP lifecycle was not run. See the structured compatibility artifact for version evidence.", diff --git a/tools/e2e/mcp-workflow-boundary.mts b/tools/e2e/mcp-workflow-boundary.mts index aff7e74d07e..29f2c377770 100644 --- a/tools/e2e/mcp-workflow-boundary.mts +++ b/tools/e2e/mcp-workflow-boundary.mts @@ -19,6 +19,14 @@ const DEV_COMPATIBILITY_TOOL = "tools/e2e/mcp-bridge-runtime-compatibility.mts"; const CREDENTIAL_WINDOW_ID = "openshell-credential-generation-window"; const CREDENTIAL_WINDOW_FILE = `test/e2e/live/${CREDENTIAL_WINDOW_ID}.test.ts`; const CREDENTIAL_WINDOW_SHARD = "deepagents"; +const MCP_TEST_SELECTOR_CASE = [ + 'case "$NEMOCLAW_MCP_BRIDGE_AGENT" in', + " openclaw) mcp_test_selector='^mcp-bridge$' ;;", + " hermes) mcp_test_selector='^mcp-bridge-hermes$' ;;", + " deepagents) mcp_test_selector='^mcp-bridge-deepagents$' ;;", + ' *) echo "::error::Unsupported MCP bridge agent: $NEMOCLAW_MCP_BRIDGE_AGENT" >&2; exit 1 ;;', + "esac", +].join("\n"); const STABLE_RELEASE_SOURCE_SHA = "3dee5570a46076a57a3b056f35f35ebc0861ac85"; const STABLE_RELEASE_SUPERVISOR_INDEX = "f4226253a3525c3832adac5b38b419a0f27d1e915effe565b5885e20f93cd5e9"; @@ -437,6 +445,18 @@ function validateJobExecution( "tools/e2e/live-vitest-invocation.mts run --test-path", `${jobName} must publish canonical risk-signal evidence`, ); + requireContains( + errors, + run.run, + MCP_TEST_SELECTOR_CASE, + `${jobName} must map each MCP agent shard to its exact live test selector`, + ); + requireContains( + errors, + run.run, + '--selector "$mcp_test_selector"', + `${jobName} must pass its exact MCP agent selector to the live test`, + ); if (jobName === "mcp-bridge") { const riskReporter = "--reporter=test/e2e/risk-signal-reporter.ts"; const reporterCount = asString(run.run).split(riskReporter).length - 1; diff --git a/tools/e2e/risk-signal.ts b/tools/e2e/risk-signal.ts index db1ab845a00..62347663034 100644 --- a/tools/e2e/risk-signal.ts +++ b/tools/e2e/risk-signal.ts @@ -1,6 +1,14 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { execFileSync } from "node:child_process"; +import fs from "node:fs"; +import path from "node:path"; + +import { readPrivateRegularFile, writePrivateRegularFile } from "./private-file.mts"; + +export const RISK_SIGNAL_FILE = "risk-signal.json"; + export type E2eRiskSignal = { version: 1; jobId: string; @@ -16,3 +24,125 @@ export type E2eRiskSignal = { unhandledErrors: number; runReason: "passed" | "failed" | "interrupted"; }; + +export type RiskSignalEnvironment = { + artifactDir: string; + jobId: string; + shardId: string; + expectedSha: string; + testedSha: string; + planHash: string; + correlationId: string; +}; + +export type RiskSignalCounts = Pick; + +const SHA_PATTERN = /^[a-f0-9]{40}$/u; +const HASH_PATTERN = /^[a-f0-9]{64}$/u; +const CORRELATION_PATTERN = + /^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/u; +const JOB_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_-]*$/u; +const SHARD_PATTERN = /^(?:default|[A-Za-z0-9][A-Za-z0-9_-]*)$/u; + +function checkedOutSha(workspace: string): string { + return execFileSync("git", ["rev-parse", "--verify", "HEAD"], { + cwd: workspace, + encoding: "utf8", + killSignal: "SIGKILL", + stdio: ["ignore", "pipe", "pipe"], + timeout: 5_000, + }).trim(); +} + +export function configuredRiskSignalEnvironment( + env: NodeJS.ProcessEnv, + resolveHead: (workspace: string) => string = checkedOutSha, +): RiskSignalEnvironment | null { + if (!env.NEMOCLAW_E2E_EXPECTED_SHA) return null; + const values = { + artifactDir: env.E2E_ARTIFACT_DIR ?? "", + jobId: env.E2E_TARGET_ID ?? "", + shardId: env.NEMOCLAW_E2E_SHARD ?? "", + expectedSha: env.NEMOCLAW_E2E_EXPECTED_SHA, + planHash: env.NEMOCLAW_E2E_PLAN_HASH ?? "", + correlationId: env.NEMOCLAW_E2E_CORRELATION_ID ?? "", + }; + if (!values.artifactDir) throw new Error("risk signal requires E2E_ARTIFACT_DIR"); + if (!JOB_PATTERN.test(values.jobId)) throw new Error("risk signal requires a safe E2E_TARGET_ID"); + if (!SHARD_PATTERN.test(values.shardId)) { + throw new Error("risk signal requires a safe shard id"); + } + if (!SHA_PATTERN.test(values.expectedSha)) { + throw new Error("risk signal requires a 40-character lowercase expected SHA"); + } + if (!HASH_PATTERN.test(values.planHash)) { + throw new Error("risk signal requires a 64-character lowercase plan hash"); + } + if (!CORRELATION_PATTERN.test(values.correlationId)) { + throw new Error("risk signal requires a lowercase UUIDv4 correlation id"); + } + const testedSha = resolveHead(env.GITHUB_WORKSPACE ?? process.cwd()); + if (!SHA_PATTERN.test(testedSha) || testedSha !== values.expectedSha) { + throw new Error("risk signal checked-out HEAD does not match the expected SHA"); + } + return { ...values, testedSha }; +} + +function mergeSignal(previous: E2eRiskSignal | null, current: E2eRiskSignal): E2eRiskSignal { + if (!previous) return current; + if ( + previous.version !== current.version || + previous.jobId !== current.jobId || + previous.shardId !== current.shardId || + previous.expectedSha !== current.expectedSha || + previous.testedSha !== current.testedSha || + previous.planHash !== current.planHash || + previous.correlationId !== current.correlationId + ) { + throw new Error("risk signal metadata changed between invocations"); + } + return { + ...current, + passed: previous.passed + current.passed, + failed: previous.failed + current.failed, + skipped: previous.skipped + current.skipped, + pending: previous.pending + current.pending, + unhandledErrors: previous.unhandledErrors + current.unhandledErrors, + runReason: + previous.runReason === "failed" || current.runReason === "failed" + ? "failed" + : previous.runReason === "interrupted" || current.runReason === "interrupted" + ? "interrupted" + : "passed", + }; +} + +function readPrevious(file: string): E2eRiskSignal | null { + const contents = readPrivateRegularFile(file, { allowMissing: true, maxBytes: 64 * 1024 }); + return contents === null ? null : (JSON.parse(contents) as E2eRiskSignal); +} + +export function writeRiskSignalCounts( + environment: RiskSignalEnvironment, + counts: RiskSignalCounts, + unhandledErrors: number, + runReason: E2eRiskSignal["runReason"], +): E2eRiskSignal { + const signal: E2eRiskSignal = { + version: 1, + jobId: environment.jobId, + shardId: environment.shardId, + expectedSha: environment.expectedSha, + testedSha: environment.testedSha, + planHash: environment.planHash, + correlationId: environment.correlationId, + ...counts, + unhandledErrors, + runReason, + }; + fs.mkdirSync(environment.artifactDir, { recursive: true }); + const file = path.join(environment.artifactDir, RISK_SIGNAL_FILE); + const merged = mergeSignal(readPrevious(file), signal); + writePrivateRegularFile(file, `${JSON.stringify(merged, null, 2)}\n`); + return merged; +} diff --git a/tools/mcp-tool-discovery-runtime/build-runtime.ts b/tools/mcp-tool-discovery-runtime/build-runtime.ts new file mode 100644 index 00000000000..39c8e86f447 --- /dev/null +++ b/tools/mcp-tool-discovery-runtime/build-runtime.ts @@ -0,0 +1,81 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import path from "node:path"; + +import { build } from "esbuild"; + +interface PackageLicense { + name: string; + version: string; + declaredLicense: string; + text: string; +} + +const outputDir = path.resolve("dist"); +const bundlePath = path.join(outputDir, "mcp-tool-discovery.mjs"); +const licenseFileNames = ["LICENSE", "LICENSE.md", "LICENSE.txt", "license", "license.md"]; + +function packageNameFromInput(inputPath: string): string | null { + const normalized = inputPath.replaceAll("\\", "/"); + const marker = "node_modules/"; + const markerIndex = normalized.lastIndexOf(marker); + if (markerIndex < 0) return null; + const segments = normalized.slice(markerIndex + marker.length).split("/"); + if (segments[0]?.startsWith("@")) return `${segments[0]}/${segments[1]}`; + return segments[0] || null; +} + +function readPackageLicense(packageName: string): PackageLicense { + const packageDir = path.resolve("node_modules", packageName); + const manifest = JSON.parse(fs.readFileSync(path.join(packageDir, "package.json"), "utf8")) as { + version?: unknown; + license?: unknown; + }; + if (typeof manifest.version !== "string" || typeof manifest.license !== "string") { + throw new Error(`bundled package ${packageName} has invalid license metadata`); + } + const licenseFileName = licenseFileNames.find((candidate) => + fs.existsSync(path.join(packageDir, candidate)), + ); + if (!licenseFileName) throw new Error(`bundled package ${packageName} has no license file`); + return { + name: packageName, + version: manifest.version, + declaredLicense: manifest.license, + text: fs.readFileSync(path.join(packageDir, licenseFileName), "utf8").trim(), + }; +} + +fs.rmSync(outputDir, { recursive: true, force: true }); +const result = await build({ + entryPoints: ["mcp-tool-discovery.ts"], + bundle: true, + platform: "node", + target: "node22", + format: "esm", + outfile: bundlePath, + metafile: true, +}); + +const bundledPackages = [...new Set(Object.keys(result.metafile.inputs).map(packageNameFromInput))] + .filter((name): name is string => name !== null) + .sort(); +if (!bundledPackages.includes("@modelcontextprotocol/sdk")) { + throw new Error("the MCP SDK was not present in the bundled input graph"); +} + +const notices = bundledPackages.map(readPackageLicense); +const noticeText = [ + "Third-party licenses for the NemoClaw MCP tool discovery runtime bundle", + "", + ...notices.flatMap(({ name, version, declaredLicense, text }) => [ + "================================================================================", + `${name}@${version} (${declaredLicense})`, + "================================================================================", + text, + "", + ]), +].join("\n"); +fs.writeFileSync(path.join(outputDir, "THIRD_PARTY_LICENSES.txt"), noticeText, "utf8"); diff --git a/tools/mcp-tool-discovery-runtime/dependency-review.md b/tools/mcp-tool-discovery-runtime/dependency-review.md new file mode 100644 index 00000000000..2dc820d4153 --- /dev/null +++ b/tools/mcp-tool-discovery-runtime/dependency-review.md @@ -0,0 +1,51 @@ + + + +# MCP tool discovery runtime dependency review + +The shared image runtime uses the official `@modelcontextprotocol/sdk` client so all NemoClaw agent images follow the same Streamable HTTP initialization, protocol-version, session, SSE, pagination, and cleanup behavior. It is not an agent adapter and never invokes a discovered tool. + +## Reviewed pin + +- Package: `@modelcontextprotocol/sdk@1.29.0` +- Registry tarball: `https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.29.0.tgz` +- Integrity: `sha512-zo37mZA9hJWpULgkRpowewez1y6ML5GsXJPY8FI0tBBCd77HEvza4jDqRKOXgHNn867PVGCyTdzqpz0izu5ZjQ==` +- License: MIT +- Locked production graph: `package-lock.json` (lockfile version 3) +- Build-only tools: `typescript@6.0.3`, `@types/node@25.5.2`, and `esbuild@0.27.4` (not copied into the final image) +- Security overrides: `@hono/node-server@2.0.11` and `fast-uri@3.1.4` + +The same SDK version and integrity are already present in the separately locked OpenClaw `mcporter` dependency graph. This runtime keeps a direct lock because Hermes and LangChain Deep Agents Code must not depend on OpenClaw's adapter package. +The SDK's client entry points do not bundle its Hono server adapter or AJV's URI validator into the names-only runtime, but those transitive packages remain in the install graph that the image audits. The exact overrides keep that reviewed graph clear of `GHSA-frvp-7c67-39w9` and `GHSA-v2hh-gcrm-f6hx` without changing the SDK client pin. + +## Build and audit contract + +Every agent image installs this committed graph with `npm ci --ignore-scripts` through the same reviewed installer, verifies registry signatures, typechecks the package against the real SDK types, and produces a single Node.js ESM bundle. Only that bundle and a deterministic notice containing the license text for every package in esbuild's actual input graph are copied into the final image; the build dependency tree is discarded with the builder stage. This preserves the official SDK implementation and its license obligations while avoiding a large production layer composed of thousands of small package files. +The installer applies the existing public corporate CA build argument to npm TLS when present. +The root CLI TypeScript project excludes only this dependency-owning image entry point; the image package's dedicated `tsconfig.json` is the source-of-truth type gate, while the dependency-free core remains covered by the root project and host tests. +The image build requires a clean low-severity production advisory audit, verified npm registry signatures, a root-owned non-writable bundled runtime, and an executable invalid-input contract check before the image can complete. + +Review evidence on 2026-07-14: + +- `npm audit --omit=dev --audit-level=low`: 0 vulnerabilities +- Pre-build `npm audit signatures`: 98 packages with verified registry signatures and 10 packages with verified attestations + +Refresh evidence on 2026-07-24: + +- `npm audit --omit=dev --audit-level=low`: 0 vulnerabilities +- Pre-build `npm audit signatures`: 98 packages with verified registry signatures and 11 packages with verified attestations + +## Updating + +Regenerate and review the graph explicitly: + +```console +$ npm --prefix tools/mcp-tool-discovery-runtime install --package-lock-only --ignore-scripts +$ npm --prefix tools/mcp-tool-discovery-runtime ci --ignore-scripts +$ npm --prefix tools/mcp-tool-discovery-runtime audit signatures +$ npm --prefix tools/mcp-tool-discovery-runtime run typecheck +$ npm --prefix tools/mcp-tool-discovery-runtime run bundle +$ npm --prefix tools/mcp-tool-discovery-runtime audit --omit=dev --audit-level=low +``` + +Update this review, the exact package pin, and the committed lock together. Do not replace the lock with a floating install or reuse an agent-specific dependency tree. diff --git a/tools/mcp-tool-discovery-runtime/install-reviewed-runtime.sh b/tools/mcp-tool-discovery-runtime/install-reviewed-runtime.sh new file mode 100755 index 00000000000..35064622b27 --- /dev/null +++ b/tools/mcp-tool-discovery-runtime/install-reviewed-runtime.sh @@ -0,0 +1,49 @@ +#!/bin/sh +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +set -eu + +script_dir=$( + CDPATH='' + cd -- "$(dirname -- "$0")" + pwd +) +cd "$script_dir" + +if [ -n "${NEMOCLAW_CORPORATE_CA_B64:-}" ]; then + command -v base64 >/dev/null 2>&1 || { + echo "[nemoclaw] base64 is required to decode the corporate CA for the MCP discovery runtime" >&2 + exit 1 + } + install -d -m 0755 /usr/local/share/nemoclaw + decoded=/tmp/nemoclaw-mcp-runtime-ca.decoded + ca_file=/usr/local/share/nemoclaw/mcp-runtime-corporate-ca.pem + if ! printf '%s' "$NEMOCLAW_CORPORATE_CA_B64" | base64 --decode >"$decoded" 2>/dev/null; then + echo "[nemoclaw] the corporate CA for the MCP discovery runtime is not valid base64" >&2 + exit 1 + fi + awk '/-----BEGIN CERTIFICATE-----/{f=1} f{print} /-----END CERTIFICATE-----/{f=0}' \ + "$decoded" >"$ca_file" + rm -f "$decoded" + if ! node -e ' + const fs = require("node:fs"); + const { X509Certificate } = require("node:crypto"); + const pem = fs.readFileSync(process.argv[1], "utf8"); + const certificates = pem.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g); + if (!certificates?.length) process.exit(1); + for (const certificate of certificates) new X509Certificate(certificate); + ' "$ca_file" >/dev/null 2>&1; then + echo "[nemoclaw] the corporate CA for the MCP discovery runtime is not a valid X.509 bundle" >&2 + exit 1 + fi + chown root:root "$ca_file" + chmod 0444 "$ca_file" + export NODE_EXTRA_CA_CERTS="$ca_file" +fi + +npm ci --ignore-scripts --no-audit --no-fund --no-progress +npm audit signatures +npm run typecheck +npm run bundle +npm audit --omit=dev --audit-level=low diff --git a/tools/mcp-tool-discovery-runtime/mcp-tool-discovery.ts b/tools/mcp-tool-discovery-runtime/mcp-tool-discovery.ts new file mode 100644 index 00000000000..8a9a54caa65 --- /dev/null +++ b/tools/mcp-tool-discovery-runtime/mcp-tool-discovery.ts @@ -0,0 +1,79 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; + +import { + buildMcpToolDiscoveryAuthorizationPlaceholder, + createBoundedMcpFetch, + MCP_TOOL_DISCOVERY_LIMITS, + MCP_TOOL_DISCOVERY_PROTOCOL, + type McpToolDiscoveryResult, + normalizeMcpToolPage, + parseMcpToolDiscoveryArguments, + runMcpToolDiscoverySession, +} from "./tool-discovery-core.ts"; + +function writeResult(result: McpToolDiscoveryResult): void { + process.stdout.write(`${JSON.stringify({ protocol: MCP_TOOL_DISCOVERY_PROTOCOL, ...result })}\n`); +} + +async function main(): Promise { + let runtimeArguments: { url: URL; credentialEnv: string }; + try { + runtimeArguments = parseMcpToolDiscoveryArguments(process.argv.slice(2)); + } catch { + writeResult({ + ok: false, + count: 0, + tools: [], + truncated: false, + detail: "tool discovery received invalid runtime arguments", + }); + return; + } + + const deadlineSignal = AbortSignal.timeout(MCP_TOOL_DISCOVERY_LIMITS.maxTotalTimeMs); + const boundedFetch = createBoundedMcpFetch(globalThis.fetch, deadlineSignal); + const transport = new StreamableHTTPClientTransport(runtimeArguments.url, { + fetch: boundedFetch, + requestInit: { + headers: { + authorization: buildMcpToolDiscoveryAuthorizationPlaceholder( + runtimeArguments.credentialEnv, + ), + }, + redirect: "manual", + }, + reconnectionOptions: { + maxReconnectionDelay: 1, + initialReconnectionDelay: 1, + reconnectionDelayGrowFactor: 1, + maxRetries: 0, + }, + }); + const client = new Client( + { name: "nemoclaw-mcp-tool-discovery", version: "1.0.0" }, + { capabilities: {} }, + ); + const requestOptions = { + signal: deadlineSignal, + timeout: MCP_TOOL_DISCOVERY_LIMITS.maxRequestTimeMs, + maxTotalTimeout: MCP_TOOL_DISCOVERY_LIMITS.maxTotalTimeMs, + }; + + await runMcpToolDiscoverySession({ + connect: () => client.connect(transport, requestOptions), + loadPage: async (cursor) => { + const page = await client.listTools(cursor ? { cursor } : undefined, requestOptions); + return normalizeMcpToolPage(page); + }, + hasSession: () => Boolean(transport.sessionId), + terminateSession: () => transport.terminateSession(), + close: () => client.close(), + publishResult: writeResult, + }); +} + +await main(); diff --git a/tools/mcp-tool-discovery-runtime/package-lock.json b/tools/mcp-tool-discovery-runtime/package-lock.json new file mode 100644 index 00000000000..36bd2b52873 --- /dev/null +++ b/tools/mcp-tool-discovery-runtime/package-lock.json @@ -0,0 +1,1697 @@ +{ + "name": "nemoclaw-mcp-tool-discovery-runtime", + "version": "0.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "nemoclaw-mcp-tool-discovery-runtime", + "version": "0.0.0", + "license": "Apache-2.0", + "dependencies": { + "@modelcontextprotocol/sdk": "1.29.0" + }, + "devDependencies": { + "@types/node": "25.5.2", + "esbuild": "0.27.4", + "typescript": "6.0.3" + }, + "engines": { + "node": ">=22.19.0" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.4.tgz", + "integrity": "sha512-cQPwL2mp2nSmHHJlCyoXgHGhbEPMrEEU5xhkcy3Hs/O7nGZqEpZ2sUtLaL9MORLtDfRvVl2/3PAuEkYZH0Ty8Q==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.27.4.tgz", + "integrity": "sha512-X9bUgvxiC8CHAGKYufLIHGXPJWnr0OCdR0anD2e21vdvgCI8lIfqFbnoeOz7lBjdrAGUhqLZLcQo6MLhTO2DKQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.27.4.tgz", + "integrity": "sha512-gdLscB7v75wRfu7QSm/zg6Rx29VLdy9eTr2t44sfTW7CxwAtQghZ4ZnqHk3/ogz7xao0QAgrkradbBzcqFPasw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.27.4.tgz", + "integrity": "sha512-PzPFnBNVF292sfpfhiyiXCGSn9HZg5BcAz+ivBuSsl6Rk4ga1oEXAamhOXRFyMcjwr2DVtm40G65N3GLeH1Lvw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.27.4.tgz", + "integrity": "sha512-b7xaGIwdJlht8ZFCvMkpDN6uiSmnxxK56N2GDTMYPr2/gzvfdQN8rTfBsvVKmIVY/X7EM+/hJKEIbbHs9oA4tQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.27.4.tgz", + "integrity": "sha512-sR+OiKLwd15nmCdqpXMnuJ9W2kpy0KigzqScqHI3Hqwr7IXxBp3Yva+yJwoqh7rE8V77tdoheRYataNKL4QrPw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.27.4.tgz", + "integrity": "sha512-jnfpKe+p79tCnm4GVav68A7tUFeKQwQyLgESwEAUzyxk/TJr4QdGog9sqWNcUbr/bZt/O/HXouspuQDd9JxFSw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.27.4.tgz", + "integrity": "sha512-2kb4ceA/CpfUrIcTUl1wrP/9ad9Atrp5J94Lq69w7UwOMolPIGrfLSvAKJp0RTvkPPyn6CIWrNy13kyLikZRZQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.27.4.tgz", + "integrity": "sha512-aBYgcIxX/wd5n2ys0yESGeYMGF+pv6g0DhZr3G1ZG4jMfruU9Tl1i2Z+Wnj9/KjGz1lTLCcorqE2viePZqj4Eg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.27.4.tgz", + "integrity": "sha512-7nQOttdzVGth1iz57kxg9uCz57dxQLHWxopL6mYuYthohPKEK0vU0C3O21CcBK6KDlkYVcnDXY099HcCDXd9dA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.27.4.tgz", + "integrity": "sha512-oPtixtAIzgvzYcKBQM/qZ3R+9TEUd1aNJQu0HhGyqtx6oS7qTpvjheIWBbes4+qu1bNlo2V4cbkISr8q6gRBFA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.27.4.tgz", + "integrity": "sha512-8mL/vh8qeCoRcFH2nM8wm5uJP+ZcVYGGayMavi8GmRJjuI3g1v6Z7Ni0JJKAJW+m0EtUuARb6Lmp4hMjzCBWzA==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.27.4.tgz", + "integrity": "sha512-1RdrWFFiiLIW7LQq9Q2NES+HiD4NyT8Itj9AUeCl0IVCA459WnPhREKgwrpaIfTOe+/2rdntisegiPWn/r/aAw==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.27.4.tgz", + "integrity": "sha512-tLCwNG47l3sd9lpfyx9LAGEGItCUeRCWeAx6x2Jmbav65nAwoPXfewtAdtbtit/pJFLUWOhpv0FpS6GQAmPrHA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.27.4.tgz", + "integrity": "sha512-BnASypppbUWyqjd1KIpU4AUBiIhVr6YlHx/cnPgqEkNoVOhHg+YiSVxM1RLfiy4t9cAulbRGTNCKOcqHrEQLIw==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.27.4.tgz", + "integrity": "sha512-+eUqgb/Z7vxVLezG8bVB9SfBie89gMueS+I0xYh2tJdw3vqA/0ImZJ2ROeWwVJN59ihBeZ7Tu92dF/5dy5FttA==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.27.4.tgz", + "integrity": "sha512-S5qOXrKV8BQEzJPVxAwnryi2+Iq5pB40gTEIT69BQONqR7JH1EPIcQ/Uiv9mCnn05jff9umq/5nqzxlqTOg9NA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.4.tgz", + "integrity": "sha512-xHT8X4sb0GS8qTqiwzHqpY00C95DPAq7nAwX35Ie/s+LO9830hrMd3oX0ZMKLvy7vsonee73x0lmcdOVXFzd6Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.27.4.tgz", + "integrity": "sha512-RugOvOdXfdyi5Tyv40kgQnI0byv66BFgAqjdgtAKqHoZTbTF2QqfQrFwa7cHEORJf6X2ht+l9ABLMP0dnKYsgg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.4.tgz", + "integrity": "sha512-2MyL3IAaTX+1/qP0O1SwskwcwCoOI4kV2IBX1xYnDDqthmq5ArrW94qSIKCAuRraMgPOmG0RDTA74mzYNQA9ow==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.27.4.tgz", + "integrity": "sha512-u8fg/jQ5aQDfsnIV6+KwLOf1CmJnfu1ShpwqdwC0uA7ZPwFws55Ngc12vBdeUdnuWoQYx/SOQLGDcdlfXhYmXQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.4.tgz", + "integrity": "sha512-JkTZrl6VbyO8lDQO3yv26nNr2RM2yZzNrNHEsj9bm6dOwwu9OYN28CjzZkH57bh4w0I2F7IodpQvUAEd1mbWXg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.27.4.tgz", + "integrity": "sha512-/gOzgaewZJfeJTlsWhvUEmUG4tWEY2Spp5M20INYRg2ZKl9QPO3QEEgPeRtLjEWSW8FilRNacPOg8R1uaYkA6g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.27.4.tgz", + "integrity": "sha512-Z9SExBg2y32smoDQdf1HRwHRt6vAHLXcxD2uGgO/v2jK7Y718Ix4ndsbNMU/+1Qiem9OiOdaqitioZwxivhXYg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.27.4.tgz", + "integrity": "sha512-DAyGLS0Jz5G5iixEbMHi5KdiApqHBWMGzTtMiJ72ZOLhbu/bzxgAe8Ue8CTS3n3HbIUHQz/L51yMdGMeoxXNJw==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.27.4.tgz", + "integrity": "sha512-+knoa0BDoeXgkNvvV1vvbZX4+hizelrkwmGJBdT17t8FNPwG2lKemmuMZlmaNQ3ws3DKKCxpb4zRZEIp3UxFCg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@hono/node-server": { + "version": "2.0.11", + "resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-2.0.11.tgz", + "integrity": "sha512-bjD221KPLoJTWUwso1J6fGKiTXEUFedG/s0visavY4zakFPkeGURMRNly+FhBHs7T8Dz4qHaZIMX9ZoJHSJtKA==", + "license": "MIT", + "engines": { + "node": ">=20" + }, + "peerDependencies": { + "hono": "^4" + } + }, + "node_modules/@modelcontextprotocol/sdk": { + "version": "1.29.0", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.29.0.tgz", + "integrity": "sha512-zo37mZA9hJWpULgkRpowewez1y6ML5GsXJPY8FI0tBBCd77HEvza4jDqRKOXgHNn867PVGCyTdzqpz0izu5ZjQ==", + "license": "MIT", + "dependencies": { + "@hono/node-server": "^1.19.9", + "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" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@cfworker/json-schema": "^4.1.1", + "zod": "^3.25 || ^4.0" + }, + "peerDependenciesMeta": { + "@cfworker/json-schema": { + "optional": true + }, + "zod": { + "optional": false + } + } + }, + "node_modules/@types/node": { + "version": "25.5.2", + "resolved": "https://registry.npmjs.org/@types/node/-/node-25.5.2.tgz", + "integrity": "sha512-tO4ZIRKNC+MDWV4qKVZe3Ql/woTnmHDr5JD8UI5hn2pwBrHEwOEMZK7WlNb5RKB6EoJ02gwmQS9OrjuFnZYdpg==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~7.18.0" + } + }, + "node_modules/accepts": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz", + "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==", + "license": "MIT", + "dependencies": { + "mime-types": "^3.0.0", + "negotiator": "^1.0.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/ajv": { + "version": "8.20.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz", + "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==", + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/ajv-formats": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz", + "integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==", + "license": "MIT", + "dependencies": { + "ajv": "^8.0.0" + }, + "peerDependencies": { + "ajv": "^8.0.0" + }, + "peerDependenciesMeta": { + "ajv": { + "optional": true + } + } + }, + "node_modules/body-parser": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.3.0.tgz", + "integrity": "sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==", + "license": "MIT", + "dependencies": { + "bytes": "^3.1.2", + "content-type": "^2.0.0", + "debug": "^4.4.3", + "http-errors": "^2.0.1", + "iconv-lite": "^0.7.2", + "on-finished": "^2.4.1", + "qs": "^6.15.2", + "raw-body": "^3.0.2", + "type-is": "^2.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/body-parser/node_modules/content-type": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.0.0.tgz", + "integrity": "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/content-disposition": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.1.0.tgz", + "integrity": "sha512-5jRCH9Z/+DRP7rkvY83B+yGIGX96OYdJmzngqnw2SBSxqCFPd0w2km3s5iawpGX8krnwSGmF0FW5Nhr0Hfai3g==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz", + "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==", + "license": "MIT", + "engines": { + "node": ">=6.6.0" + } + }, + "node_modules/cors": { + "version": "2.8.6", + "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.6.tgz", + "integrity": "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==", + "license": "MIT", + "dependencies": { + "object-assign": "^4", + "vary": "^1" + }, + "engines": { + "node": ">= 0.10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/cross-spawn": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "license": "MIT", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", + "license": "MIT" + }, + "node_modules/encodeurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz", + "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/esbuild": { + "version": "0.27.4", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.4.tgz", + "integrity": "sha512-Rq4vbHnYkK5fws5NF7MYTU68FPRE1ajX7heQ/8QXXWqNgqqJ/GkmmyxIzUnf2Sr/bakf8l54716CcMGHYhMrrQ==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.27.4", + "@esbuild/android-arm": "0.27.4", + "@esbuild/android-arm64": "0.27.4", + "@esbuild/android-x64": "0.27.4", + "@esbuild/darwin-arm64": "0.27.4", + "@esbuild/darwin-x64": "0.27.4", + "@esbuild/freebsd-arm64": "0.27.4", + "@esbuild/freebsd-x64": "0.27.4", + "@esbuild/linux-arm": "0.27.4", + "@esbuild/linux-arm64": "0.27.4", + "@esbuild/linux-ia32": "0.27.4", + "@esbuild/linux-loong64": "0.27.4", + "@esbuild/linux-mips64el": "0.27.4", + "@esbuild/linux-ppc64": "0.27.4", + "@esbuild/linux-riscv64": "0.27.4", + "@esbuild/linux-s390x": "0.27.4", + "@esbuild/linux-x64": "0.27.4", + "@esbuild/netbsd-arm64": "0.27.4", + "@esbuild/netbsd-x64": "0.27.4", + "@esbuild/openbsd-arm64": "0.27.4", + "@esbuild/openbsd-x64": "0.27.4", + "@esbuild/openharmony-arm64": "0.27.4", + "@esbuild/sunos-x64": "0.27.4", + "@esbuild/win32-arm64": "0.27.4", + "@esbuild/win32-ia32": "0.27.4", + "@esbuild/win32-x64": "0.27.4" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", + "license": "MIT" + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/eventsource": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-3.0.7.tgz", + "integrity": "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==", + "license": "MIT", + "dependencies": { + "eventsource-parser": "^3.0.1" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/eventsource-parser": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.1.0.tgz", + "integrity": "sha512-kJezFj9YFAMLeORyi7aCLxLbD5/qWMQnoMVlVPyHIll7lgRJCc3JVln9Vgl9nwQi0YkMnhdGTMNn7CkRRAptMg==", + "license": "MIT", + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/express": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/express/-/express-5.2.1.tgz", + "integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==", + "license": "MIT", + "dependencies": { + "accepts": "^2.0.0", + "body-parser": "^2.2.1", + "content-disposition": "^1.0.0", + "content-type": "^1.0.5", + "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.7", + "qs": "^6.14.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.0.1", + "vary": "^1.1.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/express-rate-limit": { + "version": "8.5.2", + "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.5.2.tgz", + "integrity": "sha512-5Kb34ipNX694DH48vN9irak1Qx30nb0PLYHXfJgw4YEjiC3ZEmZJhwOp+VfiCYwFzvFTdB9QkArYS5kXa2cx2A==", + "license": "MIT", + "dependencies": { + "ip-address": "^10.2.0" + }, + "engines": { + "node": ">= 16" + }, + "funding": { + "url": "https://github.com/sponsors/express-rate-limit" + }, + "peerDependencies": { + "express": ">= 4.11" + } + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "license": "MIT" + }, + "node_modules/fast-uri": { + "version": "3.1.4", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.4.tgz", + "integrity": "sha512-8JnbkQ4juDyvYs4mgFGQqg4yCYtFDtUtmp2QIQq11ZZe5CFQ5wcqm1rqDgAh/QdMySuBnPzMUiJUNZG5N/AiQw==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/finalhandler": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz", + "integrity": "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==", + "license": "MIT", + "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" + }, + "engines": { + "node": ">= 18.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz", + "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "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" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/hono": { + "version": "4.12.30", + "resolved": "https://registry.npmjs.org/hono/-/hono-4.12.30.tgz", + "integrity": "sha512-emn+JoJjrN9YTpRDS5it/UI2SO9BAE37T6I3d963RxcZ81G9A4pr2SZTEiiaiKbzx+NKRg5BZ89fCL7gCJCUog==", + "license": "MIT", + "engines": { + "node": ">=16.9.0" + } + }, + "node_modules/http-errors": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", + "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", + "license": "MIT", + "dependencies": { + "depd": "~2.0.0", + "inherits": "~2.0.4", + "setprototypeof": "~1.2.0", + "statuses": "~2.0.2", + "toidentifier": "~1.0.1" + }, + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/iconv-lite": { + "version": "0.7.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz", + "integrity": "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, + "node_modules/ip-address": { + "version": "10.2.0", + "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.2.0.tgz", + "integrity": "sha512-/+S6j4E9AHvW9SWMSEY9Xfy66O5PWvVEJ08O0y5JGyEKQpojb0K0GKpz/v5HJ/G0vi3D2sjGK78119oXZeE0qA==", + "license": "MIT", + "engines": { + "node": ">= 12" + } + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/is-promise": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz", + "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==", + "license": "MIT" + }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "license": "ISC" + }, + "node_modules/jose": { + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/jose/-/jose-6.2.3.tgz", + "integrity": "sha512-YYVDInQKFJfR/xa3ojUTl8c2KoTwiL1R5Wg9YCydwH0x0B9grbzlg5HC7mMjCtUJjbQ/YnGEZIhI5tCgfTb4Hw==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, + "node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "license": "MIT" + }, + "node_modules/json-schema-typed": { + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/json-schema-typed/-/json-schema-typed-8.0.2.tgz", + "integrity": "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA==", + "license": "BSD-2-Clause" + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/media-typer": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.0.tgz", + "integrity": "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/merge-descriptors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz", + "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/mime-db": { + "version": "1.54.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", + "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz", + "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==", + "license": "MIT", + "dependencies": { + "mime-db": "^1.54.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/negotiator": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz", + "integrity": "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-inspect": { + "version": "1.13.4", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "license": "ISC", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-to-regexp": { + "version": "8.4.2", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.4.2.tgz", + "integrity": "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/pkce-challenge": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/pkce-challenge/-/pkce-challenge-5.0.1.tgz", + "integrity": "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==", + "license": "MIT", + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/proxy-addr": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", + "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "license": "MIT", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/qs": { + "version": "6.15.3", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.15.3.tgz", + "integrity": "sha512-O9gl3zCl5h5blw1KGUzQKhA5oUXSl8rwUIM5o0S3nCXMliSvy5Dzx7/DJcI+SwgICv+IneSZwhBh1oSyEHA71A==", + "license": "BSD-3-Clause", + "dependencies": { + "es-define-property": "^1.0.1", + "side-channel": "^1.1.1" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/range-parser": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.3.0.tgz", + "integrity": "sha512-hek2mFQpPuI4E1BBKrSto+BU3e3x4xuarsbiwr3+lf7p44juvFMV0XFWQAP3xUyqXA4RrXLIoaSUGbSt056ZMw==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/raw-body": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.2.tgz", + "integrity": "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==", + "license": "MIT", + "dependencies": { + "bytes": "~3.1.2", + "http-errors": "~2.0.1", + "iconv-lite": "~0.7.0", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/require-from-string": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/router": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz", + "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "depd": "^2.0.0", + "is-promise": "^4.0.0", + "parseurl": "^1.3.3", + "path-to-regexp": "^8.0.0" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "license": "MIT" + }, + "node_modules/send": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz", + "integrity": "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==", + "license": "MIT", + "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" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/serve-static": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.1.tgz", + "integrity": "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==", + "license": "MIT", + "dependencies": { + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "parseurl": "^1.3.3", + "send": "^1.2.0" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "license": "ISC" + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "license": "MIT", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/side-channel": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz", + "integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==", + "license": "MIT", + "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" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz", + "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "license": "MIT", + "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" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/statuses": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", + "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "license": "MIT", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/type-is": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.1.0.tgz", + "integrity": "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==", + "license": "MIT", + "dependencies": { + "content-type": "^2.0.0", + "media-typer": "^1.1.0", + "mime-types": "^3.0.0" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/type-is/node_modules/content-type": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.0.0.tgz", + "integrity": "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/typescript": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-6.0.3.tgz", + "integrity": "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "7.18.2", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.18.2.tgz", + "integrity": "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==", + "dev": true, + "license": "MIT" + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "license": "ISC" + }, + "node_modules/zod": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.4.3.tgz", + "integrity": "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + }, + "node_modules/zod-to-json-schema": { + "version": "3.25.2", + "resolved": "https://registry.npmjs.org/zod-to-json-schema/-/zod-to-json-schema-3.25.2.tgz", + "integrity": "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA==", + "license": "ISC", + "peerDependencies": { + "zod": "^3.25.28 || ^4" + } + } + } +} diff --git a/tools/mcp-tool-discovery-runtime/package.json b/tools/mcp-tool-discovery-runtime/package.json new file mode 100644 index 00000000000..e5821f315d8 --- /dev/null +++ b/tools/mcp-tool-discovery-runtime/package.json @@ -0,0 +1,28 @@ +{ + "$comment": "SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\nSPDX-License-Identifier: Apache-2.0", + "name": "nemoclaw-mcp-tool-discovery-runtime", + "version": "0.0.0", + "private": true, + "type": "module", + "description": "Locked shared runtime for names-only managed MCP tool discovery", + "license": "Apache-2.0", + "dependencies": { + "@modelcontextprotocol/sdk": "1.29.0" + }, + "devDependencies": { + "@types/node": "25.5.2", + "esbuild": "0.27.4", + "typescript": "6.0.3" + }, + "overrides": { + "@hono/node-server": "2.0.11", + "fast-uri": "3.1.4" + }, + "engines": { + "node": ">=22.19.0" + }, + "scripts": { + "bundle": "node --experimental-strip-types build-runtime.ts", + "typecheck": "tsc -p tsconfig.json" + } +} diff --git a/tools/mcp-tool-discovery-runtime/tool-discovery-core.ts b/tools/mcp-tool-discovery-runtime/tool-discovery-core.ts new file mode 100644 index 00000000000..aa3d54143cd --- /dev/null +++ b/tools/mcp-tool-discovery-runtime/tool-discovery-core.ts @@ -0,0 +1,325 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +export const MCP_TOOL_DISCOVERY_PROTOCOL = 1; + +export const MCP_TOOL_DISCOVERY_LIMITS = { + maxTotalTimeMs: 10_000, + maxRequestTimeMs: 5_000, + maxResponseBytes: 1_048_576, + maxPages: 20, + maxTools: 500, + maxCursorBytes: 2_048, + maxToolNameBytes: 256, +} as const; + +export interface McpToolDiscoveryResult { + ok: boolean; + count: number; + tools: string[]; + truncated: boolean; + detail?: string; +} + +export interface McpToolPage { + tools: Array<{ name: string }>; + nextCursor?: string; +} + +export interface McpToolDiscoveryArguments { + url: URL; + credentialEnv: string; +} + +export function parseMcpToolDiscoveryArguments(args: string[]): McpToolDiscoveryArguments { + if (args.length !== 4 || args[0] !== "--url" || args[2] !== "--credential-env") { + throw new Error("invalid arguments"); + } + const url = new URL(args[1]); + const credentialEnv = args[3]; + if ( + url.protocol !== "https:" || + url.username !== "" || + url.password !== "" || + url.hash !== "" || + !/^[A-Za-z_][A-Za-z0-9_]{0,127}$/u.test(credentialEnv) + ) { + throw new Error("invalid arguments"); + } + return { url, credentialEnv }; +} + +export function buildMcpToolDiscoveryAuthorizationPlaceholder(credentialEnv: string): string { + return `Bearer openshell:resolve:env:${credentialEnv}`; +} + +export type McpToolPageLoader = (cursor?: string) => Promise; + +export interface McpToolDiscoverySession { + connect: () => Promise; + loadPage: McpToolPageLoader; + hasSession: () => boolean; + terminateSession: () => Promise; + close: () => Promise; + publishResult: (result: McpToolDiscoveryResult) => void; +} + +export function normalizeMcpToolPage(page: McpToolPage): McpToolPage { + return { + tools: page.tools, + ...(page.nextCursor !== undefined ? { nextCursor: page.nextCursor } : {}), + }; +} + +type ToolDiscoveryErrorCode = "invalid-response" | "redirect" | "response-too-large" | "timeout"; + +export class ToolDiscoveryRuntimeError extends Error { + readonly code: ToolDiscoveryErrorCode; + + constructor(code: ToolDiscoveryErrorCode) { + super(code); + this.name = "ToolDiscoveryRuntimeError"; + this.code = code; + } +} + +function utf8Bytes(value: string): number { + return new TextEncoder().encode(value).byteLength; +} + +function compareNames(left: string, right: string): number { + return left < right ? -1 : left > right ? 1 : 0; +} + +function validToolName(name: unknown): name is string { + return ( + typeof name === "string" && + name.length > 0 && + utf8Bytes(name) <= MCP_TOOL_DISCOVERY_LIMITS.maxToolNameBytes && + !/[\u0000-\u001f\u007f-\u009f]/u.test(name) + ); +} + +function validateCursor(cursor: unknown): cursor is string { + return ( + typeof cursor === "string" && + cursor.length > 0 && + utf8Bytes(cursor) <= MCP_TOOL_DISCOVERY_LIMITS.maxCursorBytes && + !/[\u0000-\u001f\u007f-\u009f]/u.test(cursor) + ); +} + +function truncatedResult(tools: string[], detail: string): McpToolDiscoveryResult { + const sorted = [...tools].sort(compareNames); + return { + ok: false, + count: sorted.length, + tools: sorted, + truncated: true, + detail, + }; +} + +export async function enumerateMcpToolNames( + loadPage: McpToolPageLoader, +): Promise { + const names: string[] = []; + const seenNames = new Set(); + const seenCursors = new Set(); + let cursor: string | undefined; + + for (let pageNumber = 1; pageNumber <= MCP_TOOL_DISCOVERY_LIMITS.maxPages; pageNumber += 1) { + const page = await loadPage(cursor); + if (!page || !Array.isArray(page.tools)) { + throw new ToolDiscoveryRuntimeError("invalid-response"); + } + + for (const tool of page.tools) { + if (!tool || !validToolName(tool.name) || seenNames.has(tool.name)) { + throw new ToolDiscoveryRuntimeError("invalid-response"); + } + seenNames.add(tool.name); + if (names.length < MCP_TOOL_DISCOVERY_LIMITS.maxTools) names.push(tool.name); + } + + const nextCursor = page.nextCursor; + if (nextCursor === undefined) { + if (seenNames.size > MCP_TOOL_DISCOVERY_LIMITS.maxTools) { + return truncatedResult( + names, + `tool discovery exceeded the ${MCP_TOOL_DISCOVERY_LIMITS.maxTools}-tool safety limit`, + ); + } + const sorted = [...names].sort(compareNames); + return { + ok: true, + count: sorted.length, + tools: sorted, + truncated: false, + }; + } + + if (!validateCursor(nextCursor) || seenCursors.has(nextCursor)) { + throw new ToolDiscoveryRuntimeError("invalid-response"); + } + seenCursors.add(nextCursor); + cursor = nextCursor; + + if (seenNames.size >= MCP_TOOL_DISCOVERY_LIMITS.maxTools) { + return truncatedResult( + names, + `tool discovery reached the ${MCP_TOOL_DISCOVERY_LIMITS.maxTools}-tool safety limit before pagination completed`, + ); + } + if (pageNumber === MCP_TOOL_DISCOVERY_LIMITS.maxPages) { + return truncatedResult( + names, + `tool discovery reached the ${MCP_TOOL_DISCOVERY_LIMITS.maxPages}-page safety limit`, + ); + } + } + + throw new ToolDiscoveryRuntimeError("invalid-response"); +} + +export async function runMcpToolDiscoverySession(session: McpToolDiscoverySession): Promise { + try { + await session.connect(); + session.publishResult(await enumerateMcpToolNames(session.loadPage)); + } catch (error) { + session.publishResult({ + ok: false, + count: 0, + tools: [], + truncated: false, + detail: safeToolDiscoveryErrorDetail(error), + }); + } finally { + // Source boundary: after connect, the remote MCP server owns session + // lifetime. SDK cleanup can reject once the transport has failed, so the + // client cannot prove remote reclamation. Attempt both cleanup operations + // without replacing the bounded, credential-safe diagnostic result. + // mcp-tool-discovery-runtime.test.ts pins the failed-discovery path. Remove + // this fallback when the SDK guarantees idempotent non-throwing cleanup or + // exposes a bounded cleanup outcome that the diagnostic can report safely. + if (session.hasSession()) { + try { + await session.terminateSession(); + } catch { + // Best effort at the remote-session ownership boundary described above. + } + } + try { + await session.close(); + } catch { + // Best effort at the failed-transport ownership boundary described above. + } + } +} + +export type ToolDiscoveryFetch = (input: string | URL, init?: RequestInit) => Promise; + +function combinedSignal(left: AbortSignal | null | undefined, right: AbortSignal): AbortSignal { + return left ? AbortSignal.any([left, right]) : right; +} + +export function createBoundedMcpFetch( + fetchImpl: ToolDiscoveryFetch, + deadlineSignal: AbortSignal, +): ToolDiscoveryFetch { + let responseBytes = 0; + + return async (input, init = {}) => { + let response: Response; + try { + response = await fetchImpl(input, { + ...init, + redirect: "manual", + signal: combinedSignal(init.signal, deadlineSignal), + }); + } catch (error) { + if (deadlineSignal.aborted || (error instanceof Error && error.name === "AbortError")) { + throw new ToolDiscoveryRuntimeError("timeout"); + } + throw error; + } + + if (response.status >= 300 && response.status < 400) { + await response.body?.cancel(); + throw new ToolDiscoveryRuntimeError("redirect"); + } + + const contentLength = response.headers.get("content-length"); + if (contentLength !== null && /^\d+$/u.test(contentLength)) { + const declaredBytes = Number(contentLength); + if ( + !Number.isSafeInteger(declaredBytes) || + responseBytes + declaredBytes > MCP_TOOL_DISCOVERY_LIMITS.maxResponseBytes + ) { + await response.body?.cancel(); + throw new ToolDiscoveryRuntimeError("response-too-large"); + } + } + + if (!response.body) return response; + const reader = response.body.getReader(); + const boundedBody = new ReadableStream({ + async pull(controller) { + try { + const { value, done } = await reader.read(); + if (done) { + controller.close(); + return; + } + responseBytes += value.byteLength; + if (responseBytes > MCP_TOOL_DISCOVERY_LIMITS.maxResponseBytes) { + await reader.cancel(); + controller.error(new ToolDiscoveryRuntimeError("response-too-large")); + return; + } + controller.enqueue(value); + } catch (error) { + controller.error(error); + } + }, + cancel(reason) { + return reader.cancel(reason); + }, + }); + return new Response(boundedBody, { + status: response.status, + statusText: response.statusText, + headers: response.headers, + }); + }; +} + +export function safeToolDiscoveryErrorDetail(error: unknown): string { + if (error instanceof ToolDiscoveryRuntimeError) { + switch (error.code) { + case "invalid-response": + return "MCP endpoint returned an invalid tool-list response"; + case "redirect": + return "MCP endpoint redirect was rejected"; + case "response-too-large": + return `MCP responses exceeded the ${MCP_TOOL_DISCOVERY_LIMITS.maxResponseBytes}-byte safety limit`; + case "timeout": + return `tool discovery timed out after ${MCP_TOOL_DISCOVERY_LIMITS.maxTotalTimeMs / 1_000}s`; + } + } + + if (error instanceof Error) { + if ( + error.name === "AbortError" || + /(?:request|maximum total) timeout|timed out/iu.test(error.message) + ) { + return `tool discovery timed out after ${MCP_TOOL_DISCOVERY_LIMITS.maxTotalTimeMs / 1_000}s`; + } + const code = (error as Error & { code?: unknown }).code; + if (typeof code === "number" && code >= 100 && code <= 599) { + return `MCP endpoint rejected tool discovery (HTTP ${code})`; + } + } + + return "MCP tool discovery request failed"; +} diff --git a/tools/mcp-tool-discovery-runtime/tsconfig.json b/tools/mcp-tool-discovery-runtime/tsconfig.json new file mode 100644 index 00000000000..84eec88ae46 --- /dev/null +++ b/tools/mcp-tool-discovery-runtime/tsconfig.json @@ -0,0 +1,15 @@ +{ + "$comment": "SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\nSPDX-License-Identifier: Apache-2.0", + "compilerOptions": { + "target": "ES2022", + "module": "NodeNext", + "moduleResolution": "NodeNext", + "lib": ["ES2022"], + "strict": true, + "noEmit": true, + "allowImportingTsExtensions": true, + "skipLibCheck": true, + "types": ["node"] + }, + "include": ["*.ts"] +} diff --git a/tsconfig.cli.json b/tsconfig.cli.json index 542b8df82dd..76abb13dd22 100644 --- a/tsconfig.cli.json +++ b/tsconfig.cli.json @@ -17,5 +17,5 @@ "types": ["node"] }, "include": [".agents/skills/nemoclaw-maintainer-day/scripts/check-gates.ts", ".agents/skills/nemoclaw-maintainer-day/scripts/shared.ts", "agents/hermes/**/*.ts", "bin/**/*.ts", "scripts/**/*.ts", "scripts/**/*.mts", "src/**/*.ts", "test/**/*.ts", "tools/**/*.ts", "tools/**/*.mts", "nemoclaw-blueprint/scripts/**/*.ts"], - "exclude": ["node_modules", "nemoclaw", "test/e2e/fixtures/plugins/weather"] + "exclude": ["node_modules", "nemoclaw", "test/e2e/fixtures/plugins/weather", "tools/mcp-tool-discovery-runtime/mcp-tool-discovery.ts"] }