Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
207 changes: 207 additions & 0 deletions bin/dotfiles-azure-mcp-pilot
Original file line number Diff line number Diff line change
@@ -0,0 +1,207 @@
#!/usr/bin/env bash
# Optional ChatGPT tunnel recipe; never registered in global MCP surfaces.
set -euo pipefail
set +x

mode=preview
mode_seen=false
tunnel_id=''
for arg in "$@"; do
case "$arg" in
--apply | --doctor | --status | --check | --dry-run)
[[ "$mode_seen" == false ]] || {
echo 'ERROR: choose one mode' >&2
exit 1
}
mode_seen=true
case "$arg" in
--apply) mode=apply ;;
--doctor | --status) mode=doctor ;;
*) mode=preview ;;
esac
;;
-h | --help)
cat <<'HELP'
Usage: bin/dotfiles-azure-mcp-pilot [--check|--dry-run|--apply] [tunnel_ID]
bin/dotfiles-azure-mcp-pilot --doctor|--status
Default: read-only preview. --apply creates missing recipe files only; never
installs tools, writes keys, logs in, or starts services. Existing differences
are refused. See docs/ops/azure-mcp-pilot.md for manual key activation/start.
HELP
exit 0
;;
*)
[[ -z "$tunnel_id" && "$arg" =~ ^tunnel_[A-Za-z0-9_-]+$ ]] || {
echo 'ERROR: expected tunnel_ID (never pass a runtime key)' >&2
exit 1
}
tunnel_id=$arg
;;
esac
done

# A fixed OS PATH avoids inherited IDE paths, empty entries and systemd omissions.
export PATH="$HOME/.local/bin:/usr/local/bin:/usr/bin:/bin"
[[ "$HOME" =~ ^/[A-Za-z0-9_./-]+$ && "$HOME" != *'/../'* ]] || {
echo 'ERROR: HOME must be an absolute path using letters, digits, _, ., / or -' >&2
exit 1
}
name=ixatu-azure-mcp-pilot
launcher="$HOME/.local/share/$name/start.sh"
profile="$HOME/.config/tunnel-client/$name.yaml"
unit="$HOME/.config/systemd/user/$name.service"
keyfile="$HOME/.config/$name/runtime.env"

