Skip to content
pi-c Documentation
Login

Documentation

/* MCP OAuth sign-in for Streamable HTTP servers; see mcp_oauth.h. */
#ifndef _DEFAULT_SOURCE
#define _DEFAULT_SOURCE 1
#endif
#include <ctype.h>
#include <limits.h>
#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <time.h>
#include <unistd.h>

#include "bearssl.h"
#include "cred.h"
#include "http.h"
#include "image.h"
#include "mcp_oauth.h"
#include "mcp_wire.h"
#include "net.h"
#include "oauth.h"
#include "platform.h"
#include "sqlite3.h"
#include "userdb.h"

#define MO_AAD_PREFIX "mcp-oauth:"
#define MO_REFRESH_SKEW_MS 30000LL
#define MO_MAX_EXPIRES_IN_S 3153600000.0 /* 100 years; prevents float-cast-overflow UB */
#define MO_LOCK_WAIT_MS 15000ULL
#define MO_DEFAULT_TIMEOUT 300
#define MO_STATE_CAP (256u * 1024u)

/* ---- private in-memory SQLite for JSON helpers --------------------------------------------- */

static sqlite3 *mo_jdb_conn;
static pid_t mo_jdb_pid;

static sqlite3 *mo_jdb(void) {
    if (mo_jdb_conn && mo_jdb_pid == getpid()) {
        return mo_jdb_conn;
    }
    mo_jdb_conn = NULL;
    if (sqlite3_open(":memory:", &mo_jdb_conn) != SQLITE_OK) {
        sqlite3_close(mo_jdb_conn);
        mo_jdb_conn = NULL;
    }
    mo_jdb_pid = getpid();
    return mo_jdb_conn;
}

static char *mo_jtext3(const char *sql, const char *a, const char *b, const char *c) {
    sqlite3 *db = mo_jdb();
    sqlite3_stmt *q = NULL;
    const char *args[3] = {a, b, c};
    char *out = NULL;
    if (!db || sqlite3_prepare_v2(db, sql, -1, &q, NULL) != SQLITE_OK) {
        return NULL;
    }
    for (int i = 0; i < 3 && i < sqlite3_bind_parameter_count(q); i++) {
        sqlite3_bind_text(q, i + 1, args[i], -1, SQLITE_STATIC);
    }
    if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_type(q, 0) != SQLITE_NULL) {
        size_t n = (size_t)sqlite3_column_bytes(q, 0);
        if ((out = malloc(n + 1))) {
            memcpy(out, sqlite3_column_text(q, 0), n);
            out[n] = '\0';
        }
    }
    sqlite3_finalize(q);
    return out;
}

static char *mo_jtext(const char *sql, const char *a, const char *b) { return mo_jtext3(sql, a, b, NULL); }

static long long mo_jint(const char *sql, const char *a, const char *b, long long dflt) {
    char *v = mo_jtext(sql, a, b);
    long long n = v ? strtoll(v, NULL, 10) : dflt;
    free(v);
    return n;
}

static void mo_free_secret(char *s) {
    if (s) {
        pic_cred_wipe(s, strlen(s));
        free(s);
    }
}

static long long mo_now_ms(void) { return (long long)(pic_platform_get()->wall_ns() / 1000000); }

/* Replaces control bytes with '?' so network strings never inject terminal escapes. */
static void mo_clean(char *s) {
    for (; s && *s; s++) {
        if ((unsigned char)*s < 0x20 || *s == 0x7f) {
            *s = '?';
        }
    }
}

static int mo_is_discovery_miss(int status) { return (status >= 400 && status < 500) || status == 502; }

/* ---- URL parsing, normalization and security guards ---------------------------------------- */

typedef struct {
    int tls;        /* 1 https, 0 http */
    char host[256]; /* lowercased; IPv6 without brackets */
    int ipv6;       /* 1 if bracketed IPv6 */
    int port;       /* effective port (443 or 80 if omitted) */
    int has_port;   /* 1 if port was explicit in URL */
    char path[768]; /* always starts with '/' */
    char query[512]; /* starts with '?' if present, else "" */
} mo_url;

static int mo_is_loopback_host(const char *host) {
    return strcmp(host, "127.0.0.1") == 0 || strcmp(host, "localhost") == 0 || strcmp(host, "::1") == 0;
}

static int mo_url_parse(const char *raw, mo_url *u, char *err, size_t errcap) {
    const char *p, *auth_end, *host_start, *host_end, *colon = NULL, *path_start, *q_start;
    size_t hlen, plen, qlen;
    memset(u, 0, sizeof *u);
    if (!raw || !*raw) {
        if (err) {
            (void)snprintf(err, errcap, "empty URL");
        }
        return -1;
    }
    for (const char *c = raw; *c; c++) {
        if ((unsigned char)*c <= 0x20 || *c == 0x7f) {
            if (err) {
                (void)snprintf(err, errcap, "URL contains whitespace or control characters");
            }
            return -1;
        }
        if (*c == '#') {
            if (err) {
                (void)snprintf(err, errcap, "URL must not contain a fragment");
            }
            return -1;
        }
    }
    if (strncasecmp(raw, "https://", 8) == 0) {
        u->tls = 1;
        u->port = 443;
        p = raw + 8;
    } else if (strncasecmp(raw, "http://", 7) == 0) {
        u->tls = 0;
        u->port = 80;
        p = raw + 7;
    } else {
        if (err) {
            (void)snprintf(err, errcap, "URL must use https:// (or http:// to loopback)");
        }
        return -1;
    }
    auth_end = p + strcspn(p, "/?");
    if (memchr(p, '@', (size_t)(auth_end - p)) || memchr(p, '\\', (size_t)(auth_end - p))) {
        if (err) {
            (void)snprintf(err, errcap, "URL must not contain userinfo or backslashes");
        }
        return -1;
    }
    if (auth_end == p || *p == ':') {
        if (err) {
            (void)snprintf(err, errcap, "URL has no host");
        }
        return -1;
    }
    if (*p == '[') {
        const char *close = memchr(p + 1, ']', (size_t)(auth_end - p - 1));
        int has_colon = 0;
        if (!close || close == p + 1 || (close + 1 != auth_end && close[1] != ':')) {
            if (err) {
                (void)snprintf(err, errcap, "malformed IPv6 host in URL");
            }
            return -1;
        }
        for (const char *c = p + 1; c < close; c++) {
            if (*c == ':') {
                has_colon = 1;
            } else if (!isxdigit((unsigned char)*c) && *c != '.') {
                if (err) {
                    (void)snprintf(err, errcap, "malformed IPv6 host in URL");
                }
                return -1;
            }
        }
        if (!has_colon) {
            if (err) {
                (void)snprintf(err, errcap, "malformed IPv6 host in URL");
            }
            return -1;
        }
        u->ipv6 = 1;
        host_start = p + 1;
        host_end = close;
        if (close[1] == ':') {
            colon = close + 1;
        }
    } else {
        if (memchr(p, '[', (size_t)(auth_end - p)) || memchr(p, ']', (size_t)(auth_end - p))) {
            if (err) {
                (void)snprintf(err, errcap, "invalid host in URL");
            }
            return -1;
        }
        colon = memchr(p, ':', (size_t)(auth_end - p));
        host_start = p;
        host_end = colon ? colon : auth_end;
    }
    hlen = (size_t)(host_end - host_start);
    if (hlen == 0 || hlen >= sizeof u->host) {
        if (err) {
            (void)snprintf(err, errcap, "invalid host in URL");
        }
        return -1;
    }
    for (size_t i = 0; i < hlen; i++) {
        u->host[i] = (char)tolower((unsigned char)host_start[i]);
    }
    u->host[hlen] = '\0';
    if (colon) {
        char *stop = NULL;
        long port_val;
        if (colon + 1 == auth_end || !isdigit((unsigned char)colon[1])) {
            if (err) {
                (void)snprintf(err, errcap, "invalid port in URL");
            }
            return -1;
        }
        port_val = strtol(colon + 1, &stop, 10);
        if (stop != auth_end || port_val < 1 || port_val > 65535) {
            if (err) {
                (void)snprintf(err, errcap, "invalid port in URL");
            }
            return -1;
        }
        u->port = (int)port_val;
        u->has_port = 1;
    }
    path_start = auth_end;
    q_start = strchr(path_start, '?');
    {
        const char *path_end = q_start ? q_start : path_start + strlen(path_start);
        plen = (size_t)(path_end - path_start);
        if (plen == 0) {
            u->path[0] = '/';
            u->path[1] = '\0';
        } else {
            if (plen >= sizeof u->path) {
                if (err) {
                    (void)snprintf(err, errcap, "URL path is too long");
                }
                return -1;
            }
            memcpy(u->path, path_start, plen);
            u->path[plen] = '\0';
        }
    }
    if (q_start) {
        qlen = strlen(q_start);
        if (qlen >= sizeof u->query) {
            if (err) {
                (void)snprintf(err, errcap, "URL query is too long");
            }
            return -1;
        }
        memcpy(u->query, q_start, qlen);
        u->query[qlen] = '\0';
    }
    return 0;
}

static void mo_url_origin(const mo_url *u, char *out, size_t cap) {
    int def_port = u->tls ? 443 : 80;
    if (u->port != def_port) {
        (void)snprintf(out, cap, "%s://%s%s%s:%d", u->tls ? "https" : "http", u->ipv6 ? "[" : "", u->host,
                       u->ipv6 ? "]" : "", u->port);
    } else {
        (void)snprintf(out, cap, "%s://%s%s%s", u->tls ? "https" : "http", u->ipv6 ? "[" : "", u->host,
                       u->ipv6 ? "]" : "");
    }
}

/* Path suffix without trailing slash (empty string for "/"). */
static void mo_path_suffix(const char *path, char *out, size_t cap) {
    size_t n = strlen(path);
    while (n > 0 && path[n - 1] == '/') {
        n--;
    }
    if (n >= cap) {
        n = cap - 1;
    }
    memcpy(out, path, n);
    out[n] = '\0';
}

int pic_mcp_oauth_url_allowed(const char *url, char *err, size_t errcap) {
    mo_url u;
    if (mo_url_parse(url, &u, err, errcap) != 0) {
        return -1;
    }
    if (!u.tls && !mo_is_loopback_host(u.host)) {
        if (err) {
            (void)snprintf(err, errcap, "OAuth endpoint must use https:// (http:// is allowed only for loopback)");
        }
        return -1;
    }
    return 0;
}

int pic_mcp_oauth_callback_allowed(const char *url, char *err, size_t errcap) {
    mo_url u;
    if (mo_url_parse(url, &u, err, errcap) != 0) {
        return -1;
    }
    if (u.tls || !mo_is_loopback_host(u.host)) {
        if (err) {
            (void)snprintf(err, errcap, "OAuth callbackUrl must be http:// on localhost, 127.0.0.1 or [::1]");
        }
        return -1;
    }
    if (u.query[0]) {
        if (err) {
            (void)snprintf(err, errcap, "OAuth callbackUrl must not contain a query string");
        }
        return -1;
    }
    if (strlen(u.path) >= 256) {
        if (err) {
            (void)snprintf(err, errcap, "OAuth callbackUrl path is too long");
        }
        return -1;
    }
    return 0;
}

int pic_mcp_oauth_server_key(const char *name, const char *url, char *out, size_t cap) {
    mo_url u;
    char origin[320], pbuf[768];
    size_t nlen, need, o = 0;
    if (!name || !*name || !url || !out || cap == 0) {
        return -1;
    }
    if (mo_url_parse(url, &u, NULL, 0) != 0) {
        return -1;
    }
    mo_url_origin(&u, origin, sizeof origin);
    mo_path_suffix(u.path, pbuf, sizeof pbuf);
    nlen = strlen(name);
    need = nlen + 1 + strlen(origin) + strlen(pbuf) + strlen(u.query);
    if (need >= cap) {
        return -1;
    }
    for (size_t i = 0; i < nlen; i++) {
        char c = name[i];
        out[o++] = c == '-' ? '_' : (char)tolower((unsigned char)c);
    }
    out[o++] = '|';
    memcpy(out + o, origin, strlen(origin));
    o += strlen(origin);
    memcpy(out + o, pbuf, strlen(pbuf));
    o += strlen(pbuf);
    memcpy(out + o, u.query, strlen(u.query));
    o += strlen(u.query);
    out[o] = '\0';
    return (int)o;
}

