Skip to content
pi-c Artifact [8560cae83e]
Login

Artifact [8560cae83e]

Artifact 8560cae83e53ea5d30f1d068017631ac13b3c352c403fa42b58f3b2c834eefe8:


#!/bin/sh
# /mcp in the terminal interface, on a pseudo-terminal: the MCP servers in the settings panel's
# frame, one needing attention first, then the connected ones with their tool count and revision;
# Enter lists a server's tools, where e leaves one out and offers it again; e turns a server off
# and on, d removes one after y, a and the add row
# put /mcp add in the editor, and /mcp add saves and lists a server. The rows come from the RPC
# commands behind the screen. In the box over the transcript (fullscreen) and docked (regular).
set -eu
PIC=${PIC:?set PIC to the pic binary}
DRIVE=${DRIVE:?set DRIVE to the pty_drive binary}
MCP=${MCP:-$(dirname "$PIC")/../fake_mcp}
SQLITE3=${SQLITE3:-sqlite3}
T=$(mktemp -d "${TMPDIR:-/tmp}/pic-tui-mcp.XXXXXX")
T=$(cd "$T" && pwd -P)
spid=
opid=
cleanup() { [ -n "$spid" ] && kill "$spid" 2>/dev/null || :; [ -n "$opid" ] && kill "$opid" 2>/dev/null || :; rm -rf -- "$T"; }
trap cleanup EXIT HUP INT TERM
fail() { printf 'FAIL: %s\n' "$*" >&2; exit 1; }
mkdir "$T/ws" "$T/home" "$T/srv"
for v in $(env | sed -nE 's/^([A-Za-z0-9_]*_(API_KEY|TOKEN))=.*/\1/p'); do unset "$v"; done
export HOME="$T/home" PIC_MODEL_CATALOG=offline PIC_PI_EXPORT=0 PIC_NO_NATIVE_CLIPBOARD=1 PIC_NO_KEY_CHECKS=1
"$MCP" "$T/port" "$T/srv" 120 modern &
spid=$!
i=0
while [ ! -s "$T/port" ]; do i=$((i + 1)); [ "$i" -lt 600 ] || fail "server"; sleep 0.05; done
URL="http://127.0.0.1:$(cat "$T/port")/mcp"
pic() { "$PIC" --db "$T/j" --workspace "$T/ws" "$@"; }
pic mcp add cur "$URL" > /dev/null 2>&1 || fail "add cur"
pic mcp add broken -- "$T/no-such-program" > /dev/null 2>&1 && fail "a missing program was reached"
pic mcp exposure cur 'wr*' hidden > /dev/null || fail "hide wr*"
# a trusted project narrows cur to deferred; offering a tool writes only your own choice
printf '{"mcpServers":{"cur":{"exposure":"deferred","toolExposure":{"slow":"hidden"}}}}\n' > "$T/ws/.mcp.json"
pic mcp exposure cur slow hidden > /dev/null || fail "hide slow"
pic trust yes > /dev/null
screen() { perl -pe 's/\e\[[0-9;?]*[A-Za-z]//g; s/\e\][^\a\e]*(\a|\e\\)//g; s/\r//g' "$1" | grep -v '^\s*$' | tail -20; }
drive() { # NAME MODE: pic on a pseudo-terminal, the script on stdin
    "$DRIVE" "$T/$1.tx" 110 32 "$PIC" --tui-mode "$2" --db "$T/j" --workspace "$T/ws" || fail "$1: $(screen "$T/$1.tx")"
}
enabled() { "$SQLITE3" "$HOME/.pic/pic.sqlite" "SELECT coalesce((SELECT enabled FROM picu_mcp_server WHERE name = '$1'), '-')"; }