# Refuse symlinks in all owned paths before reading or writing recipe files.
for target in "$launcher" "$profile" "$unit" "$keyfile"; do
ancestor=$target
while [[ "$ancestor" != / ]]; do
[[ ! -L "$ancestor" ]] || {
echo 'ERROR: pilot paths must not contain symlinks' >&2
exit 1
}
ancestor=${ancestor%/*}
[[ -n "$ancestor" ]] || break
done
done

if [[ "$mode" == doctor || "$mode" == apply ]]; then
for tool in az uvx; do
command -v "$tool" >/dev/null || {
printf 'ERROR: missing %s; provision it manually in ~/.local/bin or OS PATH; retry --doctor\n' "$tool" >&2
exit 1
}
done
[[ -x "$HOME/.local/bin/tunnel-client" ]] || {
echo 'ERROR: missing ~/.local/bin/tunnel-client; provision manually, then retry --doctor' >&2
exit 1
}
fi

if [[ "$mode" == doctor ]]; then
failed=0
for target in "$launcher" "$profile" "$unit"; do
if [[ -f "$target" ]]; then
printf 'present: %s\n' "$target"
else
printf 'missing: %s (preview then --apply tunnel_ID)\n' "$target"
failed=1
fi
done
# Metadata only: never source, parse, or display runtime.env.
if [[ -f "$keyfile" && -s "$keyfile" && -O "$keyfile" && "$(stat -c %a "$keyfile")" == 600 ]]; then
echo 'runtime key file: present, owner-only (contents not checked)'
else
echo 'runtime key file: missing/empty or unsafe; follow manual activation, chmod 0600'
failed=1
fi
if command -v curl >/dev/null && curl --noproxy '*' -fsS --max-time 2 -o /dev/null http://127.0.0.1:49188/readyz 2>/dev/null; then
echo 'readyz: OK (does not prove Azure authentication or tool scope)'
else
echo 'readyz: unavailable; check pilot service locally (curl required)'
failed=1
fi
exit "$failed"
fi

if [[ -z "$tunnel_id" ]]; then
[[ "$mode" != apply ]] || {
echo 'ERROR: --apply requires a new PC09 tunnel_ID' >&2
exit 1
}
printf 'PREVIEW: generate %s, %s, %s with --apply tunnel_ID\n' "$launcher" "$profile" "$unit"
echo 'No key files or services will be changed. See --help.'
exit 0
fi

# Render in memory: preview makes no directories or temporary files.
launcher_text=$(
cat <<'LAUNCHER'
#!/usr/bin/env bash
set -euo pipefail
set +x
export PATH="$HOME/.local/bin:/usr/local/bin:/usr/bin:/bin"
export AZURE_TOKEN_CREDENTIALS=AzureCliCredential
export AZURE_MCP_COLLECT_TELEMETRY=false
export AZURE_MCP_COLLECT_TELEMETRY_MICROSOFT=false
export AZURE_EXTENSION_USE_DYNAMIC_INSTALL=no
export UV_NO_PROGRESS=1
for tool in az uvx; do
command -v "$tool" >/dev/null || { printf 'ERROR: missing %s in pilot PATH\n' "$tool" >&2; exit 1; }
done
exec uvx --from msmcp-azure==3.0.0 azmcp server start --transport stdio --mode all \
--namespace containerapps --namespace group --read-only
LAUNCHER
)
profile_text=$(
cat <<PROFILE
config_version: 1
control_plane:
base_url: "https://api.openai.com"
tunnel_id: "$tunnel_id"
api_key: "env:AZURE_MCP_CONTROL_PLANE_API_KEY"
health:
listen_addr: "127.0.0.1:49188"
admin_ui:
open_browser: false
log:
level: warn
format: json
mcp:
commands:
- channel: main
command: "$launcher"
PROFILE
)
unit_text=$(
cat <<'UNIT'
[Unit]
Description=IXATU Azure MCP pilot Secure Tunnel (read-only)
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
WorkingDirectory=%h
Environment="PATH=%h/.local/bin:/usr/local/bin:/usr/bin:/bin"
EnvironmentFile=%h/.config/ixatu-azure-mcp-pilot/runtime.env
ExecStart=%h/.local/bin/tunnel-client run --profile ixatu-azure-mcp-pilot
Restart=on-failure
RestartSec=10s
UMask=0077
NoNewPrivileges=yes

[Install]
WantedBy=default.target
UNIT
)
paths=("$launcher" "$profile" "$unit")
texts=("$launcher_text" "$profile_text" "$unit_text")
# Preflight every file before creating any; never adopt unrelated content.
for i in "${!paths[@]}"; do
target=${paths[$i]}
if [[ -e "$target" ]]; then
if [[ ! -f "$target" ]] || ! cmp -s "$target" <(printf '%s\n' "${texts[$i]}"); then
echo 'ERROR: existing pilot file differs; review manually, no files overwritten' >&2
exit 1
fi
fi
done
for i in "${!paths[@]}"; do
target=${paths[$i]}
if [[ "$mode" == apply ]]; then
umask 077
mkdir -p "${target%/*}"
if [[ ! -e "$target" ]]; then
(
set -o noclobber
printf '%s\n' "${texts[$i]}" >"$target"
)
[[ "$i" != 0 ]] || chmod 700 "$target"
fi
printf 'retained/created: %s\n' "$target"
else
printf '\nPREVIEW %s\n%s\n' "$target" "${texts[$i]}"
fi
done
echo 'Key activation and service start are separate manual steps; see docs/ops/azure-mcp-pilot.md.'
131 changes: 131 additions & 0 deletions docs/ops/azure-mcp-pilot.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
# Azure MCP + ChatGPT Secure MCP Tunnel: piloto WSL2 opt-in

Receta pequeña para PC-IXATU-09, independiente de Desktop Commander. Ejecutar
manualmente desde el checkout; no se instala ni registra en Cursor/Codex,
Chezmoi o el MANIFEST global. `dotfiles-update` solo reporta versiones del piloto
si está presente. No requiere abrir Cursor.

## Preparación y preview

Provisionar por separado `az`, `uvx` y `~/.local/bin/tunnel-client`. No hay
instaladores, update checks ni login dentro de esta receta. Azure MCP se obtiene
con `uvx --from msmcp-azure==3.0.0`; el primer arranque puede descargar el paquete.
El tunnel-client existente no se actualiza: su versión y compatibilidad deben
verificarse manualmente en PC09 antes de activar.

Crear **un túnel y runtime key nuevos para PC09** en ChatGPT Secure MCP Tunnel.
No copiar ni reutilizar el ID, perfil, runtime.env o credenciales de PC08 sin
autorización explícita. El ID es identificador; la runtime key es un secreto
distinto. No pasar la clave por argumentos CLI, chat o archivos del repo.

```bash
bin/dotfiles-azure-mcp-pilot # resumen, sin escribir
bin/dotfiles-azure-mcp-pilot tunnel_REPLACE # preview completa
bin/dotfiles-azure-mcp-pilot --apply tunnel_REPLACE
```

`--apply` crea únicamente los archivos ausentes que muestra la preview:

- `~/.local/share/ixatu-azure-mcp-pilot/start.sh` (0700)
- `~/.config/tunnel-client/ixatu-azure-mcp-pilot.yaml` (0600)
- `~/.config/systemd/user/ixatu-azure-mcp-pilot.service` (0600)

Repetir con el mismo ID conserva archivos idénticos; cualquier diferencia se
rechaza antes de escribir. No sobreescribe archivos ajenos ni credenciales,
ni inicia/recarga servicios. Rechaza symlinks en las rutas del piloto. HOME debe
ser absoluto y usar letras, dígitos, `_`, `.`, `/` o `-` (sin espacios ni `%`).

## Activación humana de la clave y del servicio

En una terminal Bash local, sin tracing (`set +x`), introducir la runtime key con
entrada oculta. Este bloque se niega a reemplazar un runtime.env existente;
si existe, conservarlo y revisar su procedencia manualmente. No ejecutar el
bloque sobre rutas con symlinks. No guardar la clave en historial ni capturas.

```bash
set +x
umask 077
mkdir -p "$HOME/.config/ixatu-azure-mcp-pilot"
read -r -s -p 'PC09 runtime key: ' pilot_key; printf '\n'
if [[ -n "$pilot_key" && "$pilot_key" =~ ^[A-Za-z0-9_./+=:-]+$ ]]; then
(set -o noclobber
printf 'AZURE_MCP_CONTROL_PLANE_API_KEY=%s\n' "$pilot_key" > "$HOME/.config/ixatu-azure-mcp-pilot/runtime.env")
else
printf 'Clave vacía/formato inesperado; no se ha escrito.\n' >&2
fi
unset pilot_key
```

El archivo recién creado tiene modo 0600 por `umask 077`. El perfil referencia
`env:AZURE_MCP_CONTROL_PLANE_API_KEY`; systemd carga el archivo dedicado mediante
`EnvironmentFile=%h/.config/ixatu-azure-mcp-pilot/runtime.env`. No se usa SOPS ni
el entorno de Desktop Commander. No hacer `cat`, `source` o commit de ese archivo.

Antes de iniciar, comprobar manualmente la sesión CLI y sus permisos DEV en
PC09. Autenticación CLI ya preparada es prerrequisito; el script no ejecuta
`az login`, no cambia suscripciones y no consulta Azure. La identidad debe tener
acceso limitado a DEV: namespaces y `--read-only` **no son una frontera DEV/PROD**.
No activar con permisos PROD amplios.

```bash
systemctl --user daemon-reload
systemctl --user start ixatu-azure-mcp-pilot.service
bin/dotfiles-azure-mcp-pilot --doctor # --status es alias; sin cambios
# Opcional, solo tras validar:
systemctl --user enable ixatu-azure-mcp-pilot.service
```

El doctor verifica herramientas, presencia de archivos, propietario/modo/tamaño
de runtime.env y HTTP en `127.0.0.1:49188/readyz`; nunca lee la clave ni invoca
Azure/uvx/tunnel-client. Sale distinto de cero si falta algo. Un HTTP OK no prueba
la autenticación Azure ni el catálogo MCP. Validar en ChatGPT que `tools/list`
contenga exactamente `containerapps_list`, `group_list`, `group_resource_list`,
y hacer una consulta DEV de lectura antes de dar por válido el piloto. La receta
reproduce `--transport stdio --mode all --namespace containerapps --namespace group
--read-only` de 3.0.0; no añadir namespaces ni operaciones. Si el catálogo difiere,
parar el piloto y revisar antes de usarlo.

## Diagnóstico y parada

### Versiones en dotfiles-update

La sección `tools` lee el pin de
`~/.local/share/ixatu-azure-mcp-pilot/start.sh` y consulta el JSON de PyPI para
`msmcp-azure` (con timeouts de conexión/total de 5/15 segundos). Solo considera
versiones finales `x.y.z` con archivos no retirados; ignora beta/rc/dev.
El snapshot incluye `Azure MCP` con el pin antes/después idéntico, incluso si
PyPI falla o se ejecuta otra sección. `PINNED` representa configuración, no una
comprobación de la versión cargada en un proceso vivo ni de la caché uvx.

Si aparece una estable posterior, emite `ACTIVATION_PENDING`: revisar manualmente
la compatibilidad, cambiar el pin del launcher dedicado y activar/reiniciar el
piloto en una terminal humana separada. El updater no descarga/ejecuta uvx, no
escribe el launcher ni modifica servicios, autenticación o túneles. `--apply`
de la receta seguirá rechazando un launcher con un pin distinto del generado.
Sin piloto: `SKIP`; sin versión remota válida: `WARN` y pin conservado. En mock
no hay consulta de red. Tunnel Client conserva su reporte separado existente.

### Operación local

PATH fijo en systemd y launcher: `$HOME/.local/bin:/usr/local/bin:/usr/bin:/bin`.
Evita el 401 «Azure CLI not installed» cuando `az` viene de pipx en `.local/bin`.
Se fija `AZURE_TOKEN_CREDENTIALS=AzureCliCredential` para evitar intentos de broker
sin X/MSAL antes de CLI ([autenticación Microsoft](https://github.com/microsoft/mcp/blob/main/docs/Authentication.md)).
`AZURE_MCP_COLLECT_TELEMETRY=false` desactiva toda telemetría; también se desactiva
la de Microsoft explícitamente ([referencia Microsoft](https://github.com/microsoft/mcp/blob/main/servers/Azure.Mcp.Server/README.md)).

El perfil usa `log.level: warn` para evitar ruido de polling. Para depurar,
cambiar **solo el perfil local dedicado** a `debug`, reiniciar este servicio,
inspeccionar logs localmente y volver a `warn`. Los logs debug pueden contener
datos sensibles; no compartirlos sin revisión. `--apply` rechazará el perfil
modificado hasta restaurar su contenido original.

```bash
systemctl --user restart ixatu-azure-mcp-pilot.service
systemctl --user stop ixatu-azure-mcp-pilot.service
# Si se habilitó inicio automático:
systemctl --user disable ixatu-azure-mcp-pilot.service
```

No tocar servicios, perfiles ni puerto 49187 de Desktop Commander. Esta receta
no transfiere credenciales, crea recursos Azure ni valida remotamente producción.
3 changes: 3 additions & 0 deletions docs/ops/azure-tooling.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

Esta guía describe la integración mínima de Azure tooling en `dotfiles` para trabajar desde Windows 11 Pro + WSL2 sin mezclar configuración local con despliegues reales.

Piloto opcional ChatGPT: [Azure MCP + Secure MCP Tunnel en PC09](azure-mcp-pilot.md)
(preview, generación explícita y doctor; separado del MANIFEST global).

## Objetivo

`dotfiles` prepara herramientas generales, aliases, checks y setup local. No crea recursos Azure, no guarda credenciales y no contiene nombres reales de recursos para proyectos.
Expand Down
Loading
Loading