int pic_mcp_oauth_resource_matches(const char *server_url, const char *resource_url, char *err, size_t errcap) {
    mo_url srv, res;
    char spath[770], rpath[770];
    size_t sn, rn;
    if (mo_url_parse(server_url, &srv, err, errcap) != 0 || mo_url_parse(resource_url, &res, err, errcap) != 0) {
        return -1;
    }
    if (srv.tls != res.tls || srv.port != res.port || strcmp(srv.host, res.host) != 0) {
        if (err) {
            (void)snprintf(err, errcap, "protected resource %.200s does not match MCP server origin", resource_url);
        }
        return -1;
    }
    sn = strlen(srv.path);
    rn = strlen(res.path);
    (void)snprintf(spath, sizeof spath, "%s%s", srv.path, sn > 0 && srv.path[sn - 1] == '/' ? "" : "/");
    (void)snprintf(rpath, sizeof rpath, "%s%s", res.path, rn > 0 && res.path[rn - 1] == '/' ? "" : "/");
    if (strncmp(spath, rpath, strlen(rpath)) != 0) {
        if (err) {
            (void)snprintf(err, errcap, "protected resource %.200s does not match MCP server path", resource_url);
        }
        return -1;
    }
    return 0;
}

int pic_mcp_oauth_check_iss(const char *got_iss, const char *expected_issuer, int iss_supported, char *err,
                            size_t errcap) {
    int present = got_iss && *got_iss;
    if (!present && !iss_supported) {
        return 0;
    }
    if (!expected_issuer || !*expected_issuer || !present || strcmp(got_iss, expected_issuer) != 0) {
        if (err) {
            (void)snprintf(err, errcap, "authorization server issuer mismatch (expected %.120s, got %.120s)",
                           expected_issuer && *expected_issuer ? expected_issuer : "(none)", present ? got_iss : "(none)");
        }
        return -1;
    }
    return 0;
}

/* ---- WWW-Authenticate parser --------------------------------------------------------------- */

static int mo_is_token_char(char c) {
    unsigned char uc = (unsigned char)c;
    return isalnum(uc) || (c != '\0' && strchr("!#$%&'*+-.^_`|~", c) != NULL);
}

static void mo_copy_bounded(char *dst, size_t cap, const char *src, size_t len) {
    if (cap == 0) {
        return;
    }
    if (len >= cap) {
        len = cap - 1;
    }
    memcpy(dst, src, len);
    dst[len] = '\0';
}

void pic_mcp_oauth_parse_www_auth(const char *header, pic_mcp_oauth_challenge *out) {
    const char *p;
    int in_oauth = 0;
    memset(out, 0, sizeof *out);
    if (!header || !*header) {
        return;
    }
    p = header;
    while (*p) {
        const char *tok_start, *tok_end, *after;
        size_t tok_len;
        while (*p && (*p == ' ' || *p == '\t' || *p == ',')) {
            p++;
        }
        if (!*p) {
            break;
        }
        tok_start = p;
        while (*p && mo_is_token_char(*p)) {
            p++;
        }
        tok_end = p;
        tok_len = (size_t)(tok_end - tok_start);
        if (tok_len == 0) {
            p++;
            continue;
        }
        after = p;
        while (*after == ' ' || *after == '\t') {
            after++;
        }
        if (*after != '=') {
            /* Auth scheme name (or token68); check if Bearer or DPoP. */
            if ((tok_len == 6 && strncasecmp(tok_start, "bearer", 6) == 0) ||
                (tok_len == 4 && strncasecmp(tok_start, "dpop", 4) == 0)) {
                in_oauth = 1;
                out->is_oauth = 1;
            } else if (*after != ',' && *after != '\0') {
                in_oauth = 0;
            }
            p = after;
            continue;
        }
        /* auth-param: name = value */
        p = after + 1;
        while (*p == ' ' || *p == '\t') {
            p++;
        }
        {
            char val[1024];
            size_t vn = 0;
            if (*p == '"') {
                p++;
                while (*p && *p != '"') {
                    if (*p == '\\' && p[1]) {
                        p++;
                    }
                    if (vn + 1 < sizeof val) {
                        val[vn++] = *p;
                    }
                    p++;
                }
                if (*p == '"') {
                    p++;
                }
            } else {
                while (*p && *p != ' ' && *p != '\t' && *p != ',') {
                    if (vn + 1 < sizeof val) {
                        val[vn++] = *p;
                    }
                    p++;
                }
            }
            val[vn] = '\0';
            if (in_oauth && vn > 0) {
                if (tok_len == 17 && strncasecmp(tok_start, "resource_metadata", 17) == 0) {
                    mo_copy_bounded(out->resource_metadata, sizeof out->resource_metadata, val, vn);
                } else if (tok_len == 5 && strncasecmp(tok_start, "scope", 5) == 0) {
                    mo_copy_bounded(out->scope, sizeof out->scope, val, vn);
                } else if (tok_len == 5 && strncasecmp(tok_start, "error", 5) == 0) {
                    mo_copy_bounded(out->error, sizeof out->error, val, vn);
                } else if (tok_len == 17 && strncasecmp(tok_start, "error_description", 17) == 0) {
                    mo_copy_bounded(out->error_description, sizeof out->error_description, val, vn);
                }
            }
        }
    }
}

/* ---- step-up scope union ------------------------------------------------------------------- */

static int mo_scope_contains(const char *list, size_t list_len, const char *tok, size_t tok_len) {
    size_t i = 0;
    while (i < list_len) {
        size_t s, e;
        while (i < list_len && (list[i] == ' ' || list[i] == '\t')) {
            i++;
        }
        s = i;
        while (i < list_len && list[i] != ' ' && list[i] != '\t') {
            i++;
        }
        e = i;
        if (e - s == tok_len && memcmp(list + s, tok, tok_len) == 0) {
            return 1;
        }
    }
    return 0;
}

int pic_mcp_oauth_step_up_scope(const char *configured, const char *granted, const char *challenged, char *out,
                                size_t cap) {
    const char *lists[3] = {configured, granted, challenged};
    size_t len = 0;
    if (!out || cap == 0) {
        return -1;
    }
    out[0] = '\0';
    for (int k = 0; k < 3; k++) {
        const char *p = lists[k];
        while (p && *p) {
            const char *s, *e;
            size_t tn;
            while (*p == ' ' || *p == '\t' || *p == '\r' || *p == '\n') {
                p++;
            }
            if (!*p) {
                break;
            }
            s = p;
            while (*p && *p != ' ' && *p != '\t' && *p != '\r' && *p != '\n') {
                p++;
            }
            e = p;
            tn = (size_t)(e - s);
            if (mo_scope_contains(out, len, s, tn)) {
                continue;
            }
            if (len + (len ? 1 : 0) + tn >= cap) {
                return -1;
            }
            if (len) {
                out[len++] = ' ';
            }
            memcpy(out + len, s, tn);
            len += tn;
            out[len] = '\0';
        }
    }
    return (int)len;
}

/* ---- non-secret OAuth config JSON ---------------------------------------------------------- */

int pic_mcp_oauth_cfg_parse(const char *oauth_json, pic_mcp_oauth_cfg *cfg, char *err, size_t errcap) {
    char *v;
    long long port;
    memset(cfg, 0, sizeof *cfg);
    if (!oauth_json || !*oauth_json) {
        return 0;
    }
    if (mo_jint("SELECT json_valid(?1) AND json_type(?1) = 'object'", oauth_json, NULL, 0) != 1) {
        if (err) {
            (void)snprintf(err, errcap, "oauth must be a JSON object");
        }
        return -1;
    }
    if ((v = mo_jtext("SELECT json_extract(?1, '$.clientId') WHERE json_type(?1, '$.clientId') = 'text'", oauth_json, NULL))) {
        if (strlen(v) >= sizeof cfg->client_id) {
            free(v);
            if (err) {
                (void)snprintf(err, errcap, "oauth.clientId is too long");
            }
            return -1;
        }
        memcpy(cfg->client_id, v, strlen(v) + 1);
        free(v);
    }
    if ((v = mo_jtext("SELECT json_extract(?1, '$.callbackUrl') WHERE json_type(?1, '$.callbackUrl') = 'text'", oauth_json,
                      NULL))) {
        if (strlen(v) >= sizeof cfg->callback_url) {
            free(v);
            if (err) {
                (void)snprintf(err, errcap, "oauth.callbackUrl is too long");
            }
            return -1;
        }
        if (*v && pic_mcp_oauth_callback_allowed(v, err, errcap) != 0) {
            free(v);
            return -1;
        }
        memcpy(cfg->callback_url, v, strlen(v) + 1);
        free(v);
    }
    if (mo_jint("SELECT json_type(?1, '$.callbackPort') IS NOT NULL AND json_type(?1, '$.callbackPort') <> 'null'",
                oauth_json, NULL, 0)) {
        if (mo_jint("SELECT json_type(?1, '$.callbackPort') = 'integer'", oauth_json, NULL, 0) != 1) {
            if (err) {
                (void)snprintf(err, errcap, "oauth.callbackPort must be an integer 1-65535");
            }
            return -1;
        }
        port = mo_jint("SELECT json_extract(?1, '$.callbackPort')", oauth_json, NULL, 0);
        if (port < 1 || port > 65535) {
            if (err) {
                (void)snprintf(err, errcap, "oauth.callbackPort must be 1-65535");
            }
            return -1;
        }
        cfg->callback_port = (int)port;
    }
    if ((v = mo_jtext("SELECT json_extract(?1, '$.scope') WHERE json_type(?1, '$.scope') = 'text'", oauth_json, NULL))) {
        if (strlen(v) >= sizeof cfg->scope) {
            free(v);
            if (err) {
                (void)snprintf(err, errcap, "oauth.scope is too long");
            }
            return -1;
        }
        memcpy(cfg->scope, v, strlen(v) + 1);
        free(v);
    }
    if ((v = mo_jtext("SELECT json_extract(?1, '$.clientName') WHERE json_type(?1, '$.clientName') = 'text'", oauth_json,
                      NULL))) {
        if (strlen(v) >= sizeof cfg->client_name) {
            free(v);
            if (err) {
                (void)snprintf(err, errcap, "oauth.clientName is too long");
            }
            return -1;
        }
        memcpy(cfg->client_name, v, strlen(v) + 1);
        free(v);
    }
    if ((v = mo_jtext("SELECT json_extract(?1, '$.authServerMetadataUrl')"
                      " WHERE json_type(?1, '$.authServerMetadataUrl') = 'text'",
                      oauth_json, NULL))) {
        if (strlen(v) >= sizeof cfg->auth_server_metadata_url) {
            free(v);
            if (err) {
                (void)snprintf(err, errcap, "oauth.authServerMetadataUrl is too long");
            }
            return -1;
        }
        if (*v && pic_mcp_oauth_url_allowed(v, err, errcap) != 0) {
            free(v);
            return -1;
        }
        memcpy(cfg->auth_server_metadata_url, v, strlen(v) + 1);
        free(v);
    }
    cfg->has_client_secret = mo_jint("SELECT json_extract(?1, '$.hasClientSecret') IS 1", oauth_json, NULL, 0) == 1;
    return 0;
}

static void mo_json_append_str(sqlite3_str *t, const char *s) {
    sqlite3_str_appendall(t, "\"");
    for (const char *p = s; *p; p++) {
        if (*p == '"' || *p == '\\') {
            sqlite3_str_appendchar(t, 1, '\\');
            sqlite3_str_appendchar(t, 1, *p);
        } else if ((unsigned char)*p < 0x20) {
            sqlite3_str_appendf(t, "\\u%04x", (unsigned char)*p);
        } else {
            sqlite3_str_appendchar(t, 1, *p);
        }
    }
    sqlite3_str_appendall(t, "\"");
}