# The list, problems first; Enter lists the tools, e leaves one out; e turns a server off and on again.
drive list fullscreen <<'EOF2'
expect pic
send /mcp\r
expect MCP servers
expect Needs attention
expect ! not connected
expect 7 tools · MCP 2026-07-28
expect l/o: sign in/out · r: reconnect · e: on/off · d: remove · a: add ─
send \e[B
expect 127.0.0.1:
send \r
expect MCP tools
expect cur · 5 tools offered · 2 left out
expect deferred · read-only
expect e: leave it out · esc: the servers
send \e[F
expect e: offer it
send e
expect slow: offered by you; the project's file still leaves it out
send \e[H
wait 300
send e
expect hidden · read-only
expect echo is left out from the next request
send e
expect echo is offered from the next request
wait 300
send \e[F
wait 200
send \e[A
wait 200
send e
expect write_note is offered from the next request
send \e
expect MCP servers
send e
expect Turned off
expect cur is off
send e
expect cur is on
send \e
wait 200
send \x04\x04
EOF2
[ "$(enabled cur)" = 1 ] || fail "cur is not on again: $(enabled cur)"
[ "$("$SQLITE3" "$HOME/.pic/pic.sqlite" "SELECT coalesce(json_extract(tool_exposure, '\$.echo'), '-') || ' ' || json_extract(tool_exposure, '\$.write_note') FROM picu_mcp_server WHERE name = 'cur'")" = '- direct' ] ||
    fail "e among the tools did not leave echo out: $("$SQLITE3" "$HOME/.pic/pic.sqlite" "SELECT tool_exposure FROM picu_mcp_server")"
printf 'PASS: /mcp lists the servers, problems first, lists and leaves out tools, and turns one off and on\n'

# d then y removes a server, any other key keeps it; a puts /mcp add in the editor, which adds one.
drive edit regular <<EOF2
expect pic
send /mcp\r
expect MCP servers
send d
expect Remove broken and its sealed values? y: remove
send n
wait 200
send d
expect Remove broken
send y
expect Removed broken.
send a
wait 200
send more $URL\r
expect Added more: 7 tools, MCP 2026-07-28
send \x04\x04
EOF2
[ "$(enabled broken)" = - ] || fail "broken outlived d y"
[ "$(enabled more)" = 1 ] || fail "/mcp add did not save more"
printf 'PASS: d removes a server after y, and a or /mcp add adds one\n'

# --mcp-config reaches each child pic as a file only it can read, never as text on its argv
mkdir "$T/cfgsrv"
cfg=$(printf '{"mcpServers":{"cfgps":{"command":"sh","args":["-c","ps -o args= -p $PPID > \\"$1/argv\\"; exec \\"$2\\" --stdio \\"$3\\" 120 modern","_","%s","%s","%s"]}}}' \
    "$T" "$MCP" "$T/cfgsrv")
"$DRIVE" "$T/cfg.tx" 110 32 "$PIC" --mcp-config "$cfg" --tui-mode regular --db "$T/j" --workspace "$T/ws" <<'EOF2' ||
expect pic
send /mcp\r
expect cfgps
wait 300
send \e
wait 200
send \x04\x04
EOF2
    fail "cfg: $(screen "$T/cfg.tx")"
[ -s "$T/argv" ] || fail "the --mcp-config server was not started: $(screen "$T/cfg.tx")"
grep -q -- '--mcp-config /dev/fd/[0-9]' "$T/argv" || fail "the child's argv: $(cat "$T/argv")"
grep -q 'mcpServers' "$T/argv" && fail "the config's text is on the child's argv: $(cat "$T/argv")"
printf 'PASS: --mcp-config reaches the interface'"'"'s children as a file, not on their argv\n'

# OAuth-protected MCP server: sorted first under Needs sign-in, /mcp login signs in, /mcp logout signs out
PYTHON=${PYTHON:-python3}
cat > "$T/fake_oauth_mcp.py" <<'PYEOF'
import base64, hashlib, json, os, sys, threading, time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, urlencode, urlparse

port_file = sys.argv[1]
deadline = time.time() + int(sys.argv[2])
CODES = {}
TOKENS = set()

def pkce_s256(v):
    return base64.urlsafe_b64encode(hashlib.sha256(v.encode()).digest()).rstrip(b"=").decode()

class H(BaseHTTPRequestHandler):
    def log_message(self, *a): pass
    def send_json(self, code, obj, hdrs=None):
        b = json.dumps(obj).encode()
        self.send_response(code)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(b)))
        for k, v in (hdrs or {}).items():
            self.send_header(k, v)
        self.end_headers()
        self.wfile.write(b)
    def base(self):
        return f"http://127.0.0.1:{self.server.server_address[1]}"
    def do_GET(self):
        p = urlparse(self.path)
        b = self.base()
        if p.path == "/.well-known/oauth-protected-resource/mcp":
            return self.send_json(200, {"resource": f"{b}/mcp", "authorization_servers": [f"{b}/as"], "scopes_supported": ["read"]})
        if p.path == "/.well-known/oauth-authorization-server/as":
            return self.send_json(200, {
                "issuer": f"{b}/as", "authorization_endpoint": f"{b}/auth", "token_endpoint": f"{b}/tok",
                "registration_endpoint": f"{b}/reg", "response_types_supported": ["code"],
                "code_challenge_methods_supported": ["S256"], "token_endpoint_auth_methods_supported": ["none"],
                "authorization_response_iss_parameter_supported": True,
            })
        if p.path == "/auth":
            q = {k: v[0] for k, v in parse_qs(p.query).items()}
            CODES["c1"] = (q.get("code_challenge", ""), q.get("redirect_uri", ""))
            loc = q["redirect_uri"] + "?" + urlencode({"code": "c1", "state": q.get("state", ""), "iss": f"{b}/as"})
            self.send_response(302)
            self.send_header("Location", loc)
            self.send_header("Content-Length", "0")
            self.end_headers()
            return
        self.send_json(404, {"error": "not_found"})
    def do_POST(self):
        p = urlparse(self.path)
        n = int(self.headers.get("Content-Length", "0"))
        raw = self.rfile.read(n).decode() if n else ""
        b = self.base()
        if p.path == "/reg":
            req = json.loads(raw)
            return self.send_json(201, {"client_id": "tui-c1", "redirect_uris": req["redirect_uris"], "token_endpoint_auth_method": "none"})
        if p.path == "/tok":
            q = {k: v[0] for k, v in parse_qs(raw).items()}
            ch, ruri = CODES.get(q.get("code", ""), ("", ""))
            if not ch or pkce_s256(q.get("code_verifier", "")) != ch or q.get("redirect_uri") != ruri:
                return self.send_json(400, {"error": "invalid_grant"})
            TOKENS.add("tui_tok_1")
            return self.send_json(200, {"access_token": "tui_tok_1", "token_type": "Bearer", "expires_in": 3600})
        if p.path == "/mcp":
            auth = self.headers.get("Authorization", "")
            if auth != "Bearer tui_tok_1" or "tui_tok_1" not in TOKENS:
                return self.send_json(401, {"error": "unauth"}, {"WWW-Authenticate": f'Bearer resource_metadata="{b}/.well-known/oauth-protected-resource/mcp"'})
            msg = json.loads(raw)
            mid, method = msg.get("id"), msg.get("method", "")
            if method == "server/discover":
                return self.send_json(200, {"jsonrpc": "2.0", "id": mid, "result": {"resultType": "complete", "supportedVersions": ["2026-07-28"], "capabilities": {"tools": {}}, "_meta": {"io.modelcontextprotocol/serverInfo": {"name": "o", "version": "1"}}}})
            if method == "tools/list":
                return self.send_json(200, {"jsonrpc": "2.0", "id": mid, "result": {"resultType": "complete", "tools": [{"name": "ping", "description": "Ping", "inputSchema": {"type": "object"}}]}})
            return self.send_json(200, {"jsonrpc": "2.0", "id": mid, "result": {"resultType": "complete", "content": [{"type": "text", "text": "pong"}]}})
        self.send_json(404, {"error": "not_found"})

srv = ThreadingHTTPServer(("127.0.0.1", 0), H)
with open(port_file + ".tmp", "w") as f:
    f.write(str(srv.server_address[1]) + "\n")
os.replace(port_file + ".tmp", port_file)
threading.Thread(target=lambda: (time.sleep(max(1, deadline - time.time())), os._exit(0)), daemon=True).start()
srv.serve_forever()
PYEOF

"$PYTHON" -u "$T/fake_oauth_mcp.py" "$T/oport" 120 &
opid=$!
i=0
while [ ! -s "$T/oport" ]; do i=$((i + 1)); [ "$i" -lt 200 ] || fail "oauth server"; sleep 0.05; done
OPORT=$(cat "$T/oport")
OURL="http://127.0.0.1:$OPORT/mcp"
pic mcp add oauthsrv "$OURL" > /dev/null 2>&1 || fail "add oauthsrv"

# Background helper watches the PTY transcript for the auth URL and follows the loopback redirect
"$PYTHON" - "$T/oauth.tx" "$OPORT" <<'PYEOF' &
import re, sys, time, urllib.request
tx, oport = sys.argv[1], sys.argv[2]
ansi = re.compile(r'\x1b\[[0-9;?]*[A-Za-z]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\r')
prefix = f"http://127.0.0.1:{oport}/auth?"
end = time.time() + 20
while time.time() < end:
    try:
        raw = open(tx, "r", errors="ignore").read()
    except FileNotFoundError:
        time.sleep(0.05)
        continue
    clean = ansi.sub("", raw)
    pos = clean.rfind(prefix)
    if pos >= 0:
        wpos = clean.find("Waiting for the browser", pos)
        if wpos > pos:
            url = re.sub(r"\s+", "", clean[pos:wpos])
            if "redirect_uri=" in url and "state=" in url:
                try:
                    urllib.request.urlopen(url, timeout=5).read()
                    sys.exit(0)
                except Exception:
                    pass
    time.sleep(0.05)
PYEOF
hpid=$!

drive oauth regular <<'EOF2'
expect pic
send /mcp\r
expect MCP servers
expect Needs sign-in
expect ! needs sign-in
send \e
wait 200
send /mcp login oauthsrv --no-browser\r
expect Sign in to MCP server oauthsrv
expect Signed in to MCP server oauthsrv
send /mcp\r
expect MCP servers
expect 1 tool · MCP 2026-07-28 · signed in
send \e
wait 200
send /mcp logout oauthsrv\r
expect Signed out of MCP server oauthsrv.
send \x04\x04
EOF2
wait "$hpid" 2>/dev/null || :
printf 'PASS: /mcp shows Needs sign-in first, and /mcp login and /mcp logout work in place\n'