Connect Hermes to the Core's MCP hub and to Supermarket

Hermes runs in CoreDesktop's sandbox, with its own network, so it can't
reach 127.0.0.1:8470. The app now also serves MCP on a Unix socket in its
data folder (/data/mcp.sock), which Hermes reaches with socat. HTTP /mcp
with the bearer token remains for other agents.

hermes/setup.sh asks for the user's own hub token (the Core now issues
per-user tokens), checks it with the hub, and stores it in Hermes' .env.
The hub only speaks SSE, and Hermes' Streamable HTTP attempt can use up
its connect time, so the setup sets transport: sse. It also warns when
Hermes' gateway is still running with the old servers.

Check-ins store the hub's own tool names, without Hermes' mcp__mcphub__
prefix.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-20 12:31:14 -07:00
co-authored by Claude Opus 5.5
parent 1a86589840
commit f3e5b9eff6
12 changed files with 393 additions and 68 deletions
+64 -18
View File
@@ -99,20 +99,28 @@ from `~/.hermes/.env`, so `config.yaml` holds no secret:
mcp_servers:
mcphub:
url: "https://mcphub.<CORE_DOMAIN>/sse?as_user=<CORE_USER>"
transport: sse
headers:
Authorization: "Basic ${MCPHUB_AUTH}"
supermarket:
url: "http://127.0.0.1:8470/mcp"
headers:
Authorization: "Bearer ${SUPERMARKET_MCP_TOKEN}"
command: socat
args: ["STDIO", "UNIX-CONNECT:<data folder>/mcp.sock"]
```
**`~/.hermes/.env`** (written through `hermes config set`, which routes
UPPER_SNAKE names to `.env`):
**Why a socket, not `http://127.0.0.1:8470/mcp`** (found 2026-11-19).
CoreDesktop runs Hermes under srt, in its own network namespace. Hermes
always dials loopback directly, never through the proxy, and finds nothing
there. srt's proxy, in turn, refuses any name that resolves to loopback.
Unix sockets are allowed in Hermes' sandbox, so the app serves stdio-style
MCP on `/data/mcp.sock`, and Hermes runs `socat` as a stdio MCP server. The
socket is 0600, which is the same protection as the token file beside it.
The HTTP endpoint with its bearer token stays for unsandboxed agents
(Claude Code).
**`~/.hermes/.env`**:
```
MCPHUB_AUTH=<base64 of user:password, from a hidden prompt>
SUPERMARKET_MCP_TOKEN=<random, generated by install.sh, also in /data/secrets>
MCPHUB_AUTH=<the user's own hub token from the Core (the part after "Basic "), from a hidden prompt>
```
How `install.sh` does it, safely and idempotently:
@@ -120,9 +128,9 @@ How `install.sh` does it, safely and idempotently:
CoreDesktop's `configure hermes` calls Hermes. Hermes edits its YAML
with comment-preserving ruamel, so we never hand-edit its 2,400-line config.
If an `mcphub` entry already exists, it's left alone.
2. It asks whether Hermes may reach `mcphub.<CORE_DOMAIN>` and
`127.0.0.1:8470`. On yes, it adds them to `network.allowedDomains` in
`~/.config/coredesktop/sandbox/hermes.json`. Hermes' sandbox blocks both
2. It asks whether Hermes may reach `mcphub.<CORE_DOMAIN>`. On yes, it adds
it to `network.allowedDomains` in
`~/.config/coredesktop/sandbox/hermes.json`. Hermes' sandbox blocks it
by default, and that file is the one no sandbox can write.
3. It stops the gateway (`hermes gateway stop`; Hermes starts it on demand) so the
servers load, then checks that Hermes lists the hub's tools.
@@ -258,9 +266,43 @@ done, and so is the tooling for item 8. What changed from the plan:
times are imported into SQLite, and its X/LinkedIn/YouTube clients and
fetcher are kept for Phase 1. Until Phase 1 lands, there's no way to post.
Still to do for item 8, on a real CoreDesktop machine: run `install.sh`,
ask Hermes the check-in question, and confirm that sandboxed Hermes reaches
`127.0.0.1:8470` and lists the hub's EspoCRM tools.
**Status (2026-11-20): Phase 0 is done, on `phase0-foundation`.** Item 8
works end to end: Hermes loads the hub's tools and checks in with the app.
What item 8 turned up:
- Sandboxed Hermes **can't** reach `127.0.0.1:8470` (see "Why a socket" in
the Hermes bridge section), so it reaches the app through `/data/mcp.sock`
with `socat`.
- `hermes config set` writes nested `mcp_servers.*` keys correctly, lists
(`args`) included.
- The hub rejected the shared admin token (401 at Traefik). The Core moved
to per-user tokens, still sent as `Authorization: "Basic <token>"`, with
`as_user=<user>` kept. The setup asks for the token, checks it with the
hub, and `supermarket hermes --reconfigure` re-enters it.
- The hub (FastMCP "mcpserver-hub" 3.2.0) speaks only SSE: a POST to `/sse`
gets 405. Hermes tries Streamable HTTP first, and that try ran out of its
60-second connect time, so setup.sh sets `transport: sse`. `tools/list`
takes about 10 seconds.
- A running Hermes gateway keeps its old servers, and `gateway stop` from
outside the sandbox didn't always stop it. setup.sh now checks the pid
file and says so when the gateway is still running.
- The hub offers 213 tools: Nextcloud 155, Listmonk 29, Superpanel 9,
Baserow 8, Plausible 6 and EspoCRM 6 (`espocrm_search_records`,
`espocrm_get_record`, `espocrm_get_related_records`,
`espocrm_create_record`, `espocrm_update_record`,
`espocrm_delete_record`). Hermes reports them with its own `mcp__mcphub__`
prefix, and the app stores the hub's names. Phase 2 builds on the generic
EspoCRM record tools.
- The per-user token also sees `nextcloud_admin_list_users` and
`nextcloud_admin_get_contacts`, both described as admin-only. To raise with
the Core's developer: it isn't known yet whether the hub blocks them for
non-admins.
Next: start Phase 1.
Supermarket's half can be checked before the token arrives: ask Hermes the
check-in question now. It should reach `bridge_checkin` and note that
mcphub failed.
1. Restructure into the layout above. Port config and the JSON stores to
SQLite, with import from the old files.
@@ -278,11 +320,10 @@ ask Hermes the check-in question, and confirm that sandboxed Hermes reaches
7. Inventory module: list, edit, import (from the old config and from YAML),
and relationship labels.
8. **Hermes bridge test** (do this early, since Phases 2 and 4 depend on it):
- Can sandboxed Hermes reach `127.0.0.1:8470` once it's in `hermes.json`?
Each sandbox has its own network; LAN servers work this way, but this
machine's loopback is untested.
- Does `hermes config set` write nested `mcp_servers.*.headers` keys
correctly?
- ~~Can sandboxed Hermes reach `127.0.0.1:8470` once it's in
`hermes.json`?~~ No. Answered 2026-11-19: it uses the MCP socket instead.
- ~~Does `hermes config set` write nested `mcp_servers.*.headers` keys
correctly?~~ Yes.
- What EspoCRM tools does the hub expose?
- Can Hermes cron jobs call MCP tools?
- How reliable is a run of 50 queued actions?
@@ -409,6 +450,11 @@ Phases 1, 3, 5 and the Stripe half of 4 depend only on Phase 0.
`as_user=` to act as the user. Can the hub issue per-user credentials or
tokens instead? An admin password in each desktop's Hermes `.env` gives an
agent that reads untrusted web content admin access to the Core.
*2026-11-19:* the Core's developer confirmed it's always the admin token
today. After the admin token failed with a 401, they said the hub will
likely move to per-user tokens.
*2026-11-20:* resolved. The hub now issues per-user tokens, still sent as
`Authorization: "Basic <token>"`, with `as_user=<user>` kept in the URL.
2. **MCP hub URL**: is it always `mcphub.<CORE_DOMAIN>`, so it can be worked out
from `core.conf`?
3. **Gitea**: which Gitea do sites live on (the Core's, at
+7 -8
View File
@@ -64,7 +64,7 @@ Back up `~/.local/share/supermarket` to keep everything.
## Hermes and your Core
Supermarket never talks to your Core's MCP hub itself. CoreDesktop's Hermes agent does: it holds the hub's password, and carries out the CRM work Supermarket queues (from Phase 2). The two meet through Supermarket's own MCP endpoint at `http://127.0.0.1:8470/mcp`, which requires a bearer token.
Supermarket never talks to your Core's MCP hub itself. CoreDesktop's Hermes agent does: it holds your own token for the hub, and carries out the CRM work Supermarket queues (from Phase 2). The two meet through Supermarket's own MCP server. Hermes runs in CoreDesktop's sandbox, which has its own network (`127.0.0.1:8470` there isn't your computer's), so Hermes reaches Supermarket through a Unix socket in the data folder, `~/.local/share/supermarket/mcp.sock`, using `socat`. Other agents, such as Claude Code, use `http://localhost:8470/mcp` with the bearer token from `supermarket token`.
`install.sh` (or `supermarket hermes`) adds both MCP servers to `~/.hermes/config.yaml`:
@@ -72,22 +72,21 @@ Supermarket never talks to your Core's MCP hub itself. CoreDesktop's Hermes agen
mcp_servers:
mcphub:
url: "https://mcphub.<your Core's domain>/sse?as_user=<your user name>"
transport: sse
headers:
Authorization: "Basic ${MCPHUB_AUTH}"
supermarket:
url: "http://127.0.0.1:8470/mcp"
headers:
Authorization: "Bearer ${SUPERMARKET_MCP_TOKEN}"
command: socat
args: ["STDIO", "UNIX-CONNECT:/home/<you>/.local/share/supermarket/mcp.sock"]
```
Hermes fills in each `${...}` from `~/.hermes/.env` when it connects, so `config.yaml` holds no password:
Hermes fills in `${MCPHUB_AUTH}` from `~/.hermes/.env` when it connects, so `config.yaml` holds no secret:
```
MCPHUB_AUTH=<base64 of user:password>
SUPERMARKET_MCP_TOKEN=<from supermarket token>
MCPHUB_AUTH=<your own hub token from your Core: the part after "Basic ">
```
Hermes runs in CoreDesktop's sandbox, so it can only reach the hub and Supermarket once they're in `network.allowedDomains` in `~/.config/coredesktop/sandbox/hermes.json`. The script asks before adding them, then restarts Hermes' gateway.
Hermes' sandbox can only reach the hub once it's in `network.allowedDomains` in `~/.config/coredesktop/sandbox/hermes.json`. The script asks before adding it, then restarts Hermes' gateway. To enter a different hub token: `supermarket hermes --reconfigure`.
To check the connection, open **Core & Hermes** in Supermarket and ask Hermes the question shown there. Hermes lists the hub's tools and reports them back to Supermarket, which shows when it last heard from Hermes.
+12 -1
View File
@@ -7,6 +7,9 @@
// SUPERMARKET_ADDR listen address (default :8080)
// SUPERMARKET_PUBLIC_URL the address the browser uses (default http://localhost:8470)
// SUPERMARKET_CORE_CONF CoreDesktop's core.conf (default <data>/core.conf)
// SUPERMARKET_MCP_SOCKET Unix socket for agents' MCP (default <data>/mcp.sock)
// SUPERMARKET_HOST_DATA the data folder's path on the host, to show in
// setup instructions (default: same as the data folder)
package main
import (
@@ -60,6 +63,8 @@ func run(log *slog.Logger) error {
addr := env("SUPERMARKET_ADDR", ":8080")
publicURL := strings.TrimRight(env("SUPERMARKET_PUBLIC_URL", "http://localhost:8470"), "/")
coreConf := env("SUPERMARKET_CORE_CONF", filepath.Join(dataDir, "core.conf"))
mcpSocket := env("SUPERMARKET_MCP_SOCKET", filepath.Join(dataDir, "mcp.sock"))
hostData := env("SUPERMARKET_HOST_DATA", dataDir)
// Everything the app writes (database, secrets, clones) is for this user
// only: it will hold contacts and credentials.
@@ -108,6 +113,7 @@ func run(log *slog.Logger) error {
PublicURL: publicURL,
Version: version,
MCPToken: token,
MCPSocket: filepath.Join(hostData, filepath.Base(mcpSocket)),
MCP: mcpserver.Handler(database, token, version),
Log: log,
ImportStatus: status,
@@ -126,7 +132,12 @@ func run(log *slog.Logger) error {
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
errCh := make(chan error, 1)
errCh := make(chan error, 2)
go func() {
if err := mcpserver.ServeSocket(ctx, database, version, mcpSocket, log); err != nil {
errCh <- fmt.Errorf("MCP socket %s: %w", mcpSocket, err)
}
}()
go func() {
log.Info("Supermarket is running", "version", version, "listen", addr, "open", publicURL)
errCh <- httpServer.ListenAndServe()
+2
View File
@@ -19,6 +19,8 @@ services:
- "127.0.0.1:8470:8080"
environment:
SUPERMARKET_PUBLIC_URL: http://localhost:8470
# Where the data folder (and the MCP socket Hermes uses) is on the host
SUPERMARKET_HOST_DATA: ${SUPERMARKET_DATA:?}
volumes:
- ${SUPERMARKET_DATA:?}:/data
# LLM servers on this computer are at host.docker.internal.
+98 -22
View File
@@ -11,16 +11,19 @@
# mcp_servers:
# mcphub:
# url: "https://mcphub.<core domain>/sse?as_user=<user>"
# transport: sse
# headers:
# Authorization: "Basic ${MCPHUB_AUTH}"
# supermarket:
# url: "http://127.0.0.1:8470/mcp"
# headers:
# Authorization: "Bearer ${SUPERMARKET_MCP_TOKEN}"
# command: socat
# args: ["STDIO", "UNIX-CONNECT:<data folder>/mcp.sock"]
#
# Hermes runs in CoreDesktop's sandbox, which blocks both servers until
# they're added to ~/.config/coredesktop/sandbox/hermes.json, a file no
# sandbox can write; this script asks before adding them.
# Hermes runs in CoreDesktop's sandbox, which has its own network: there,
# 127.0.0.1:8470 isn't this computer's, and the sandbox's proxy won't carry
# loopback traffic. So Hermes reaches Supermarket through the socket the app
# keeps in its data folder (Unix sockets are allowed in Hermes' sandbox). The
# hub is blocked until it's added to ~/.config/coredesktop/sandbox/hermes.json,
# a file no sandbox can write; this script asks before adding it.
# ${...} in single quotes is meant literally: Hermes expands it, not bash.
# shellcheck disable=SC2016
@@ -35,7 +38,9 @@ HERMES_HOME="${HERMES_HOME:-$HOME/.hermes}"
HERMES_ENV="$HERMES_HOME/.env"
HERMES_CONFIG="$HERMES_HOME/config.yaml"
HERMES_SANDBOX_CONF="$HOME/.config/coredesktop/sandbox/hermes.json"
MCP_LOCAL="127.0.0.1:8470"
MCP_SOCKET="$DATA/mcp.sock"
# What earlier versions of this script set up, before the socket
OLD_MCP_LOCAL="127.0.0.1:8470"
if [ ! -x "$HOME/.local/bin/hermes" ]; then
echo "Hermes isn't installed, so Supermarket can't reach your Core's CRM yet."
@@ -62,10 +67,32 @@ set_env() {
chmod 600 "$tmp" && mv -f "$tmp" "$HERMES_ENV"
}
# unset_env KEY: remove a line from Hermes' .env
unset_env() {
local tmp
[ -f "$HERMES_ENV" ] && grep -q "^$1=" "$HERMES_ENV" || return 0
tmp="$(mktemp "$HERMES_ENV.XXXXXX")"
grep -v "^$1=" "$HERMES_ENV" > "$tmp" || true
chmod 600 "$tmp" && mv -f "$tmp" "$HERMES_ENV"
}
# set_server NAME URL AUTH: add or update an MCP server in Hermes' config.
set_server() {
"${HERMES[@]}" config set "mcp_servers.$1.url" "$2" > /dev/null
"${HERMES[@]}" config set "mcp_servers.$1.headers.Authorization" "$3" > /dev/null
set_transport "$1" "$2"
}
# set_transport NAME URL: a hub address ending in /sse speaks only the older
# SSE transport. Hermes tries Streamable HTTP first and falls back to SSE,
# but the failed first try can use up its 60-second connect time, and then
# the hub's tools never load. So name the transport outright.
set_transport() {
if [[ "$2" =~ /sse/?(\?|$) ]]; then
"${HERMES[@]}" config set "mcp_servers.$1.transport" sse > /dev/null
else
"${HERMES[@]}" config unset "mcp_servers.$1.transport" > /dev/null 2>&1 || true
fi
}
# server_configured NAME: true if Hermes' config has an MCP server NAME
@@ -73,6 +100,17 @@ server_configured() {
[ -f "$HERMES_CONFIG" ] && "${HERMES[@]}" config get "mcp_servers.$1.url" 2> /dev/null | grep -q '://'
}
disallow() {
local tmp
allowed "$1" || return 0
tmp="$(mktemp "$HERMES_SANDBOX_CONF.XXXXXX")"
if jq --arg host "$1" '.network.allowedDomains -= [$host]' "$HERMES_SANDBOX_CONF" > "$tmp"; then
mv -f "$tmp" "$HERMES_SANDBOX_CONF"
else
rm -f "$tmp"
fi
}
allowed() {
[ -f "$HERMES_SANDBOX_CONF" ] && jq -e --arg host "$1" \
'(.network.allowedDomains // []) | index($host) != null' "$HERMES_SANDBOX_CONF" > /dev/null 2>&1
@@ -96,8 +134,18 @@ allow() {
echo "Connecting Hermes to Supermarket and to your Core's MCP hub."
# --- Supermarket ---
set_env SUPERMARKET_MCP_TOKEN "$(tr -d '\n' < "$DATA/mcp-token")"
set_server supermarket "http://$MCP_LOCAL/mcp" 'Bearer ${SUPERMARKET_MCP_TOKEN}'
if ! command -v socat > /dev/null; then
echo "Hermes reaches Supermarket with socat, which isn't installed: sudo pacman -S socat, then: supermarket hermes"
exit 1
fi
# Drop the HTTP settings earlier versions used; Hermes picks the transport
# from whichever of url and command is there.
"${HERMES[@]}" config unset mcp_servers.supermarket.url > /dev/null 2>&1 || true
"${HERMES[@]}" config unset mcp_servers.supermarket.headers > /dev/null 2>&1 || true
"${HERMES[@]}" config set mcp_servers.supermarket.command socat > /dev/null
"${HERMES[@]}" config set mcp_servers.supermarket.args "[\"STDIO\", \"UNIX-CONNECT:$MCP_SOCKET\"]" > /dev/null
unset_env SUPERMARKET_MCP_TOKEN
disallow "$OLD_MCP_LOCAL"
# --- The Core's MCP hub ---
hub_host=""
@@ -111,6 +159,7 @@ if [ -z "$CORE_DOMAIN" ]; then
elif server_configured mcphub && [ "${1:-}" != "--reconfigure" ]; then
hub_url="$("${HERMES[@]}" config get mcp_servers.mcphub.url 2> /dev/null | grep -o 'https\?://[^" ]*' | head -n 1)"
hub_host="$(sed -E 's#^https?://([^/:]+).*#\1#' <<< "$hub_url")"
set_transport mcphub "$hub_url"
echo "Hermes already connects to the MCP hub at $hub_url (to change it: supermarket hermes --reconfigure)."
else
user="${CORE_EMAIL%@*}"
@@ -119,29 +168,44 @@ else
echo "Your Core's MCP hub lets Hermes use the Core's apps, such as EspoCRM."
read -rp "Its address [$default_url]: " hub_url
hub_url="${hub_url:-$default_url}"
read -rp "The hub's user name [$CORE_EMAIL]: " hub_user
hub_user="${hub_user:-$CORE_EMAIL}"
read -rsp "Its password (not shown): " hub_password
# The Core gives each user their own token for the hub: its MCP settings
# read `Authorization: "Basic <token>"`.
echo "Your Core gives you your own token for it, in an MCP block like: Authorization: \"Basic <token>\""
read -rsp "Paste the token, the part after \"Basic \" (not shown): " hub_token
echo
if [ -z "$hub_password" ]; then
echo "No password given; skipping the MCP hub. Run \`supermarket hermes\` to try again."
# Forgive pasting the whole header value, or stray quotes and spaces
hub_token="$(tr -d '"'"'"' \t\r\n' <<< "${hub_token#*Basic }")"
hub_token="${hub_token#Basic}"
if [ -z "$hub_token" ]; then
echo "No token given; skipping the MCP hub. Run \`supermarket hermes --reconfigure\` to try again."
else
set_env MCPHUB_AUTH "$(printf '%s:%s' "$hub_user" "$hub_password" | base64 -w0)"
unset hub_password
# The hub streams once it accepts us, so only the status line matters
code="$(curl -s -o /dev/null -w '%{http_code}' --max-time 5 \
-H "Authorization: Basic $hub_token" -H 'Accept: text/event-stream' "$hub_url" 2> /dev/null || true)"
case "$code" in
200) echo "The hub accepted the token." ;;
401 | 403)
echo "Warning: the hub turned the token down (HTTP $code); saving it anyway."
echo " Check that it's your own token for this hub, copied whole, and that the address's"
echo " as_user= is your user name. Get a current one from your Core, then: supermarket hermes --reconfigure"
;;
*) echo "Couldn't check the token with the hub (HTTP ${code:-no answer}); saving it anyway." ;;
esac
set_env MCPHUB_AUTH "$hub_token"
unset hub_token
set_server mcphub "$hub_url" 'Basic ${MCPHUB_AUTH}'
hub_host="$(sed -E 's#^https?://([^/:]+).*#\1#' <<< "$hub_url")"
echo "Hermes will connect to $hub_url. The password is in $HERMES_ENV, readable only by you."
echo "Hermes will connect to $hub_url. The token is in $HERMES_ENV, readable only by you."
fi
fi
# Hermes must write ${...} into its config, not the secret itself.
if ! grep -qF '${SUPERMARKET_MCP_TOKEN}' "$HERMES_CONFIG" 2> /dev/null; then
echo "Warning: $HERMES_CONFIG doesn't hold the \${SUPERMARKET_MCP_TOKEN} reference as expected; check its mcp_servers section."
if ! "${HERMES[@]}" config get mcp_servers.supermarket.args 2> /dev/null | grep -qF "$MCP_SOCKET"; then
echo "Warning: $HERMES_CONFIG doesn't point Hermes at $MCP_SOCKET as expected; check its mcp_servers section."
fi
# --- Hermes' sandbox ---
need=()
for host in "$MCP_LOCAL" $hub_host; do
for host in $hub_host; do
allowed "$host" || need+=("$host")
done
if [ "${#need[@]}" -gt 0 ]; then
@@ -158,11 +222,23 @@ fi
# The gateway only reads the config when it starts. It's usually started on
# demand (and exits when idle) rather than run as a service: stop it, and
# Hermes starts a fresh one the next time it's used.
# A gateway started inside CoreDesktop's sandbox doesn't always answer
# `gateway stop` from outside it, so check its pid file rather than trust the
# exit code: a gateway left running would keep the old servers.
gateway_pid="$HERMES_HOME/gateway.pid"
if systemctl --user is-active --quiet hermes-gateway 2> /dev/null; then
systemctl --user restart hermes-gateway && echo "Restarted Hermes' gateway so it loads the servers."
elif "${HERMES[@]}" gateway stop > /dev/null 2>&1; then
elif [ -s "$gateway_pid" ]; then
before="$(cat "$gateway_pid")"
"${HERMES[@]}" gateway stop > /dev/null 2>&1 || true
sleep 1
if [ -s "$gateway_pid" ] && [ "$(cat "$gateway_pid")" = "$before" ]; then
echo "Warning: Hermes' gateway is still running with the old servers. Quit Hermes, then run:"
echo " hermes gateway stop"
else
echo "Stopped Hermes' gateway; the next time you use Hermes, it starts again with the new servers."
fi
fi
echo
echo "To check that it works, open Supermarket's \"Core & Hermes\" page and ask Hermes the question shown there."
+21
View File
@@ -8,6 +8,7 @@ import (
"database/sql"
"encoding/json"
"errors"
"strings"
"time"
"supermarket/internal/db"
@@ -21,8 +22,28 @@ type Checkin struct {
Note string
}
// hermesPrefix is how Hermes names an MCP server's tools in its own catalog.
const hermesPrefix = "mcp__mcphub__"
// HubToolNames returns the names as the hub itself gives them: agents may
// report their own prefixed names (Hermes: mcp__mcphub__espocrm_get_record),
// and later phases look tools up by the hub's name (espocrm_get_record).
func HubToolNames(names []string) []string {
out := make([]string, 0, len(names))
for _, n := range names {
n = strings.TrimPrefix(strings.TrimSpace(n), hermesPrefix)
if n != "" {
out = append(out, n)
}
}
return out
}
// Record stores a check-in.
func Record(d *db.DB, c Checkin) error {
if c.MCPHubTools != nil {
c.MCPHubTools = HubToolNames(c.MCPHubTools)
}
tools, err := json.Marshal(c.MCPHubTools)
if err != nil {
return err
+20
View File
@@ -0,0 +1,20 @@
package bridge
import (
"reflect"
"testing"
)
func TestHubToolNames(t *testing.T) {
got := HubToolNames([]string{
"mcp__mcphub__espocrm_get_record",
" espocrm_search_records ",
"mcp__mcphub__",
"",
"nextcloud_list_files",
})
want := []string{"espocrm_get_record", "espocrm_search_records", "nextcloud_list_files"}
if !reflect.DeepEqual(got, want) {
t.Fatalf("HubToolNames = %q, want %q", got, want)
}
}
+59 -5
View File
@@ -1,12 +1,17 @@
// Package mcpserver exposes the app's data and actions to agents (Hermes,
// Claude Code) over MCP at /mcp, behind a bearer token.
// Package mcpserver exposes the app's data and actions to agents over MCP:
// at /mcp behind a bearer token (Claude Code), and on a Unix socket in the
// data folder (Hermes).
package mcpserver
import (
"context"
"crypto/subtle"
"encoding/json"
"errors"
"log/slog"
"net"
"net/http"
"os"
"strings"
"github.com/modelcontextprotocol/go-sdk/mcp"
@@ -20,9 +25,7 @@ import (
// Handler returns the /mcp handler. Requests without "Authorization: Bearer
// <token>" are refused.
func Handler(d *db.DB, token, version string) http.Handler {
server := mcp.NewServer(&mcp.Implementation{Name: "supermarket", Version: version}, nil)
addTools(server, d)
server := newServer(d, version)
h := mcp.NewStreamableHTTPHandler(func(*http.Request) *mcp.Server { return server },
&mcp.StreamableHTTPOptions{Stateless: true, JSONResponse: true})
@@ -37,6 +40,57 @@ func Handler(d *db.DB, token, version string) http.Handler {
})
}
func newServer(d *db.DB, version string) *mcp.Server {
server := mcp.NewServer(&mcp.Implementation{Name: "supermarket", Version: version}, nil)
addTools(server, d)
return server
}
// ServeSocket serves MCP on a Unix socket at path, one stdio-style session
// (newline-delimited JSON-RPC) per connection, until ctx ends.
//
// This is how Hermes reaches the app. CoreDesktop runs Hermes in a sandbox
// with its own network, where 127.0.0.1:8470 isn't this computer's, so Hermes
// runs `socat STDIO UNIX-CONNECT:<path>` as a stdio MCP server instead. The
// socket has no token: it is only usable by you (the umask makes it 0700),
// and anything that can open it can read mcp-token in the same folder anyway.
func ServeSocket(ctx context.Context, d *db.DB, version, path string, log *slog.Logger) error {
// A socket left by the last run would make Listen fail.
if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) {
return err
}
ln, err := net.Listen("unix", path)
if err != nil {
return err
}
if err := os.Chmod(path, 0o600); err != nil {
ln.Close()
return err
}
go func() {
<-ctx.Done()
ln.Close()
}()
server := newServer(d, version)
for {
conn, err := ln.Accept()
if err != nil {
if ctx.Err() != nil {
return nil
}
return err
}
go func() {
defer conn.Close()
err := server.Run(ctx, &mcp.IOTransport{Reader: conn, Writer: conn})
if err != nil && ctx.Err() == nil && !errors.Is(err, net.ErrClosed) {
log.Debug("MCP socket session ended", "err", err)
}
}()
}
}
func jsonResult(v any) (*mcp.CallToolResult, error) {
raw, err := json.MarshalIndent(v, "", " ")
if err != nil {
+94
View File
@@ -0,0 +1,94 @@
package mcpserver
import (
"context"
"io"
"log/slog"
"net"
"os"
"path/filepath"
"testing"
"time"
"github.com/modelcontextprotocol/go-sdk/mcp"
"supermarket/internal/bridge"
"supermarket/internal/db"
)
// Hermes reaches the app through the socket with `socat STDIO UNIX-CONNECT:`,
// which is a plain stdio MCP session over the connection.
func TestServeSocket(t *testing.T) {
dir := t.TempDir()
d, err := db.Open(filepath.Join(dir, "app.db"))
if err != nil {
t.Fatal(err)
}
defer d.Close()
path := filepath.Join(dir, "mcp.sock")
// A socket left over from the last run must not stop the next one.
if err := os.WriteFile(path, nil, 0o600); err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithCancel(context.Background())
done := make(chan error, 1)
go func() {
done <- ServeSocket(ctx, d, "test", path, slog.New(slog.NewTextHandler(io.Discard, nil)))
}()
var conn net.Conn
for i := 0; i < 100; i++ {
if conn, err = net.Dial("unix", path); err == nil {
break
}
time.Sleep(10 * time.Millisecond)
}
if err != nil {
t.Fatal(err)
}
if fi, err := os.Stat(path); err != nil || fi.Mode().Perm() != 0o600 {
t.Errorf("socket mode = %v, %v; want 0600", fi.Mode().Perm(), err)
}
client := mcp.NewClient(&mcp.Implementation{Name: "test"}, nil)
session, err := client.Connect(ctx, &mcp.IOTransport{Reader: conn, Writer: conn}, nil)
if err != nil {
t.Fatal(err)
}
tools, err := session.ListTools(ctx, nil)
if err != nil {
t.Fatal(err)
}
found := false
for _, tool := range tools.Tools {
found = found || tool.Name == "bridge_checkin"
}
if !found {
t.Fatalf("bridge_checkin not among %d tools", len(tools.Tools))
}
res, err := session.CallTool(ctx, &mcp.CallToolParams{
Name: "bridge_checkin",
Arguments: map[string]any{"agent": "hermes", "mcphub_tools": []string{"espocrm_search"}},
})
if err != nil || res.IsError {
t.Fatalf("bridge_checkin: %v %+v", err, res)
}
last, err := bridge.Last(d)
if err != nil || last == nil || last.Agent != "hermes" || len(last.MCPHubTools) != 1 {
t.Fatalf("last check-in = %+v, %v", last, err)
}
session.Close()
cancel()
select {
case err := <-done:
if err != nil {
t.Fatalf("ServeSocket: %v", err)
}
case <-time.After(5 * time.Second):
t.Fatal("ServeSocket didn't stop")
}
}
+6 -5
View File
@@ -184,6 +184,7 @@ type coreData struct {
User string
HubURL string
MCPURL string
MCPSocket string
MCPToken string
Last *bridge.Checkin
Prompt string
@@ -201,6 +202,7 @@ func (s *Server) corePage(w http.ResponseWriter, r *http.Request) {
Core: s.Core,
MCPURL: "http://127.0.0.1:" + publicPort(s.PublicURL) + "/mcp",
MCPToken: s.MCPToken,
MCPSocket: s.MCPSocket,
Last: last,
Prompt: bridge.CheckinPrompt,
}
@@ -213,14 +215,13 @@ func (s *Server) corePage(w http.ResponseWriter, r *http.Request) {
d.HermesConfig = `mcp_servers:
mcphub:
url: "` + hub + `"
transport: sse
headers:
Authorization: "Basic ${MCPHUB_AUTH}"
supermarket:
url: "` + d.MCPURL + `"
headers:
Authorization: "Bearer ${SUPERMARKET_MCP_TOKEN}"`
d.HermesEnv = `MCPHUB_AUTH=<base64 of user:password>
SUPERMARKET_MCP_TOKEN=<the token below>`
command: socat
args: ["STDIO", "UNIX-CONNECT:` + d.MCPSocket + `"]`
d.HermesEnv = `MCPHUB_AUTH=<your own hub token from your Core: the part after "Basic ">`
s.render(w, r, "core", page{Title: "Core & Hermes", Nav: "core", Data: d})
}
+1
View File
@@ -36,6 +36,7 @@ type Server struct {
PublicURL string // e.g. http://localhost:8470, for OAuth redirect URIs
Version string
MCPToken string
MCPSocket string // the MCP socket's path on the host, for Hermes' config
MCP http.Handler
Log *slog.Logger
+3 -3
View File
@@ -14,14 +14,14 @@
<section class="card">
<h2>Hermes bridge</h2>
<p>Hermes, CoreDesktop's agent, is the only thing that talks to your Core's MCP hub. It reaches Supermarket at <code>{{.MCPURL}}</code>.</p>
<p>Hermes, CoreDesktop's agent, is the only thing that talks to your Core's MCP hub. It reaches Supermarket through the socket <code>{{.MCPSocket}}</code>; other agents, such as Claude Code, use <code>{{.MCPURL}}</code> with the MCP token.</p>
{{with .Last}}
<p class="ok">Hermes last checked in {{ago .At}}{{if .Note}}: “{{.Note}}”{{end}}.</p>
{{if .MCPHubTools}}
<details><summary>It can use {{len .MCPHubTools}} tools from the MCP hub</summary>
<ul class="pills">{{range .MCPHubTools}}<li><span class="pill">{{.}}</span></li>{{end}}</ul>
</details>
{{else}}<p class="warn-text">It reported no tools from the MCP hub: check the hub's address and password.</p>{{end}}
{{else}}<p class="warn-text">It reported no tools from the MCP hub: check the hub's address and your hub token.</p>{{end}}
{{else}}
<p>Hermes hasn't checked in yet.</p>
{{end}}
@@ -38,7 +38,7 @@
<div class="copy"><pre id="hermes-config">{{.HermesConfig}}</pre><button type="button" class="secondary" data-copy="hermes-config">Copy</button></div>
<p>and this to <code>~/.hermes/.env</code>, so no password is in <code>config.yaml</code>:</p>
<pre>{{.HermesEnv}}</pre>
<p>Hermes runs in CoreDesktop's sandbox, so also let it reach both servers: add <code>mcphub.{{if .Core}}{{.Core.Domain}}{{else}}&lt;your Core's domain&gt;{{end}}</code> and <code>127.0.0.1:8470</code> to <code>network.allowedDomains</code> in <code>~/.config/coredesktop/sandbox/hermes.json</code>. Then restart Hermes' gateway: <code>systemctl --user restart hermes-gateway</code>.</p>
<p>Hermes runs in CoreDesktop's sandbox, so also let it reach the hub: add <code>mcphub.{{if .Core}}{{.Core.Domain}}{{else}}&lt;your Core's domain&gt;{{end}}</code> to <code>network.allowedDomains</code> in <code>~/.config/coredesktop/sandbox/hermes.json</code>. Then restart Hermes' gateway: <code>systemctl --user restart hermes-gateway</code>.</p>
<details><summary>Show the MCP token</summary><pre>{{.MCPToken}}</pre><p class="help">Also in <code>mcp-token</code> in the data folder.</p></details>
</details>
{{end}}{{end}}