char *pic_mcp_oauth_cfg_json(const pic_mcp_oauth_cfg *cfg) {
    sqlite3_str *t;
    char *res, *out;
    int any = 0;
    if (!cfg || (!cfg->client_id[0] && !cfg->callback_url[0] && !cfg->callback_port && !cfg->scope[0] &&
                 !cfg->client_name[0] && !cfg->auth_server_metadata_url[0] && !cfg->has_client_secret)) {
        return NULL;
    }
    t = sqlite3_str_new(NULL);
    sqlite3_str_appendall(t, "{");
    if (cfg->client_id[0]) {
        sqlite3_str_appendall(t, "\"clientId\":");
        mo_json_append_str(t, cfg->client_id);
        any = 1;
    }
    if (cfg->callback_url[0]) {
        sqlite3_str_appendf(t, "%s\"callbackUrl\":", any ? "," : "");
        mo_json_append_str(t, cfg->callback_url);
        any = 1;
    }
    if (cfg->callback_port > 0) {
        sqlite3_str_appendf(t, "%s\"callbackPort\":%d", any ? "," : "", cfg->callback_port);
        any = 1;
    }
    if (cfg->scope[0]) {
        sqlite3_str_appendf(t, "%s\"scope\":", any ? "," : "");
        mo_json_append_str(t, cfg->scope);
        any = 1;
    }
    if (cfg->client_name[0]) {
        sqlite3_str_appendf(t, "%s\"clientName\":", any ? "," : "");
        mo_json_append_str(t, cfg->client_name);
        any = 1;
    }
    if (cfg->auth_server_metadata_url[0]) {
        sqlite3_str_appendf(t, "%s\"authServerMetadataUrl\":", any ? "," : "");
        mo_json_append_str(t, cfg->auth_server_metadata_url);
        any = 1;
    }
    if (cfg->has_client_secret) {
        sqlite3_str_appendf(t, "%s\"hasClientSecret\":true", any ? "," : "");
    }
    sqlite3_str_appendall(t, "}");
    res = sqlite3_str_finish(t);
    out = res ? strdup(res) : NULL;
    sqlite3_free(res);
    return out;
}

/* ---- sealed storage in picu_mcp_oauth ------------------------------------------------------ */

static int mo_row_exists(const char *server_key) {
    sqlite3 *db = pic_userdb(NULL, 0);
    sqlite3_stmt *q = NULL;
    int has = 0;
    if (db && sqlite3_prepare_v2(db, "SELECT 1 FROM picu_mcp_oauth WHERE server_key = ?1", -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, server_key, -1, SQLITE_STATIC);
        has = sqlite3_step(q) == SQLITE_ROW;
    }
    sqlite3_finalize(q);
    return has;
}

/* Loads and unboxes the JSON state for SERVER_KEY (store must already be unlocked).
 * Returns 0 with *OUT (malloc'd, caller wipes & frees), 1 when no row exists, -1 on error. */
static int mo_state_load(const char *server_key, char **out, char *err, size_t errcap) {
    sqlite3 *db = pic_userdb(err, errcap);
    sqlite3_stmt *q = NULL;
    char aad[1536];
    int rc = 1;
    *out = NULL;
    if (!db) {
        return -1;
    }
    if (sqlite3_prepare_v2(db, "SELECT sealed FROM picu_mcp_oauth WHERE server_key = ?1", -1, &q, NULL) != SQLITE_OK) {
        if (err) {
            (void)snprintf(err, errcap, "cannot read picu_mcp_oauth: %s", sqlite3_errmsg(db));
        }
        return -1;
    }
    sqlite3_bind_text(q, 1, server_key, -1, SQLITE_STATIC);
    if (sqlite3_step(q) == SQLITE_ROW) {
        const unsigned char *blob = sqlite3_column_blob(q, 0);
        int bn = sqlite3_column_bytes(q, 0);
        char *plain;
        if (!blob || bn < PIC_CRED_OVERHEAD || (size_t)bn > MO_STATE_CAP + PIC_CRED_OVERHEAD) {
            if (err) {
                (void)snprintf(err, errcap, "stored MCP OAuth state is damaged");
            }
            rc = -1;
        } else if (!(plain = calloc(1, (size_t)(bn - PIC_CRED_OVERHEAD) + 1))) {
            if (err) {
                (void)snprintf(err, errcap, "out of memory");
            }
            rc = -1;
        } else {
            (void)snprintf(aad, sizeof aad, MO_AAD_PREFIX "%s", server_key);
            if (pic_cred_unbox(aad, blob, (size_t)bn, plain, err, errcap) != 0) {
                pic_cred_wipe(plain, (size_t)(bn - PIC_CRED_OVERHEAD) + 1);
                free(plain);
                rc = -1;
            } else {
                *out = plain;
                rc = 0;
            }
        }
    }
    sqlite3_finalize(q);
    return rc;
}

/* Seals JSON into picu_mcp_oauth under SERVER_KEY (store must already be unlocked). 0 or -1. */
static int mo_state_save(const char *server_key, const char *json, char *err, size_t errcap) {
    sqlite3 *db = pic_userdb(err, errcap);
    sqlite3_stmt *q = NULL;
    char aad[1536];
    size_t jn = strlen(json);
    unsigned char *box;
    int rc = -1;
    if (!db) {
        return -1;
    }
    if (jn > MO_STATE_CAP) {
        if (err) {
            (void)snprintf(err, errcap, "OAuth state exceeds size limit");
        }
        return -1;
    }
    if (!(box = malloc(jn + PIC_CRED_OVERHEAD))) {
        if (err) {
            (void)snprintf(err, errcap, "out of memory");
        }
        return -1;
    }
    (void)snprintf(aad, sizeof aad, MO_AAD_PREFIX "%s", server_key);
    if (pic_cred_box(aad, json, jn, box, err, errcap) != 0) {
        free(box);
        return -1;
    }
    for (int attempt = 0; attempt < 2; attempt++) {
        if (sqlite3_prepare_v2(db,
                               "INSERT INTO picu_mcp_oauth(server_key, sealed, updated_ms) VALUES(?1, ?2, ?3)"
                               " ON CONFLICT(server_key) DO UPDATE SET sealed = excluded.sealed, updated_ms = excluded.updated_ms",
                               -1, &q, NULL) == SQLITE_OK) {
            sqlite3_bind_text(q, 1, server_key, -1, SQLITE_STATIC);
            sqlite3_bind_blob(q, 2, box, (int)(jn + PIC_CRED_OVERHEAD), SQLITE_STATIC);
            sqlite3_bind_int64(q, 3, mo_now_ms());
            rc = sqlite3_step(q) == SQLITE_DONE ? 0 : -1;
        }
        sqlite3_finalize(q);
        q = NULL;
        if (rc == 0) {
            break;
        }
        {
            struct timespec ts = {0, 200 * 1000000L};
            (void)nanosleep(&ts, NULL);
        }
    }
    if (rc != 0 && err) {
        (void)snprintf(err, errcap, "cannot save MCP OAuth state: %s", sqlite3_errmsg(db));
    }
    free(box);
    return rc;
}

int pic_mcp_oauth_save_secret(const char *server_name, const char *server_url, const char *client_secret, char *err,
                              size_t errcap) {
    char key[1400], *old = NULL, *updated = NULL;
    int got, rc = -1;
    if (!client_secret || !*client_secret) {
        return 0;
    }
    if (pic_mcp_oauth_server_key(server_name, server_url, key, sizeof key) < 0) {
        if (err) {
            (void)snprintf(err, errcap, "invalid MCP server URL for OAuth storage");
        }
        return -1;
    }
    if (pic_cred_prepare(err, errcap) != 0) {
        return -1;
    }
    got = mo_state_load(key, &old, err, errcap);
    if (got < 0) {
        /* If old row cannot open, start fresh with new secret. */
        old = NULL;
    }
    updated = mo_jtext3("SELECT json_set(coalesce(?1, '{}'), '$.serverUrl', ?2, '$.configuredClientSecret', ?3)", old,
                        server_url, client_secret);
    mo_free_secret(old);
    if (!updated) {
        if (err) {
            (void)snprintf(err, errcap, "out of memory");
        }
        return -1;
    }
    rc = mo_state_save(key, updated, err, errcap);
    mo_free_secret(updated);
    return rc;
}

int pic_mcp_oauth_logout(const char *server_name, const char *server_url, char *err, size_t errcap) {
    sqlite3 *db = pic_userdb(err, errcap);
    sqlite3_stmt *q = NULL;
    char key[1400];
    int rc = -1;
    if (!db) {
        return -1;
    }
    if (pic_mcp_oauth_server_key(server_name, server_url, key, sizeof key) < 0) {
        if (err) {
            (void)snprintf(err, errcap, "invalid MCP server URL");
        }
        return -1;
    }
    (void)sqlite3_exec(db, "PRAGMA secure_delete = ON;", NULL, NULL, NULL);
    if (sqlite3_prepare_v2(db, "DELETE FROM picu_mcp_oauth WHERE server_key = ?1", -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, key, -1, SQLITE_STATIC);
        rc = sqlite3_step(q) == SQLITE_DONE ? (sqlite3_changes(db) > 0 ? 1 : 0) : -1;
    } else if (err) {
        (void)snprintf(err, errcap, "cannot clear MCP OAuth state: %s", sqlite3_errmsg(db));
    }
    sqlite3_finalize(q);
    (void)sqlite3_exec(db, "PRAGMA secure_delete = OFF;", NULL, NULL, NULL);
    return rc;
}

static int mo_error_needs_auth(const char *last_error) {
    if (!last_error || !*last_error) {
        return 0;
    }
    return strstr(last_error, "pic mcp login") != NULL || strstr(last_error, "HTTP 401") != NULL ||
           strstr(last_error, "insufficient_scope") != NULL || strstr(last_error, "requires sign-in") != NULL;
}

pic_mcp_auth_status pic_mcp_oauth_status(const char *server_name, const char *server_url, const char *oauth_json,
                                         const char *last_error, int has_explicit_auth) {
    char key[1400];
    int has_row, has_cfg = oauth_json && *oauth_json && strcmp(oauth_json, "{}") != 0;
    if (!server_url || !*server_url || has_explicit_auth) {
        return PIC_MCP_AUTH_NONE;
    }
    if (pic_mcp_oauth_server_key(server_name, server_url, key, sizeof key) < 0) {
        return PIC_MCP_AUTH_NONE;
    }
    if (mo_error_needs_auth(last_error)) {
        return PIC_MCP_AUTH_NEEDS_AUTH;
    }
    has_row = mo_row_exists(key);
    if (has_row) {
        char qerr[128] = "";
        int q = pic_cred_quiet(qerr, sizeof qerr);
        if (q == 0) {
            char *state = NULL;
            if (mo_state_load(key, &state, NULL, 0) == 0 && state) {
                int has_tok = mo_jint("SELECT json_type(?1, '$.tokens.access_token') = 'text'"
                                      " AND length(json_extract(?1, '$.tokens.access_token')) > 0",
                                      state, NULL, 0) == 1;
                mo_free_secret(state);
                if (has_tok) {
                    return PIC_MCP_AUTH_SIGNED_IN;
                }
                return has_cfg ? PIC_MCP_AUTH_NEEDS_AUTH : PIC_MCP_AUTH_NONE;
            }
            mo_free_secret(state);
        } else if (q == 1) {
            /* Locked passphrase store: row exists without error -> treat as signed_in unless only clientSecret. */
            int only_secret = has_cfg && mo_jint("SELECT json_extract(?1, '$.hasClientSecret') IS 1", oauth_json, NULL, 0) == 1;
            return only_secret ? PIC_MCP_AUTH_NEEDS_AUTH : PIC_MCP_AUTH_SIGNED_IN;
        }
    }
    return has_cfg ? PIC_MCP_AUTH_NEEDS_AUTH : PIC_MCP_AUTH_NONE;
}

/* ---- cross-process refresh lockfile -------------------------------------------------------- */

