# 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
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
ENV NODE_ENV=production
RUN 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"]
