# syntax=docker/dockerfile:1
#
# Two-stage build:
#   1. Compile the stdio `caveman-mcp` server from the pinned caveman source ref.
#   2. Wrap it as a streamable-HTTP MCP endpoint with supergateway so n8n's
#      built-in MCP Client Tool (which speaks only SSE / streamable HTTP) can
#      call `caveman_retrieve`.
#
# Why this exists: caveman-proxy only elides bytes from a *streaming* turn when
# the incoming request advertises a `caveman_retrieve` tool. caveman-mcp is
# stdio-only and ships in no image, so this bridge is the only way to give n8n
# that tool. It shares the proxy's /data volume so the recovery handles the
# proxy wrote resolve here.

FROM golang:1.27.1-alpine AS build
ARG CAVEMAN_REF=bin-v2.0.2
# Passed by caveman/docker-compose.yml at build time (Portainer builds this
# image, CI does not). Unset, the value is the public default. The separators
# are `|` so a proxy that is down falls through to the public proxy instead of
# failing on "connect: connection refused" — with commas the go command only
# falls through on a 404/410.
ARG PROXY_URL=
ENV GOPROXY=${PROXY_URL:+$PROXY_URL/go|}https://proxy.golang.org|direct
RUN apk add --no-cache git
WORKDIR /src
# A tag, not a moving branch: the bridge is pinned to the same release as the
# caveman-proxy image so the proxy and its recovery tool stay in step.
RUN git clone --depth 1 --branch "${CAVEMAN_REF}" https://github.com/JuliusBrussee/caveman.git .
RUN --mount=type=cache,target=/go/pkg/mod \
    --mount=type=cache,target=/root/.cache/go-build \
    CGO_ENABLED=0 go build -trimpath -buildvcs=false \
      -ldflags "-s -w -X main.version=${CAVEMAN_REF}" \
      -o /out/caveman-mcp ./mcp/cmd/caveman-mcp

FROM node:22-bookworm-slim
ARG SUPERGATEWAY_VERSION=3.4.3
ARG PROXY_URL=
ENV NODE_ENV=production
# Only rewrite the registry when a proxy was supplied, so the default build is
# byte-for-byte the same command as before.
RUN if [ -n "$PROXY_URL" ]; then npm config set registry "${PROXY_URL}/npm/"; fi \
 && npm install -g "supergateway@${SUPERGATEWAY_VERSION}"
COPY --from=build /out/caveman-mcp /usr/local/bin/caveman-mcp
COPY entrypoint.sh /usr/local/bin/entrypoint.sh
RUN chmod 0755 /usr/local/bin/caveman-mcp /usr/local/bin/entrypoint.sh

# Match the uid that owns the shared /data volume (the proxy image's 65532) so
# the SQLite recovery store can be opened read-write. The node base image's own
# user is 1000, which cannot write that volume.
USER 65532:65532
ENV HOME=/tmp \
    NPM_CONFIG_CACHE=/tmp/.npm \
    CAVEMAN_HOME=/data

EXPOSE 8000
ENTRYPOINT ["/usr/local/bin/entrypoint.sh"]