static int mo_refresh_lock(const char *server_key, char *err, size_t errcap) {
    char dbpath[4096], lockpath[4096];
    const pic_platform *p = pic_platform_get();
    uint64_t end = p->mono_ns() + MO_LOCK_WAIT_MS * 1000000ULL;
    br_sha256_context h;
    unsigned char digest[32];
    size_t n;
    if (pic_userdb_path(dbpath, sizeof dbpath) != 0 || (n = strlen(dbpath)) < 10) {
        if (err) {
            (void)snprintf(err, errcap, "no home directory for ~/.pic");
        }
        return -1;
    }
    br_sha256_init(&h);
    br_sha256_update(&h, server_key, strlen(server_key));
    br_sha256_out(&h, digest);
    (void)snprintf(lockpath, sizeof lockpath, "%.*smcp-oauth-%02x%02x%02x%02x%02x%02x%02x%02x.lock",
                   (int)(n - strlen("pic.sqlite")), dbpath, digest[0], digest[1], digest[2], digest[3], digest[4],
                   digest[5], digest[6], digest[7]);
    for (;;) {
        int handle = p->lock(lockpath, 0);
        if (handle >= 0) {
            return handle;
        }
        if (handle == -1 || p->mono_ns() >= end) {
            if (err) {
                (void)snprintf(err, errcap,
                               handle == -1 ? "cannot open MCP OAuth lockfile" : "another pic is refreshing this MCP sign-in");
            }
            return -1;
        }
        {
            struct timespec ts = {0, 20 * 1000000L};
            (void)nanosleep(&ts, NULL);
        }
    }
}

/* ---- OAuth discovery (RFC 9728 + RFC 8414 / OIDC) ------------------------------------------ */

typedef struct {
    char issuer[1024];
    char auth_endpoint[1024];
    char token_endpoint[1024];
    char reg_endpoint[1024];
    char resource[1024];
    char prm_scopes[512];
    char auth_methods_json[256]; /* JSON array of token_endpoint_auth_methods_supported, or "[]" */
    int has_metadata;
    int iss_supported;
    int supports_code;
    int has_pkce_methods;
    int supports_s256;
} mo_discovery;

static void mo_trim_slash(const char *in, char *out, size_t cap) {
    size_t n = strlen(in);
    while (n > 0 && in[n - 1] == '/') {
        n--;
    }
    if (n >= cap) {
        n = cap - 1;
    }
    memcpy(out, in, n);
    out[n] = '\0';
}

/* Extracts a required http(s) allowed URL from JSON at PATH into DST. 0 or -1. */
static int mo_extract_allowed_url(const char *json, const char *path, const char *label, char *dst, size_t cap, char *err,
                                  size_t errcap) {
    char *v = mo_jtext("SELECT json_extract(?1, ?2) WHERE json_valid(?1) AND json_type(?1, ?2) = 'text'"
                       " AND length(json_extract(?1, ?2)) > 0",
                       json, path);
    if (!v) {
        if (err) {
            (void)snprintf(err, errcap, "OAuth metadata lacks %s", label);
        }
        return -1;
    }
    if (pic_mcp_oauth_url_allowed(v, err, errcap) != 0) {
        free(v);
        return -1;
    }
    if (strlen(v) >= cap) {
        free(v);
        if (err) {
            (void)snprintf(err, errcap, "OAuth metadata %s URL is too long", label);
        }
        return -1;
    }
    memcpy(dst, v, strlen(v) + 1);
    free(v);
    return 0;
}

static int mo_parse_as_metadata(const char *body, const char *expected_issuer, int check_issuer, mo_discovery *d, char *err,
                                size_t errcap) {
    char *v;
    if (mo_jint("SELECT json_valid(?1) AND json_type(?1) = 'object'", body, NULL, 0) != 1) {
        if (err) {
            (void)snprintf(err, errcap, "authorization server metadata is not a JSON object");
        }
        return -1;
    }
    if (mo_extract_allowed_url(body, "$.issuer", "issuer", d->issuer, sizeof d->issuer, err, errcap) != 0 ||
        mo_extract_allowed_url(body, "$.authorization_endpoint", "authorization_endpoint", d->auth_endpoint,
                               sizeof d->auth_endpoint, err, errcap) != 0 ||
        mo_extract_allowed_url(body, "$.token_endpoint", "token_endpoint", d->token_endpoint, sizeof d->token_endpoint,
                               err, errcap) != 0) {
        return -1;
    }
    if (check_issuer && expected_issuer && *expected_issuer) {
        char a[1024], b[1024];
        mo_trim_slash(d->issuer, a, sizeof a);
        mo_trim_slash(expected_issuer, b, sizeof b);
        if (strcmp(a, b) != 0) {
            if (err) {
                (void)snprintf(err, errcap, "authorization server issuer mismatch (expected %.120s, got %.120s)", b, a);
            }
            return -1;
        }
    }
    if (mo_jint("SELECT json_type(?1, '$.response_types_supported') = 'array'", body, NULL, 0) != 1) {
        if (err) {
            (void)snprintf(err, errcap, "authorization server metadata lacks response_types_supported");
        }
        return -1;
    }
    d->supports_code = mo_jint("SELECT count(*) FROM json_each(?1, '$.response_types_supported')"
                               " WHERE type = 'text' AND value = 'code'",
                               body, NULL, 0) > 0;
    d->has_pkce_methods = mo_jint("SELECT json_type(?1, '$.code_challenge_methods_supported') = 'array'", body, NULL, 0) == 1;
    d->supports_s256 = !d->has_pkce_methods ||
                       mo_jint("SELECT count(*) FROM json_each(?1, '$.code_challenge_methods_supported')"
                               " WHERE type = 'text' AND value = 'S256'",
                               body, NULL, 0) > 0;
    if ((v = mo_jtext("SELECT json_extract(?1, '$.registration_endpoint')"
                      " WHERE json_type(?1, '$.registration_endpoint') = 'text' AND length(json_extract(?1, '$.registration_endpoint')) > 0",
                      body, NULL))) {
        if (pic_mcp_oauth_url_allowed(v, err, errcap) != 0) {
            free(v);
            return -1;
        }
        if (strlen(v) >= sizeof d->reg_endpoint) {
            free(v);
            if (err) {
                (void)snprintf(err, errcap, "OAuth metadata registration_endpoint URL is too long");
            }
            return -1;
        }
        memcpy(d->reg_endpoint, v, strlen(v) + 1);
        free(v);
    }
    {
        /* Keep only the methods pic supports so auth_methods_json is always bounded valid JSON. */
        static const char *const supported[3] = {"client_secret_basic", "client_secret_post", "none"};
        size_t o = 0;
        d->auth_methods_json[o++] = '[';
        for (size_t i = 0; i < 3; i++) {
            if (mo_jint("SELECT count(*) FROM json_each(?1, '$.token_endpoint_auth_methods_supported')"
                        " WHERE json_type(?1, '$.token_endpoint_auth_methods_supported') = 'array'"
                        " AND type = 'text' AND value = ?2",
                        body, supported[i], 0) > 0) {
                o += (size_t)snprintf(d->auth_methods_json + o, sizeof d->auth_methods_json - o, "%s\"%s\"",
                                      o > 1 ? "," : "", supported[i]);
            }
        }
        d->auth_methods_json[o++] = ']';
        d->auth_methods_json[o] = '\0';
    }
    d->iss_supported = mo_jint("SELECT json_extract(?1, '$.authorization_response_iss_parameter_supported') IS 1", body,
                               NULL, 0) == 1;
    d->has_metadata = 1;
    return 0;
}

static int mo_discover(const char *server_url, const char *resource_metadata_url, const char *auth_metadata_override,
                       mo_discovery *d, char *err, size_t errcap) {
    static const char *const disc_hdrs[] = {"MCP-Protocol-Version: " PIC_MCP_CURRENT};
    mo_url srv;
    char origin[320], psuf[768], prm_url[1400], as_url[1024] = "";
    char *body = NULL;
    int status = 0;
    memset(d, 0, sizeof *d);
    (void)snprintf(d->auth_methods_json, sizeof d->auth_methods_json, "[]");
    d->supports_code = 1;
    d->supports_s256 = 1;
    if (mo_url_parse(server_url, &srv, err, errcap) != 0) {
        return -1;
    }
    mo_url_origin(&srv, origin, sizeof origin);
    mo_path_suffix(srv.path, psuf, sizeof psuf);

    /* 1. RFC 9728 Protected Resource Metadata */
    if (resource_metadata_url && *resource_metadata_url) {
        if (pic_mcp_oauth_url_allowed(resource_metadata_url, err, errcap) != 0) {
            return -1;
        }
        if (strlen(resource_metadata_url) >= sizeof prm_url) {
            if (err) {
                (void)snprintf(err, errcap, "OAuth resource_metadata URL is too long");
            }
            return -1;
        }
        memcpy(prm_url, resource_metadata_url, strlen(resource_metadata_url) + 1);
    } else {
        (void)snprintf(prm_url, sizeof prm_url, "%s/.well-known/oauth-protected-resource%s", origin, psuf);
    }
    if (pic_oauth_get(prm_url, disc_hdrs, 1, &status, &body, err, errcap) == 0) {
        if ((!resource_metadata_url || !*resource_metadata_url) && psuf[0] && mo_is_discovery_miss(status)) {
            free(body);
            body = NULL;
            (void)snprintf(prm_url, sizeof prm_url, "%s/.well-known/oauth-protected-resource", origin);
            if (pic_oauth_get(prm_url, disc_hdrs, 1, &status, &body, err, errcap) != 0) {
                status = 0;
                body = NULL;
            }
        }
        if (status >= 200 && status < 300 && body) {
            char res_uri[1024] = "";
            if (mo_jint("SELECT json_valid(?1) AND json_type(?1) = 'object'", body, NULL, 0) != 1) {
                free(body);
                if (err) {
                    (void)snprintf(err, errcap, "protected resource metadata is not a JSON object");
                }
                return -1;
            }
            if (mo_extract_allowed_url(body, "$.resource", "resource", res_uri, sizeof res_uri, err, errcap) != 0 ||
                pic_mcp_oauth_resource_matches(server_url, res_uri, err, errcap) != 0) {
                free(body);
                return -1;
            }
            (void)snprintf(d->resource, sizeof d->resource, "%s", res_uri);
            {
                char *as0 = mo_jtext("SELECT json_extract(?1, '$.authorization_servers[0]')"
                                     " WHERE json_type(?1, '$.authorization_servers') = 'array'"
                                     " AND json_type(?1, '$.authorization_servers[0]') = 'text'",
                                     body, NULL);
                if (as0) {
                    if (pic_mcp_oauth_url_allowed(as0, err, errcap) != 0) {
                        free(as0);
                        free(body);
                        return -1;
                    }
                    if (strlen(as0) >= sizeof as_url) {
                        free(as0);
                        free(body);
                        if (err) {
                            (void)snprintf(err, errcap, "OAuth metadata authorization_servers URL is too long");
                        }
                        return -1;
                    }
                    memcpy(as_url, as0, strlen(as0) + 1);
                    free(as0);
                }
            }
            {
                char *sc = mo_jtext("SELECT group_concat(value, ' ') FROM json_each(?1, '$.scopes_supported')"
                                    " WHERE json_type(?1, '$.scopes_supported') = 'array' AND type = 'text'",
                                    body, NULL);
                if (sc) {
                    (void)snprintf(d->prm_scopes, sizeof d->prm_scopes, "%s", sc);
                    free(sc);
                }
            }
        }
        free(body);
        body = NULL;
    }

    /* 2. Authorization Server Metadata (override, else RFC 8414 + OIDC) */
    if (auth_metadata_override && *auth_metadata_override) {
        if (pic_mcp_oauth_url_allowed(auth_metadata_override, err, errcap) != 0) {
            return -1;
        }
        if (pic_oauth_get(auth_metadata_override, disc_hdrs, 1, &status, &body, err, errcap) != 0) {
            return -1;
        }
        if (status < 200 || status >= 300) {
            free(body);
            if (err) {
                (void)snprintf(err, errcap, "HTTP %d loading authorization server metadata", status);
            }
            return -1;
        }
        {
            int prc = mo_parse_as_metadata(body, NULL, 0, d, err, errcap);
            free(body);
            return prc;
        }
    }

    if (!as_url[0]) {
        (void)snprintf(as_url, sizeof as_url, "%s/", origin);
    }
    {
        mo_url asu;
        char as_orig[320], as_path[768], cands[3][1400];
        int ncands = 0;
        if (mo_url_parse(as_url, &asu, err, errcap) != 0) {
            return -1;
        }
        mo_url_origin(&asu, as_orig, sizeof as_orig);
        mo_path_suffix(asu.path, as_path, sizeof as_path);
        (void)snprintf(cands[ncands++], sizeof cands[0], "%s/.well-known/oauth-authorization-server%s", as_orig, as_path);
        (void)snprintf(cands[ncands++], sizeof cands[0], "%s/.well-known/openid-configuration%s", as_orig, as_path);
        if (as_path[0]) {
            (void)snprintf(cands[ncands++], sizeof cands[0], "%s%s/.well-known/openid-configuration", as_orig, as_path);
        }
        for (int i = 0; i < ncands; i++) {
            status = 0;
            body = NULL;
            if (pic_oauth_get(cands[i], disc_hdrs, 1, &status, &body, err, errcap) != 0) {
                return -1;
            }
            if (status >= 200 && status < 300) {
                int prc = mo_parse_as_metadata(body, as_url, 1, d, err, errcap);
                free(body);
                return prc;
            }
            free(body);
            if (!mo_is_discovery_miss(status)) {
                if (err) {
                    (void)snprintf(err, errcap, "HTTP %d loading authorization server metadata", status);
                }
                return -1;
            }
        }
        /* No metadata endpoint answered 2xx: default RFC 6749 endpoints on AS origin. */
        (void)snprintf(d->auth_endpoint, sizeof d->auth_endpoint, "%s/authorize", as_orig);
        (void)snprintf(d->token_endpoint, sizeof d->token_endpoint, "%s/token", as_orig);
        (void)snprintf(d->reg_endpoint, sizeof d->reg_endpoint, "%s/register", as_orig);
        d->has_metadata = 0;
    }
    return 0;
}

/* ---- client authentication & token requests ------------------------------------------------ */

typedef enum { MO_AUTH_NONE, MO_AUTH_BASIC, MO_AUTH_POST } mo_client_auth;

static int mo_methods_include(const char *methods_json, const char *name) {
    return methods_json && mo_jint("SELECT count(*) FROM json_each(?1) WHERE type = 'text' AND value = ?2", methods_json,
                                   name, 0) > 0;
}

static mo_client_auth mo_select_auth_method(const char *hint, int has_secret, const char *methods_json) {
    int nmethods = methods_json ? (int)mo_jint("SELECT json_array_length(?1)", methods_json, NULL, 0) : 0;
    if (hint && *hint && (nmethods == 0 || mo_methods_include(methods_json, hint))) {
        if (strcmp(hint, "client_secret_basic") == 0 && has_secret) {
            return MO_AUTH_BASIC;
        }
        if (strcmp(hint, "client_secret_post") == 0 && has_secret) {
            return MO_AUTH_POST;
        }
        if (strcmp(hint, "none") == 0) {
            return MO_AUTH_NONE;
        }
    }
    if (nmethods == 0) {
        return has_secret ? MO_AUTH_BASIC : MO_AUTH_NONE;
    }
    if (has_secret && mo_methods_include(methods_json, "client_secret_basic")) {
        return MO_AUTH_BASIC;
    }
    if (has_secret && mo_methods_include(methods_json, "client_secret_post")) {
        return MO_AUTH_POST;
    }
    if (mo_methods_include(methods_json, "none")) {
        return MO_AUTH_NONE;
    }
    return has_secret ? MO_AUTH_POST : MO_AUTH_NONE;
}

static void mo_scrub_token_err(char *err, const char *client_secret, const char *const *base_pairs) {
    if (!err || !*err) {
        return;
    }
    if (client_secret && *client_secret) {
        pic_cred_scrub(err, client_secret);
    }
    for (size_t i = 0; base_pairs && base_pairs[i]; i += 2) {
        const char *k = base_pairs[i], *v = base_pairs[i + 1];
        if (v && *v &&
            (strcmp(k, "refresh_token") == 0 || strcmp(k, "code") == 0 || strcmp(k, "code_verifier") == 0)) {
            pic_cred_scrub(err, v);
        }
    }
}

/* Sends a token request (authorization_code or refresh_token).
 * Returns 0 with *RESP_BODY (malloc'd, caller wipes & frees) on HTTP 2xx without $.error;
 * -1 on error, setting *OAUTH_ERR (e.g. "invalid_grant", "invalid_client") if server sent one. */
static int mo_token_post(const char *token_url, const char *client_id, const char *client_secret, const char *auth_hint,
                         const char *methods_json, const char *const *base_pairs, char **resp_body, char *oauth_err,
                         size_t oerr_cap, char *err, size_t errcap) {
    mo_client_auth method = mo_select_auth_method(auth_hint, client_secret && *client_secret, methods_json);
    const char *pairs[24];
    size_t np = 0;
    char *form = NULL, *basic_hdr = NULL, *body = NULL;
    const char *extra[1];
    size_t nextra = 0;
    int status = 0, rc = -1;
    *resp_body = NULL;
    if (oauth_err && oerr_cap) {
        oauth_err[0] = '\0';
    }
    if (pic_mcp_oauth_url_allowed(token_url, err, errcap) != 0) {
        return -1;
    }
    for (size_t i = 0; base_pairs[i] && np + 2 < 20; i += 2) {
        pairs[np++] = base_pairs[i];
        pairs[np++] = base_pairs[i + 1];
    }
    if (method == MO_AUTH_BASIC) {
        size_t clen = strlen(client_id), slen = strlen(client_secret);
        size_t raw_n = clen + 1 + slen;
        size_t b64_cap = 4 * ((raw_n + 2) / 3) + 1;
        char *raw = malloc(raw_n + 1);
        basic_hdr = malloc(b64_cap + 32);
        if (!raw || !basic_hdr) {
            free(raw);
            free(basic_hdr);
            if (err) {
                (void)snprintf(err, errcap, "out of memory");
            }
            return -1;
        }
        memcpy(raw, client_id, clen);
        raw[clen] = ':';
        memcpy(raw + clen + 1, client_secret, slen + 1);
        memcpy(basic_hdr, "Authorization: Basic ", 21);
        (void)pic_base64_encode((const unsigned char *)raw, raw_n, basic_hdr + 21);
        pic_cred_wipe(raw, raw_n);
        free(raw);
        extra[nextra++] = basic_hdr;
    } else {
        pairs[np++] = "client_id";
        pairs[np++] = client_id;
        if (method == MO_AUTH_POST && client_secret && *client_secret) {
            pairs[np++] = "client_secret";
            pairs[np++] = client_secret;
        }
    }
    pairs[np] = NULL;
    form = pic_oauth_form(pairs);
    if (!form) {
        mo_free_secret(basic_hdr);
        if (err) {
            (void)snprintf(err, errcap, "out of memory");
        }
        return -1;
    }
    rc = pic_oauth_post_ex(token_url, form, "application/x-www-form-urlencoded", extra, nextra, &status, &body, err,
                           errcap);
    mo_free_secret(form);
    mo_free_secret(basic_hdr);
    if (rc != 0) {
        mo_scrub_token_err(err, client_secret, base_pairs);
        mo_free_secret(body);
        return -1;
    }
    /* Check OAuth JSON error before HTTP status (RFC 6749 ยง5.2). */
    {
        char *ecode = mo_jtext("SELECT json_extract(?1, '$.error') WHERE json_valid(?1) AND json_type(?1, '$.error') = 'text'",
                               body, NULL);
        if (ecode && *ecode) {
            if (oauth_err && oerr_cap) {
                (void)snprintf(oauth_err, oerr_cap, "%s", ecode);
            }
            pic_oauth_error(status, body, err, errcap);
            mo_scrub_token_err(err, client_secret, base_pairs);
            free(ecode);
            mo_free_secret(body);
            return -1;
        }
        free(ecode);
    }
    if (status < 200 || status >= 300) {
        pic_oauth_error(status, body, err, errcap);
        mo_scrub_token_err(err, client_secret, base_pairs);
        mo_free_secret(body);
        return -1;
    }
    *resp_body = body;
    return 0;
}

/* Validates token response JSON and produces normalized tokens JSON + expires_at ms. 0 or -1. */
static int mo_build_tokens_json(const char *resp, const char *fallback_refresh, const char *fallback_scope,
                                char **tokens_json, long long *expires_at, char *err, size_t errcap) {
    char *access = NULL, *refresh = NULL, *scope = NULL, *ttype = NULL;
    double expires_in;
    sqlite3_str *t;
    char *res;
    *tokens_json = NULL;
    *expires_at = 0;
    if (mo_jint("SELECT json_valid(?1) AND json_type(?1) = 'object'", resp, NULL, 0) != 1) {
        if (err) {
            (void)snprintf(err, errcap, "OAuth token response is not a JSON object");
        }
        return -1;
    }
    access = mo_jtext("SELECT json_extract(?1, '$.access_token') WHERE json_type(?1, '$.access_token') = 'text'"
                      " AND length(json_extract(?1, '$.access_token')) > 0",
                      resp, NULL);
    if (!access) {
        if (err) {
            (void)snprintf(err, errcap, "OAuth token response lacks access_token");
        }
        return -1;
    }
    /* Header-safe check on access token. */
    if (strlen(access) >= PIC_CRED_TOKEN_CAP) {
        mo_free_secret(access);
        if (err) {
            (void)snprintf(err, errcap, "OAuth access token is too long");
        }
        return -1;
    }
    for (const char *c = access; *c; c++) {
        if ((unsigned char)*c <= 0x20 || *c == 0x7f) {
            mo_free_secret(access);
            if (err) {
                (void)snprintf(err, errcap, "OAuth access token contains invalid characters");
            }
            return -1;
        }
    }
    ttype = mo_jtext("SELECT json_extract(?1, '$.token_type') WHERE json_type(?1, '$.token_type') = 'text'"
                     " AND length(json_extract(?1, '$.token_type')) > 0",
                     resp, NULL);
    refresh = mo_jtext("SELECT json_extract(?1, '$.refresh_token') WHERE json_type(?1, '$.refresh_token') = 'text'"
                       " AND length(json_extract(?1, '$.refresh_token')) > 0",
                       resp, NULL);
    if (!refresh && fallback_refresh && *fallback_refresh) {
        refresh = strdup(fallback_refresh);
    }
    scope = mo_jtext("SELECT json_extract(?1, '$.scope') WHERE json_type(?1, '$.scope') = 'text'"
                     " AND length(json_extract(?1, '$.scope')) > 0",
                     resp, NULL);
    if (!scope && fallback_scope && *fallback_scope) {
        scope = strdup(fallback_scope);
    }
    expires_in = pic_oauth_json_number(resp, "$.expires_in");
    if (isfinite(expires_in) && expires_in > 0.0) {
        if (expires_in > MO_MAX_EXPIRES_IN_S) {
            expires_in = MO_MAX_EXPIRES_IN_S;
        }
        *expires_at = mo_now_ms() + (long long)(expires_in * 1000.0);
    }
    t = sqlite3_str_new(NULL);
    sqlite3_str_appendall(t, "{\"access_token\":");
    mo_json_append_str(t, access);
    sqlite3_str_appendall(t, ",\"token_type\":");
    mo_json_append_str(t, ttype ? ttype : "Bearer");
    if (refresh) {
        sqlite3_str_appendall(t, ",\"refresh_token\":");
        mo_json_append_str(t, refresh);
    }
    if (scope) {
        sqlite3_str_appendall(t, ",\"scope\":");
        mo_json_append_str(t, scope);
    }
    if (*expires_at > 0) {
        sqlite3_str_appendf(t, ",\"expires_at\":%lld", *expires_at);
    }
    sqlite3_str_appendall(t, "}");
    {
        int n = sqlite3_str_length(t);
        res = sqlite3_str_finish(t);
        if (res) {
            *tokens_json = strdup(res);
            pic_cred_wipe(res, (size_t)n);
            sqlite3_free(res);
        }
    }
    mo_free_secret(access);
    mo_free_secret(refresh);
    free(scope);
    free(ttype);
    if (!*tokens_json) {
        if (err) {
            (void)snprintf(err, errcap, "out of memory");
        }
        return -1;
    }
    return 0;
}

static char *mo_build_discovery_json(const mo_discovery *d) {
    sqlite3_str *t = sqlite3_str_new(NULL);
    char *res, *out;
    sqlite3_str_appendall(t, "{");
    sqlite3_str_appendall(t, "\"issuer\":");
    mo_json_append_str(t, d->issuer);
    sqlite3_str_appendall(t, ",\"authorization_endpoint\":");
    mo_json_append_str(t, d->auth_endpoint);
    sqlite3_str_appendall(t, ",\"token_endpoint\":");
    mo_json_append_str(t, d->token_endpoint);
    sqlite3_str_appendall(t, ",\"registration_endpoint\":");
    mo_json_append_str(t, d->reg_endpoint);
    sqlite3_str_appendall(t, ",\"resource\":");
    mo_json_append_str(t, d->resource);
    sqlite3_str_appendf(t, ",\"token_endpoint_auth_methods_supported\":%s,\"iss_supported\":%d}",
                        d->auth_methods_json[0] ? d->auth_methods_json : "[]", d->iss_supported ? 1 : 0);
    res = sqlite3_str_finish(t);
    out = res ? strdup(res) : NULL;
    sqlite3_free(res);
    return out;
}

/* ---- RFC 7591 Dynamic Client Registration -------------------------------------------------- */

static int mo_dcr_register(const mo_discovery *d, const char *redirect_uri, const char *client_name, const char *scope,
                           char **client_json, char *err, size_t errcap) {
    sqlite3_str *t;
    char *req_body, *resp_body = NULL, *cid = NULL, *csec = NULL, *amethod = NULL, *ruris = NULL;
    int status = 0, rc = -1;
    *client_json = NULL;
    if (!d->reg_endpoint[0]) {
        if (err) {
            (void)snprintf(err, errcap,
                           "authorization server does not support dynamic client registration; add --oauth-client-id");
        }
        return -1;
    }
    if (pic_mcp_oauth_url_allowed(d->reg_endpoint, err, errcap) != 0) {
        return -1;
    }
    t = sqlite3_str_new(NULL);
    sqlite3_str_appendall(t, "{\"redirect_uris\":[");
    mo_json_append_str(t, redirect_uri);
    sqlite3_str_appendall(t, "],\"grant_types\":[\"authorization_code\",\"refresh_token\"],"
                             "\"response_types\":[\"code\"],\"token_endpoint_auth_method\":\"none\","
                             "\"application_type\":\"native\",\"client_name\":");
    mo_json_append_str(t, client_name && *client_name ? client_name : "pic");
    if (scope && *scope) {
        sqlite3_str_appendall(t, ",\"scope\":");
        mo_json_append_str(t, scope);
    }
    sqlite3_str_appendall(t, "}");
    req_body = sqlite3_str_finish(t);
    if (!req_body) {
        if (err) {
            (void)snprintf(err, errcap, "out of memory");
        }
        return -1;
    }
    rc = pic_oauth_post_ex(d->reg_endpoint, req_body, "application/json", NULL, 0, &status, &resp_body, err, errcap);
    sqlite3_free(req_body);
    if (rc != 0) {
        mo_free_secret(resp_body);
        return -1;
    }
    if (status < 200 || status >= 300) {
        pic_oauth_error(status, resp_body, err, errcap);
        mo_free_secret(resp_body);
        return -1;
    }
    cid = mo_jtext("SELECT json_extract(?1, '$.client_id') WHERE json_valid(?1) AND json_type(?1, '$.client_id') = 'text'"
                   " AND length(json_extract(?1, '$.client_id')) > 0",
                   resp_body, NULL);
    if (!cid) {
        if (err) {
            (void)snprintf(err, errcap, "dynamic client registration response lacks client_id");
        }
        mo_free_secret(resp_body);
        return -1;
    }
    csec = mo_jtext("SELECT json_extract(?1, '$.client_secret') WHERE json_type(?1, '$.client_secret') = 'text'"
                    " AND length(json_extract(?1, '$.client_secret')) > 0",
                    resp_body, NULL);
    amethod = mo_jtext("SELECT json_extract(?1, '$.token_endpoint_auth_method')"
                       " WHERE json_type(?1, '$.token_endpoint_auth_method') = 'text'"
                       " AND length(json_extract(?1, '$.token_endpoint_auth_method')) > 0",
                       resp_body, NULL);
    ruris = mo_jtext("SELECT json(json_extract(?1, '$.redirect_uris')) WHERE json_type(?1, '$.redirect_uris') = 'array'",
                     resp_body, NULL);
    mo_free_secret(resp_body);

    t = sqlite3_str_new(NULL);
    sqlite3_str_appendall(t, "{\"client_id\":");
    mo_json_append_str(t, cid);
    if (csec) {
        sqlite3_str_appendall(t, ",\"client_secret\":");
        mo_json_append_str(t, csec);
    }
    if (amethod) {
        sqlite3_str_appendall(t, ",\"token_endpoint_auth_method\":");
        mo_json_append_str(t, amethod);
    }
    if (ruris) {
        sqlite3_str_appendf(t, ",\"redirect_uris\":%s", ruris);
    } else {
        sqlite3_str_appendall(t, ",\"redirect_uris\":[");
        mo_json_append_str(t, redirect_uri);
        sqlite3_str_appendall(t, "]");
    }
    sqlite3_str_appendall(t, "}");
    {
        int n = sqlite3_str_length(t);
        char *res = sqlite3_str_finish(t);
        if (res) {
            *client_json = strdup(res);
            pic_cred_wipe(res, (size_t)n);
            sqlite3_free(res);
        }
    }
    free(cid);
    mo_free_secret(csec);
    free(amethod);
    free(ruris);
    if (!*client_json) {
        if (err) {
            (void)snprintf(err, errcap, "out of memory");
        }
        return -1;
    }
    return 0;
}

/* ---- self-healing invalidation ------------------------------------------------------------- */

static void mo_invalidate(const char *server_key, int drop_client, int drop_tokens, int drop_discovery) {
    char *state = NULL, *next = NULL;
    if (mo_state_load(server_key, &state, NULL, 0) != 0 || !state) {
        return;
    }
    if (drop_client && drop_tokens && drop_discovery) {
        next = mo_jtext("SELECT json_remove(?1, '$.client', '$.tokens', '$.tokensExpireAt', '$.discovery')", state, NULL);
    } else if (drop_tokens) {
        next = mo_jtext("SELECT json_remove(?1, '$.tokens', '$.tokensExpireAt')", state, NULL);
    }
    mo_free_secret(state);
    if (next) {
        (void)mo_state_save(server_key, next, NULL, 0);
        mo_free_secret(next);
    }
}

/* ---- probe MCP server for WWW-Authenticate challenge --------------------------------------- */

static int mo_probe_sink(void *ctx, const char *bytes, size_t n) {
    (void)ctx;
    (void)bytes;
    (void)n;
    return 0;
}

static void mo_probe_challenge(const char *server_url, const char *existing_token, pic_mcp_oauth_challenge *ch) {
    static const char body[] = "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"server/discover\",\"params\":{"
                               "\"_meta\":{\"io.modelcontextprotocol/protocolVersion\":\"" PIC_MCP_CURRENT "\"}}}";
    const char *hdrs[6];
    char *auth_hdr = NULL, err[160] = "", ubuf[1200];
    size_t nh = 0;
    pic_net *net;
    pic_http_resp r;
    const char *u = server_url;
    memset(ch, 0, sizeof *ch);
    {
        const char *p = strstr(server_url, "://"), *d;
        if (!p || strchr(server_url, '#')) {
            return;
        }
        d = (p + 3) + strcspn(p + 3, "/?");
        if (*d == '\0') {
            if (snprintf(ubuf, sizeof ubuf, "%s/", server_url) >= (int)sizeof ubuf) {
                return;
            }
            u = ubuf;
        } else if (*d == '?') {
            if (snprintf(ubuf, sizeof ubuf, "%.*s/%s", (int)(d - server_url), server_url, d) >= (int)sizeof ubuf) {
                return;
            }
            u = ubuf;
        }
    }
    hdrs[nh++] = "Content-Type: application/json";
    hdrs[nh++] = "Accept: application/json, text/event-stream";
    hdrs[nh++] = "User-Agent: pic";
    hdrs[nh++] = "MCP-Protocol-Version: " PIC_MCP_CURRENT;
    if (existing_token && *existing_token) {
        size_t cap = strlen(existing_token) + 24;
        if ((auth_hdr = malloc(cap))) {
            (void)snprintf(auth_hdr, cap, "Authorization: Bearer %s", existing_token);
            hdrs[nh++] = auth_hdr;
        }
    }
    if ((net = pic_net_new(err, sizeof err))) {
        pic_http_resp_init(&r, mo_probe_sink, NULL);
        if (pic_http_post(net, u, hdrs, nh, body, sizeof body - 1, &r, 10, 10, err, sizeof err) == 0 &&
            (r.status == 401 || r.status == 403) && r.www_authenticate[0]) {
            pic_mcp_oauth_parse_www_auth(r.www_authenticate, ch);
        }
        pic_net_free(net);
    }
    mo_free_secret(auth_hdr);
}

/* ---- interactive sign-in (pic mcp login) --------------------------------------------------- */

static int mo_scope_has_word(const char *scope, const char *word) {
    return scope && word && mo_scope_contains(scope, strlen(scope), word, strlen(word));
}

int pic_mcp_oauth_login(const char *server_name, const char *server_url, const pic_mcp_oauth_cfg *cfg,
                        const char *client_secret_override, const pic_oauth_io *io, int timeout_seconds, char *err,
                        size_t errcap) {
    pic_mcp_oauth_cfg empty_cfg;
    char key[1400], verifier[64], challenge_code[64], state_tok[64], redirect_uri[600], scope[1024];
    char cb_path[256] = "/callback", cb_host[128] = "127.0.0.1", oauth_err[128] = "";
    int cb_port = 0, cb_fixed = 0, rc = -1, using_dcr = 0;
    char *stored = NULL, *existing_tok = NULL, *existing_scope = NULL, *cfg_secret = NULL;
    char *pending_scope = NULL, *pending_prm = NULL;
    char *client_id = NULL, *client_secret = NULL, *auth_hint = NULL, *client_json = NULL;
    char *auth_url = NULL, *query = NULL, *pasted = NULL, *code = NULL, *iss = NULL;
    char *tok_resp = NULL, *tokens_json = NULL, *disc_json = NULL, *new_state = NULL;
    long long expires_at = 0;
    pic_mcp_oauth_challenge ch;
    mo_discovery disc;
    pic_oauth_callback cb;
    memset(&empty_cfg, 0, sizeof empty_cfg);
    if (!cfg) {
        cfg = &empty_cfg;
    }
    cb.fd = -1;
    verifier[0] = '\0';
    if (pic_mcp_oauth_url_allowed(server_url, err, errcap) != 0) {
        return -1;
    }
    if (pic_mcp_oauth_server_key(server_name, server_url, key, sizeof key) < 0) {
        (void)snprintf(err, errcap, "invalid MCP server name or URL");
        return -1;
    }
    if (pic_cred_prepare(err, errcap) != 0) {
        return -1;
    }
    if (mo_state_load(key, &stored, NULL, 0) == 0 && stored) {
        existing_tok = mo_jtext("SELECT json_extract(?1, '$.tokens.access_token')"
                                " WHERE json_type(?1, '$.tokens.access_token') = 'text'",
                                stored, NULL);
        existing_scope = mo_jtext("SELECT json_extract(?1, '$.tokens.scope')"
                                  " WHERE json_type(?1, '$.tokens.scope') = 'text'",
                                  stored, NULL);
        cfg_secret = mo_jtext("SELECT json_extract(?1, '$.configuredClientSecret')"
                              " WHERE json_type(?1, '$.configuredClientSecret') = 'text'",
                              stored, NULL);
        pending_scope = mo_jtext("SELECT json_extract(?1, '$.pendingScope')"
                                 " WHERE json_type(?1, '$.pendingScope') = 'text'",
                                 stored, NULL);
        pending_prm = mo_jtext("SELECT json_extract(?1, '$.pendingResourceMetadata')"
                               " WHERE json_type(?1, '$.pendingResourceMetadata') = 'text'",
                               stored, NULL);
    }

    /* Probe MCP server for WWW-Authenticate challenge (resource_metadata, scope). */
    pic_oauth_say(io, "Discovering OAuth metadata...");
    mo_probe_challenge(server_url, existing_tok, &ch);
    if (!ch.resource_metadata[0] && pending_prm && *pending_prm) {
        (void)snprintf(ch.resource_metadata, sizeof ch.resource_metadata, "%s", pending_prm);
    }
    if (pending_scope && *pending_scope) {
        char merged_ch[512];
        if (pic_mcp_oauth_step_up_scope(pending_scope, ch.scope, NULL, merged_ch, sizeof merged_ch) >= 0) {
            (void)snprintf(ch.scope, sizeof ch.scope, "%s", merged_ch);
        }
    }
    if (mo_discover(server_url, ch.resource_metadata, cfg->auth_server_metadata_url, &disc, err, errcap) != 0) {
        goto out;
    }
    if (disc.has_metadata) {
        if (!disc.supports_code) {
            (void)snprintf(err, errcap, "authorization server does not support authorization codes (response_type=code)");
            goto out;
        }
        if (!disc.supports_s256) {
            (void)snprintf(err, errcap, "authorization server does not support PKCE S256");
            goto out;
        }
    }

    /* Loopback callback setup. */
    if (cfg->callback_url[0]) {
        mo_url cbu;
        if (pic_mcp_oauth_callback_allowed(cfg->callback_url, err, errcap) != 0 ||
            mo_url_parse(cfg->callback_url, &cbu, err, errcap) != 0) {
            goto out;
        }
        if (strlen(cbu.path) >= sizeof cb_path) {
            (void)snprintf(err, errcap, "OAuth callbackUrl path is too long");
            goto out;
        }
        (void)snprintf(cb_host, sizeof cb_host, "%s%s%s", cbu.ipv6 ? "[" : "", cbu.host, cbu.ipv6 ? "]" : "");
        memcpy(cb_path, cbu.path, strlen(cbu.path) + 1);
        if (cbu.has_port) {
            cb_port = cbu.port;
            cb_fixed = 1;
        } else if (cfg->callback_port > 0) {
            cb_port = cfg->callback_port;
        }
    } else if (cfg->callback_port > 0) {
        cb_port = cfg->callback_port;
    }
    if (pic_oauth_pkce(verifier, challenge_code) != 0 || pic_oauth_random(state_tok, sizeof state_tok, 32) != 0) {
        (void)snprintf(err, errcap, "no entropy for OAuth sign-in");
        goto out;
    }
    {
        int lrc = pic_oauth_listen_host(&cb, cb_host, cb_port, cb_path, state_tok, err, errcap);
        if (lrc == -2) {
            (void)snprintf(err, errcap, "callback port %d is already in use; close the other sign-in and try again", cb_port);
        }
        if (lrc != 0) {
            goto out;
        }
    }
    if (cb_fixed) {
        (void)snprintf(redirect_uri, sizeof redirect_uri, "%s", cfg->callback_url);
    } else {
        (void)snprintf(redirect_uri, sizeof redirect_uri, "http://%s:%d%s", cb_host, cb.port, cb_path);
    }

    /* Step-up scope union: configured + existing + challenged (else PRM scopes_supported). */
    if (pic_mcp_oauth_step_up_scope(cfg->scope, existing_scope, ch.scope, scope, sizeof scope) < 0) {
        (void)snprintf(err, errcap, "OAuth scope list is too long");
        goto out;
    }
    if (!scope[0] && disc.prm_scopes[0]) {
        (void)snprintf(scope, sizeof scope, "%s", disc.prm_scopes);
    }

    /* Client identification: pre-registered, else cached DCR if redirect_uris matches, else DCR. */
    if (cfg->client_id[0]) {
        client_id = strdup(cfg->client_id);
        if (client_secret_override && *client_secret_override) {
            client_secret = strdup(client_secret_override);
        } else if (cfg_secret && *cfg_secret) {
            client_secret = strdup(cfg_secret);
        }
    } else {
        if (stored && mo_jint("SELECT count(*) FROM json_each(?1, '$.client.redirect_uris')"
                              " WHERE json_type(?1, '$.client.redirect_uris') = 'array' AND type = 'text' AND value = ?2",
                              stored, redirect_uri, 0) > 0) {
            client_json = mo_jtext("SELECT json(json_extract(?1, '$.client')) WHERE json_type(?1, '$.client') = 'object'",
                                   stored, NULL);
        }
        if (!client_json) {
            pic_oauth_say(io, "Registering OAuth client...");
            if (mo_dcr_register(&disc, redirect_uri, cfg->client_name, scope[0] ? scope : NULL, &client_json, err, errcap) !=
                0) {
                goto out;
            }
        }
        using_dcr = 1;
        client_id = mo_jtext("SELECT json_extract(?1, '$.client_id')", client_json, NULL);
        client_secret = mo_jtext("SELECT json_extract(?1, '$.client_secret') WHERE json_type(?1, '$.client_secret') = 'text'",
                                 client_json, NULL);
        auth_hint = mo_jtext("SELECT json_extract(?1, '$.token_endpoint_auth_method')"
                             " WHERE json_type(?1, '$.token_endpoint_auth_method') = 'text'",
                             client_json, NULL);
    }
    if (!client_id || !*client_id) {
        (void)snprintf(err, errcap, "out of memory");
        goto out;
    }

    /* Build authorization URL and open browser / wait for callback or paste. */
    {
        const char *prompt = mo_scope_has_word(scope, "offline_access") ? "consent" : NULL;
        const char *pairs[] = {"response_type", "code", "client_id", client_id, "code_challenge", challenge_code,
                               "code_challenge_method", "S256", "redirect_uri", redirect_uri, "state", state_tok,
                               "scope", scope[0] ? scope : NULL, "prompt", prompt, "resource",
                               disc.resource[0] ? disc.resource : NULL, NULL};
        char *q = pic_oauth_form(pairs);
        size_t n = q ? strlen(disc.auth_endpoint) + strlen(q) + 2 : 0;
        if (!q || !(auth_url = malloc(n))) {
            free(q);
            (void)snprintf(err, errcap, "out of memory");
            goto out;
        }
        (void)snprintf(auth_url, n, "%s%c%s", disc.auth_endpoint, strchr(disc.auth_endpoint, '?') ? '&' : '?', q);
        free(q);
    }
    pic_oauth_show_url(io, auth_url,
                       "Sign in in the browser. If the browser cannot reach this machine, paste the redirect URL here and press Enter.");
    if (pic_oauth_wait(&cb, io, timeout_seconds > 0 ? timeout_seconds : MO_DEFAULT_TIMEOUT, &query, &pasted, err, errcap) !=
        0) {
        goto out;
    }
    pic_oauth_close(&cb);
    if (pasted && pic_oauth_pasted_query(pasted, redirect_uri, state_tok, &query, err, errcap) != 0) {
        goto out;
    }
    code = pic_oauth_param(query, "code");
    iss = pic_oauth_param(query, "iss");
    if (!code || !*code) {
        (void)snprintf(err, errcap, "the redirect carried no authorization code");
        goto out;
    }
    if (pic_mcp_oauth_check_iss(iss, disc.issuer, disc.iss_supported, err, errcap) != 0) {
        goto out;
    }

    /* Exchange authorization code for tokens. */
    pic_oauth_say(io, "Exchanging authorization code for tokens...");
    {
        const char *pairs[] = {"grant_type", "authorization_code", "code", code, "code_verifier", verifier,
                               "redirect_uri", redirect_uri, "resource", disc.resource[0] ? disc.resource : NULL, NULL};
        if (mo_token_post(disc.token_endpoint, client_id, client_secret, auth_hint, disc.auth_methods_json, pairs,
                          &tok_resp, oauth_err, sizeof oauth_err, err, errcap) != 0) {
            if (strcmp(oauth_err, "invalid_client") == 0 || strcmp(oauth_err, "unauthorized_client") == 0) {
                if (using_dcr) {
                    mo_invalidate(key, 1, 1, 1);
                }
            } else if (strcmp(oauth_err, "invalid_grant") == 0) {
                mo_invalidate(key, 0, 1, 0);
            }
            goto out;
        }
    }
    if (mo_build_tokens_json(tok_resp, NULL, scope[0] ? scope : NULL, &tokens_json, &expires_at, err, errcap) != 0) {
        goto out;
    }
    disc_json = mo_build_discovery_json(&disc);
    if (!disc_json) {
        (void)snprintf(err, errcap, "out of memory");
        goto out;
    }
    {
        sqlite3_str *t = sqlite3_str_new(NULL);
        char *res;
        int n;
        sqlite3_str_appendall(t, "{\"serverUrl\":");
        mo_json_append_str(t, server_url);
        if (cfg_secret && *cfg_secret) {
            sqlite3_str_appendall(t, ",\"configuredClientSecret\":");
            mo_json_append_str(t, cfg_secret);
        }
        if (client_json) {
            sqlite3_str_appendf(t, ",\"client\":%s", client_json);
        }
        sqlite3_str_appendf(t, ",\"tokens\":%s", tokens_json);
        if (expires_at > 0) {
            sqlite3_str_appendf(t, ",\"tokensExpireAt\":%lld", expires_at);
        }
        sqlite3_str_appendf(t, ",\"discovery\":%s}", disc_json);
        n = sqlite3_str_length(t);
        res = sqlite3_str_finish(t);
        if (res) {
            new_state = strdup(res);
            pic_cred_wipe(res, (size_t)n);
            sqlite3_free(res);
        }
    }
    if (!new_state) {
        (void)snprintf(err, errcap, "out of memory");
        goto out;
    }
    rc = mo_state_save(key, new_state, err, errcap);

out:
    pic_oauth_close(&cb);
    pic_cred_wipe(verifier, sizeof verifier);
    pic_cred_wipe(state_tok, sizeof state_tok);
    mo_free_secret(stored);
    mo_free_secret(existing_tok);
    free(existing_scope);
    free(pending_scope);
    free(pending_prm);
    mo_free_secret(cfg_secret);
    free(client_id);
    mo_free_secret(client_secret);
    free(auth_hint);
    mo_free_secret(client_json);
    free(auth_url);
    mo_free_secret(query);
    mo_free_secret(pasted);
    mo_free_secret(code);
    free(iss);
    mo_free_secret(tok_resp);
    mo_free_secret(tokens_json);
    free(disc_json);
    mo_free_secret(new_state);
    return rc;
}

/* ---- locked token refresh & transport callbacks -------------------------------------------- */

/* Performs a cross-process locked refresh for CTX.
 * STALE non-NULL: reactive 401 refresh (skip if stored access_token already differs from STALE).
 * STALE NULL: proactive expiry refresh (skip if stored token no longer expires within skew).
 * Returns 1 with fresh token in OUT, 0 when interactive sign-in is required, -1 on error. */
static int mo_refresh_locked(const pic_mcp_oauth_ctx *ctx, const char *stale, const pic_mcp_oauth_challenge *ch, char *out,
                             size_t cap, char *err, size_t errcap) {
    char key[1400], oauth_err[128] = "";
    char *state = NULL, *cur_access = NULL, *refresh_tok = NULL, *cur_scope = NULL;
    char *client_id = NULL, *client_secret = NULL, *auth_hint = NULL, *token_ep = NULL, *methods_json = NULL,
         *resource = NULL, *resp = NULL, *new_tokens = NULL, *updated = NULL;
    long long cur_exp = 0, new_exp = 0;
    int lock = -1, rc = 0, got, using_dcr = 0;
    out[0] = '\0';
    if (pic_mcp_oauth_server_key(ctx->name, ctx->url, key, sizeof key) < 0) {
        return 0;
    }
    if ((lock = mo_refresh_lock(key, err, errcap)) < 0) {
        return -1;
    }
    got = mo_state_load(key, &state, err, errcap);
    if (got != 0 || !state) {
        rc = got < 0 ? -1 : 0;
        goto out;
    }
    cur_access = mo_jtext("SELECT json_extract(?1, '$.tokens.access_token')"
                          " WHERE json_type(?1, '$.tokens.access_token') = 'text'",
                          state, NULL);
    cur_exp = mo_jint("SELECT coalesce(json_extract(?1, '$.tokensExpireAt'), json_extract(?1, '$.tokens.expires_at'), 0)",
                      state, NULL, 0);
    /* Another process already rotated the access token while we waited for the lock. */
    if (cur_access && *cur_access) {
        if ((stale && strcmp(cur_access, stale) != 0) || (!stale && (cur_exp <= 0 || cur_exp - MO_REFRESH_SKEW_MS > mo_now_ms()))) {
            if (strlen(cur_access) < cap) {
                memcpy(out, cur_access, strlen(cur_access) + 1);
                rc = 1;
            } else {
                rc = -1;
            }
            goto out;
        }
    }
    refresh_tok = mo_jtext("SELECT json_extract(?1, '$.tokens.refresh_token')"
                           " WHERE json_type(?1, '$.tokens.refresh_token') = 'text'"
                           " AND length(json_extract(?1, '$.tokens.refresh_token')) > 0",
                           state, NULL);
    if (!refresh_tok) {
        rc = 0; /* no refresh token: caller must prompt for pic mcp login */
        goto out;
    }
    cur_scope = mo_jtext("SELECT json_extract(?1, '$.tokens.scope') WHERE json_type(?1, '$.tokens.scope') = 'text'", state,
                         NULL);

    /* Resolve client credentials. */
    if (ctx->cfg.client_id[0]) {
        client_id = strdup(ctx->cfg.client_id);
        if (ctx->client_secret_override && *ctx->client_secret_override) {
            client_secret = strdup(ctx->client_secret_override);
        } else {
            client_secret = mo_jtext("SELECT json_extract(?1, '$.configuredClientSecret')"
                                     " WHERE json_type(?1, '$.configuredClientSecret') = 'text'",
                                     state, NULL);
        }
    } else {
        using_dcr = 1;
        client_id = mo_jtext("SELECT json_extract(?1, '$.client.client_id') WHERE json_type(?1, '$.client.client_id') = 'text'",
                             state, NULL);
        client_secret = mo_jtext("SELECT json_extract(?1, '$.client.client_secret')"
                                 " WHERE json_type(?1, '$.client.client_secret') = 'text'",
                                 state, NULL);
        auth_hint = mo_jtext("SELECT json_extract(?1, '$.client.token_endpoint_auth_method')"
                             " WHERE json_type(?1, '$.client.token_endpoint_auth_method') = 'text'",
                             state, NULL);
    }
    if (!client_id || !*client_id) {
        rc = 0;
        goto out;
    }

    /* Resolve token endpoint (from cached discovery, or fresh discovery when override/missing). */
    if (!ctx->cfg.auth_server_metadata_url[0]) {
        token_ep = mo_jtext("SELECT json_extract(?1, '$.discovery.token_endpoint')"
                            " WHERE json_type(?1, '$.discovery.token_endpoint') = 'text'"
                            " AND length(json_extract(?1, '$.discovery.token_endpoint')) > 0",
                            state, NULL);
        methods_json = mo_jtext("SELECT json(json_extract(?1, '$.discovery.token_endpoint_auth_methods_supported'))"
                                " WHERE json_type(?1, '$.discovery.token_endpoint_auth_methods_supported') = 'array'",
                                state, NULL);
        resource = mo_jtext("SELECT json_extract(?1, '$.discovery.resource')"
                            " WHERE json_type(?1, '$.discovery.resource') = 'text'"
                            " AND length(json_extract(?1, '$.discovery.resource')) > 0",
                            state, NULL);
    }
    if (!token_ep) {
        mo_discovery disc;
        if (mo_discover(ctx->url, ch ? ch->resource_metadata : NULL, ctx->cfg.auth_server_metadata_url, &disc, err, errcap) !=
            0) {
            rc = 0;
            goto out;
        }
        token_ep = strdup(disc.token_endpoint);
        free(methods_json);
        methods_json = strdup(disc.auth_methods_json);
        free(resource);
        resource = disc.resource[0] ? strdup(disc.resource) : NULL;
    }
    if (!token_ep || !*token_ep) {
        rc = 0;
        goto out;
    }

    {
        const char *pairs[] = {"grant_type", "refresh_token", "refresh_token", refresh_tok, "resource",
                               resource && *resource ? resource : NULL, NULL};
        if (mo_token_post(token_ep, client_id, client_secret, auth_hint, methods_json, pairs, &resp, oauth_err,
                          sizeof oauth_err, err, errcap) != 0) {
            if (strcmp(oauth_err, "invalid_client") == 0 || strcmp(oauth_err, "unauthorized_client") == 0) {
                mo_invalidate(key, using_dcr, 1, 1);
            } else if (strcmp(oauth_err, "invalid_grant") == 0) {
                mo_invalidate(key, 0, 1, 0);
            }
            rc = 0;
            goto out;
        }
    }
    if (mo_build_tokens_json(resp, refresh_tok, cur_scope, &new_tokens, &new_exp, err, errcap) != 0) {
        rc = 0;
        goto out;
    }
    {
        char exp_s[32];
        (void)snprintf(exp_s, sizeof exp_s, "%lld", new_exp);
        updated = new_exp > 0 ? mo_jtext3("SELECT json_set(?1, '$.tokens', json(?2), '$.tokensExpireAt', CAST(?3 AS INTEGER))",
                                          state, new_tokens, exp_s)
                              : mo_jtext("SELECT json_set(json_remove(?1, '$.tokensExpireAt'), '$.tokens', json(?2))", state,
                                         new_tokens);
    }
    if (!updated || mo_state_save(key, updated, err, errcap) != 0) {
        rc = -1;
        goto out;
    }
    {
        char *fresh = mo_jtext("SELECT json_extract(?1, '$.access_token')", new_tokens, NULL);
        if (fresh && strlen(fresh) < cap) {
            memcpy(out, fresh, strlen(fresh) + 1);
            rc = 1;
        } else {
            rc = -1;
        }
        mo_free_secret(fresh);
    }

out:
    mo_free_secret(state);
    mo_free_secret(cur_access);
    mo_free_secret(refresh_tok);
    free(cur_scope);
    free(client_id);
    mo_free_secret(client_secret);
    free(auth_hint);
    free(token_ep);
    free(methods_json);
    free(resource);
    mo_free_secret(resp);
    mo_free_secret(new_tokens);
    mo_free_secret(updated);
    if (lock >= 0) {
        pic_platform_get()->unlock(lock);
    }
    return rc;
}

static int mo_hook_bearer(void *vctx, char *out, size_t cap, char *err, size_t errcap) {
    const pic_mcp_oauth_ctx *ctx = vctx;
    char key[1400], qerr[128] = "";
    char *state = NULL, *access = NULL;
    long long exp = 0;
    int has_refresh = 0, qrc;
    out[0] = '\0';
    if (pic_mcp_oauth_server_key(ctx->name, ctx->url, key, sizeof key) < 0 || !mo_row_exists(key)) {
        return 0;
    }
    qrc = ctx->quiet ? pic_cred_quiet(qerr, sizeof qerr) : pic_cred_unlock(qerr, sizeof qerr);
    if (qrc != 0) {
        /* If store is locked during quiet background call, proceed without token so 401 reports cleanly. */
        return 0;
    }
    if (mo_state_load(key, &state, NULL, 0) != 0 || !state) {
        return 0;
    }
    access = mo_jtext("SELECT json_extract(?1, '$.tokens.access_token')"
                      " WHERE json_type(?1, '$.tokens.access_token') = 'text'"
                      " AND length(json_extract(?1, '$.tokens.access_token')) > 0",
                      state, NULL);
    exp = mo_jint("SELECT coalesce(json_extract(?1, '$.tokensExpireAt'), json_extract(?1, '$.tokens.expires_at'), 0)", state,
                  NULL, 0);
    has_refresh = mo_jint("SELECT json_type(?1, '$.tokens.refresh_token') = 'text'"
                          " AND length(json_extract(?1, '$.tokens.refresh_token')) > 0",
                          state, NULL, 0) == 1;
    mo_free_secret(state);
    if (!access) {
        return 0;
    }
    /* Proactive refresh when within 30 s of expiry. */
    if (exp > 0 && exp - MO_REFRESH_SKEW_MS <= mo_now_ms() && has_refresh) {
        char rerr[256] = "";
        int rrc = mo_refresh_locked(ctx, NULL, NULL, out, cap, rerr, sizeof rerr);
        if (rrc == 1 && out[0]) {
            mo_free_secret(access);
            return 1;
        }
        /* Fall through with existing token if still present in store (401 will decide). */
        if (mo_state_load(key, &state, NULL, 0) == 0 && state) {
            int still = mo_jint("SELECT json_type(?1, '$.tokens.access_token') = 'text'", state, NULL, 0) == 1;
            mo_free_secret(state);
            if (!still) {
                mo_free_secret(access);
                return 0;
            }
        }
    }
    if (strlen(access) >= cap) {
        mo_free_secret(access);
        if (err) {
            (void)snprintf(err, errcap, "OAuth access token is too long");
        }
        return -1;
    }
    memcpy(out, access, strlen(access) + 1);
    mo_free_secret(access);
    return 1;
}

static int mo_hook_on_unauth(void *vctx, int status, const char *www_auth, const char *stale, char *out, size_t cap,
                             char *err, size_t errcap) {
    const pic_mcp_oauth_ctx *ctx = vctx;
    pic_mcp_oauth_challenge ch;
    char key[1400], qerr[128] = "";
    out[0] = '\0';
    pic_mcp_oauth_parse_www_auth(www_auth, &ch);
    if (strcmp(ch.error, "insufficient_scope") == 0) {
        if ((ch.scope[0] || ch.resource_metadata[0]) &&
            pic_mcp_oauth_server_key(ctx->name, ctx->url, key, sizeof key) >= 0 &&
            (ctx->quiet ? pic_cred_quiet(qerr, sizeof qerr) : pic_cred_unlock(qerr, sizeof qerr)) == 0) {
            int lock = mo_refresh_lock(key, NULL, 0);
            if (lock >= 0) {
                char *state = NULL, *next = NULL;
                int got = mo_state_load(key, &state, NULL, 0);
                if (got >= 0) {
                    next = mo_jtext3("SELECT json_set(coalesce(?1, '{}'), '$.pendingScope', nullif(?2, ''),"
                                     " '$.pendingResourceMetadata', nullif(?3, ''))",
                                     state, ch.scope, ch.resource_metadata);
                    if (next) {
                        (void)mo_state_save(key, next, NULL, 0);
                        mo_free_secret(next);
                    }
                }
                mo_free_secret(state);
                pic_platform_get()->unlock(lock);
            }
        }
        if (err && errcap) {
            if (ch.scope[0]) {
                (void)snprintf(err, errcap, "insufficient_scope (requires %s)", ch.scope);
                mo_clean(err);
            } else {
                (void)snprintf(err, errcap, "insufficient_scope");
            }
        }
        return 0;
    }
    if (status == 403) {
        return 0;
    }
    if (pic_mcp_oauth_server_key(ctx->name, ctx->url, key, sizeof key) < 0 || !mo_row_exists(key)) {
        return 0;
    }
    if ((ctx->quiet ? pic_cred_quiet(qerr, sizeof qerr) : pic_cred_unlock(qerr, sizeof qerr)) != 0) {
        if (err && errcap) {
            (void)snprintf(err, errcap, "credential store is locked");
        }
        return 0;
    }
    return mo_refresh_locked(ctx, stale, &ch, out, cap, err, errcap);
}

void pic_mcp_oauth_attach(pic_mcp_oauth_ctx *ctx, const char *server_name, const char *server_url,
                          const pic_mcp_oauth_cfg *cfg, const char *client_secret_override, int quiet,
                          pic_mcp_auth *out) {
    memset(ctx, 0, sizeof *ctx);
    memset(out, 0, sizeof *out);
    if (!server_url || !*server_url) {
        return;
    }
    (void)snprintf(ctx->name, sizeof ctx->name, "%s", server_name ? server_name : "");
    (void)snprintf(ctx->url, sizeof ctx->url, "%s", server_url);
    if (cfg) {
        ctx->cfg = *cfg;
    }
    if (client_secret_override && *client_secret_override) {
        ctx->client_secret_override = strdup(client_secret_override);
    }
    ctx->quiet = quiet;
    out->bearer = mo_hook_bearer;
    out->on_unauth = mo_hook_on_unauth;
    out->ctx = ctx;
}

void pic_mcp_oauth_ctx_free(pic_mcp_oauth_ctx *ctx) {
    if (!ctx) {
        return;
    }
    mo_free_secret(ctx->client_secret_override);
    memset(ctx, 0, sizeof *ctx);
}