feat(mcp): OAuth per-user connectors (§15) — providers, PKCE copy-paste flow, env credential delivery

- oauth_providers registry table (per-provider client creds) + db/oauth_providers.rs
- mcp/oauth.rs: authorization-code + PKCE S256, RAM-only TTL'd flow store, copy-paste consent
- mcp/install.rs + verify.rs: connector file install + manifest verification
- activate persists a pending row (needs_oauth); /mcp/oauth/start + /complete exchange code for refresh token
- credential delivery via env var on docker exec (google_authorized_user JSON), never on disk
- mcp_catalog/mcp_user_servers: additive OAuth columns (ensure_column), catalog_name/oauth_provider/deliver_json bare TEXT snapshots
- frontend: connector-detail.js (OAuth login panel), shared/connector-common.js, connectors.js admin Sign-in providers modal
- API: /mcp/providers (admin OAuth creds), /mcp/oauth/start|complete
- .gitignore: add /homes/ (instance data), /connectors/, /reset.sh; drop stale /secrets/
This commit is contained in:
2026-07-17 21:47:51 +01:00
parent bcd8f7b5c0
commit e6c4e202a4
28 changed files with 3349 additions and 553 deletions
+1 -1
View File
@@ -301,7 +301,7 @@ export class CatalogPage extends LightElement {
${this._select('Transport', f.transport, ['stdio', 'http', 'sse'], e => this._patch('transport', e.target.value))}
${isScript
? html`${this._field('Command', f.command, e => this._patch('command', e.target.value), { placeholder: 'python3', mono: true })}
${this._field('Script path', f.script_path, e => this._patch('script_path', e.target.value), { hint: 'under ./scripts', mono: true })}`
${this._field('Script path', f.script_path, e => this._patch('script_path', e.target.value), { hint: 'as <connector>/<file>, under ./connectors', mono: true })}`
: this._field('URL', f.url, e => this._patch('url', e.target.value), { mono: true })}
${this._field('Args', f.args, e => this._patch('args', e.target.value), { hint: 'one per line', mono: true })}
${this._field('Required secret/env keys', f.config_schema, e => this._patch('config_schema', e.target.value), { hint: 'comma/newline', mono: true })}
+626
View File
@@ -0,0 +1,626 @@
import { html, nothing } from 'lit';
import { LightElement } from '../lib/base.js';
import {
announceChange, connectorIconUrl, jf, normalizeSchema, parseJson, seedEnv, statusOf,
} from './shared/connector-common.js';
// One connector's own page — `#connector?name=<catalog name>`.
//
// This replaces the activation dialog. A connector declares its own env/secret
// schema, so the form's height is the *connector's* choice, not the UI's: EMAIL asks
// for a dozen fields, and a fixed-size modal simply could not hold them — it grew
// taller than the viewport and the buttons went off-screen. A page scrolls.
//
// It is also the natural home for everything else that is per-connector and was
// scattered before: the Test button, the global enable, and the per-user access
// grants — which used to be a second modal reached from a third place.
//
// Deliberately not a `name` field: the list is one row per connector (§7 template),
// so the runtime name is the catalog name. The backend still defends against
// collisions; the UI just stops offering a way to cause them.
const ADMIN_ID = 'admin';
const PAGE_ID = 'connector';
function nameFromHash() {
const m = location.hash.match(/^#connector\?name=(.*)$/);
if (!m) return null;
try { return decodeURIComponent(m[1]); } catch { return null; }
}
export class ConnectorDetailPage extends LightElement {
static get properties() {
return {
_open: { state: true },
_name: { state: true },
_me: { state: true },
_entry: { state: true }, // catalog row (null for a global we cannot read)
_act: { state: true }, // my activation row, if any
_glob: { state: true }, // the global instance, if any
_schema: { state: true },
_form: { state: true }, // { api_key, env: {} }
_test: { state: true }, // null | 'running' | report
_busy: { state: true },
_error: { state: true },
_users: { state: true }, // admin: for the access panel
_access: { state: true }, // admin: Set of granted user ids
_noIcon: { state: true },
_oauth: { state: true }, // in-flight OAuth login: { state, auth_url, code }
};
}
constructor() {
super();
this._open = false;
this._noIcon = false;
this._reset();
}
_reset() {
this._name = null;
this._me = null;
this._entry = null;
this._act = null;
this._glob = null;
this._schema = [];
this._form = { api_key: '', env: {} };
this._test = null;
this._busy = false;
this._error = null;
this._users = null;
this._access = null;
this._oauth = null;
}
connectedCallback() {
super.connectedCallback();
window.addEventListener('llm-page-change', (e) => {
this._open = e.detail.page === PAGE_ID;
this.style.display = this._open ? 'flex' : 'none';
if (this._open) this._loadFromHash();
});
window.addEventListener('hashchange', () => {
if (this._open) this._loadFromHash();
});
}
get _isAdmin() { return this._me?.role_id === ADMIN_ID; }
get _isGlobal() { return (this._entry?.scope ?? (this._glob ? 'global' : null)) === 'global'; }
get _status() { return statusOf({ _act: this._act, _glob: this._glob }); }
async _loadFromHash() {
const name = nameFromHash();
if (!name) return;
// A different connector must not inherit the previous one's typed secrets.
if (name !== this._name) this._reset();
this._name = name;
await this._load();
}
async _load() {
this._error = null;
try {
this._me = await jf('/api/auth/me');
const [available, activated] = await Promise.all([
jf('/api/mcp/available'),
jf('/api/mcp/activated'),
]);
const entry = (available?.catalog ?? []).find(e => e.name === this._name) ?? null;
const glob = (available?.globals ?? [])
.find(g => (g.catalog_name ?? g.name) === this._name) ?? null;
const act = (activated ?? []).find(r => r.catalog_name === this._name) ?? null;
if (!entry && !glob) {
this._error = `No connector named “${this._name}” is available to you.`;
return;
}
this._entry = entry;
this._glob = glob;
this._act = act;
const schema = normalizeSchema(parseJson(entry?.config_schema_json, []));
this._schema = schema;
// Keep whatever the user has already typed across a reload triggered by a save.
this._form = { api_key: this._form.api_key || '', env: { ...seedEnv(schema), ...this._form.env } };
if (this._isAdmin && this._isGlobal) await this._loadAccess();
} catch (e) {
this._error = e.message;
}
}
async _loadAccess() {
try {
this._users = await jf('/api/users');
if (this._glob) {
const granted = await jf(`/api/mcp/global/${this._glob.id}/access`);
this._access = new Set(granted || []);
}
} catch (e) { this._error = e.message; }
}
_back() {
// Prefer real history so the browser's own Back stays consistent; fall back to
// the list when this page was opened straight from a pasted URL.
if (history.length > 1) { history.back(); return; }
history.pushState({ page: 'connectors' }, '', '#connectors');
window.dispatchEvent(new CustomEvent('llm-page-change', { detail: { page: 'connectors' } }));
}
_patchEnv(key, value) {
this._form = { ...this._form, env: { ...this._form.env, [key]: value } };
}
/// The env map to send: empty fields are dropped so a blank box means "unset"
/// rather than "set to empty string".
get _envPayload() {
const env = {};
for (const [k, v] of Object.entries(this._form.env || {})) if (v !== '') env[k] = v;
return Object.keys(env).length ? env : null;
}
// ── Actions ────────────────────────────────────────────────────────────────
async _testCreds() {
this._test = 'running';
try {
this._test = await jf('/api/mcp/test', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
catalog_name: this._name,
api_key: this._form.api_key || null,
env: this._envPayload,
}),
});
} catch (e) {
this._test = { ok: false, message: e.message };
}
}
async _activate() {
this._busy = true; this._error = null;
try {
const res = await jf('/api/mcp/activate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
catalog_name: this._name,
api_key: this._form.api_key || null,
env: this._envPayload,
}),
});
if (res?.auth_state === 'pending') {
this._test = res.verify ?? { ok: false, message: 'Verification failed.' };
this._error = 'Saved, but the credentials did not check out — fix them and test again.';
} else if (res?.error) {
this._error = res.error;
}
announceChange();
await this._load();
} catch (e) { this._error = e.message; }
finally { this._busy = false; }
}
async _deactivate() {
if (!confirm(`Deactivate “${this._entry?.friendly_name || this._name}”?`)) return;
this._busy = true;
try {
await jf(`/api/mcp/activated/${this._act.id}`, { method: 'DELETE' });
this._act = null;
this._test = null;
announceChange();
await this._load();
} catch (e) { this._error = e.message; }
finally { this._busy = false; }
}
// ── OAuth login (§15): activate → consent in a tab → paste code → complete ────
async _startOauth() {
this._busy = true; this._error = null;
try {
// The activation may not exist yet (first sign-in) — create the pending row,
// then reuse it. A `pending` row from a previous attempt is signed in again.
let serverId = this._act?.id;
if (!serverId) {
const res = await jf('/api/mcp/activate', {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ catalog_name: this._name }),
});
if (res?.error) { this._error = res.error; return; }
serverId = res.id;
}
const start = await jf('/api/mcp/oauth/start', {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ server_id: serverId }),
});
this._oauth = { state: start.state, auth_url: start.auth_url, code: '' };
window.open(start.auth_url, '_blank', 'noopener');
announceChange();
await this._load();
} catch (e) { this._error = e.message; }
finally { this._busy = false; }
}
async _completeOauth() {
this._busy = true; this._error = null;
try {
const res = await jf('/api/mcp/oauth/complete', {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ state: this._oauth.state, code: this._oauth.code.trim() }),
});
if (res?.error) { this._error = res.error; }
else { this._oauth = null; }
announceChange();
await this._load();
} catch (e) { this._error = e.message; }
finally { this._busy = false; }
}
async _enableGlobal() {
this._busy = true; this._error = null;
try {
const res = await jf('/api/mcp/global', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
catalog_name: this._name,
api_key: this._form.api_key || null,
env: this._envPayload,
}),
});
if (res?.verify && !res.verify.ok && !res.verify.skipped) {
this._test = res.verify;
this._error = 'Verification failed — the connector stays disabled until the credentials are fixed.';
} else if (res?.error) {
this._error = res.error;
}
announceChange();
await this._load();
} catch (e) { this._error = e.message; }
finally { this._busy = false; }
}
async _disableGlobal() {
if (!confirm(`Disable “${this._glob.friendly_name || this._name}”?\n\nIt stops for everyone who can use it.`)) return;
this._busy = true;
try {
await jf(`/api/mcp/global/${this._glob.id}`, { method: 'DELETE' });
this._glob = null;
announceChange();
await this._load();
} catch (e) { this._error = e.message; }
finally { this._busy = false; }
}
_toggleAccess(userId) {
const next = new Set(this._access);
next.has(userId) ? next.delete(userId) : next.add(userId);
this._access = next;
}
async _saveAccess() {
this._busy = true;
try {
await jf(`/api/mcp/global/${this._glob.id}/access`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ user_ids: [...this._access] }),
});
announceChange();
await this._load();
} catch (e) { this._error = e.message; }
finally { this._busy = false; }
}
// ── Render ─────────────────────────────────────────────────────────────────
render() {
if (!this._open) return nothing;
if (this._error && !this._entry && !this._glob) {
return html`
<div class="um-page">
${this._renderHeader()}
<div class="alert alert-danger py-2 mx-4" style="font-size:.85rem">${this._error}</div>
</div>`;
}
if (!this._entry && !this._glob) {
return html`<div class="um-page">${this._renderHeader()}
<div class="um-empty"><i class="bi bi-hourglass-split"></i> Loading…</div></div>`;
}
return html`
<div class="um-page">
${this._renderHeader()}
<div style="padding:0 1.25rem 2rem; overflow:auto">
${this._error ? html`
<div class="alert alert-danger py-2 mb-3" style="font-size:.85rem">${this._error}</div>` : nothing}
${this._renderSummary()}
${this._renderConfig()}
${this._renderAccess()}
</div>
</div>`;
}
_renderHeader() {
const title = this._entry?.friendly_name || this._glob?.friendly_name || this._name || 'Connector';
return html`
<div class="um-header">
<div class="d-flex align-items-center gap-2" style="min-width:0">
<button class="btn btn-sm btn-outline-secondary" title="Back" @click=${() => this._back()}>
<i class="bi bi-arrow-left"></i>
</button>
<h2 class="um-title" style="min-width:0;overflow:hidden;text-overflow:ellipsis">${title}</h2>
</div>
</div>`;
}
_renderSummary() {
const e = this._entry;
const isScript = e?.source === 'local_script';
const status = this._status;
const desc = e?.description || this._glob?.description;
return html`
<div class="connector-card" style="margin-top:1rem">
<div class="connector-card-head">
${!this._noIcon
? html`<img class="connector-card-icon" style="width:44px;height:44px"
src=${connectorIconUrl(this._name, 'lg')} alt=""
@error=${() => { this._noIcon = true; }} />`
: html`<div class="connector-card-icon connector-card-icon--empty" style="width:44px;height:44px">
<i class="bi bi-plug"></i></div>`}
<div class="connector-card-title">
<div class="connector-card-name" style="font-size:1rem">
${e?.friendly_name || this._glob?.friendly_name || this._name}
</div>
<div class="connector-card-sub">${this._name}</div>
</div>
</div>
${desc ? html`<div class="connector-card-desc" style="-webkit-line-clamp:initial">${desc}</div>` : nothing}
<div class="connector-chips">
<span class="connector-chip connector-chip--scope">
<i class="bi ${this._isGlobal ? 'bi-globe' : 'bi-person'}"></i>${this._isGlobal ? 'global' : 'per-user'}
</span>
${isScript ? html`
<span class="connector-chip connector-chip--script">
<i class="bi bi-file-earmark-code"></i>runs code on this box
</span>` : nothing}
${e?.auth_kind && e.auth_kind !== 'none' ? html`
<span class="connector-chip"><i class="bi bi-key"></i>${e.auth_kind}</span>` : nothing}
${status === 'active' ? html`
<span class="connector-chip connector-chip--ok"><i class="bi bi-check-circle"></i>active</span>` : nothing}
${status === 'pending' ? html`
<span class="connector-chip connector-chip--script"><i class="bi bi-exclamation-triangle"></i>needs fixing</span>` : nothing}
${status === 'needs_login' ? html`
<span class="connector-chip connector-chip--script"><i class="bi bi-box-arrow-in-right"></i>needs sign-in</span>` : nothing}
</div>
${this._isGlobal ? html`
<div class="connector-card-note">
<i class="bi bi-info-circle"></i>Runs once for the household, on the host. Nobody reaches it until they are granted access.
</div>` : nothing}
</div>`;
}
_renderConfig() {
const e = this._entry;
// A granted global we have no catalog row for: nothing here is ours to configure.
if (!e) {
return html`
<div style="margin-top:1.5rem">
<div class="um-empty" style="padding:1rem"><i class="bi bi-check2-circle"></i>
<p>This connector is managed for you.</p>
<p style="font-size:.8rem;opacity:.7">It is enabled by an admin and granted to you — there is nothing to configure.</p>
</div>
</div>`;
}
const active = this._isGlobal ? !!this._glob : !!this._act;
const canManage = this._isGlobal ? this._isAdmin : true;
const hasVerify = !!e.verify_command;
const oauth = e.auth_kind === 'oauth';
if (this._isGlobal && !this._isAdmin) return nothing;
// OAuth is a per-user, interactive flow — a browser consent, not a form of
// typed credentials — so it gets its own panel instead of the api_key/env body.
if (oauth && !this._isGlobal) {
return html`
<div style="margin-top:1.5rem">
<div class="um-header" style="padding:0 0 .5rem">
<h3 class="um-title" style="font-size:1rem"><i class="bi bi-key me-2"></i>Sign in</h3>
</div>
${this._renderOauth()}
</div>`;
}
return html`
<div style="margin-top:1.5rem">
<div class="um-header" style="padding:0 0 .5rem">
<h3 class="um-title" style="font-size:1rem">
<i class="bi bi-sliders me-2"></i>${active ? 'Configuration' : 'Set up'}
</h3>
</div>
${active ? html`
<div class="text-muted mb-3" style="font-size:.78rem">
${this._isGlobal
? 'Already enabled. Re-submitting replaces the stored credentials.'
: 'Already active. Re-submitting replaces the stored credentials.'}
</div>` : nothing}
${e.auth_kind === 'api_key' ? html`
<div class="mb-3">
<label class="form-label">API key<span class="text-danger">*</span></label>
<input class="form-control" type="password" .value=${this._form.api_key}
@input=${(ev) => { this._form = { ...this._form, api_key: ev.target.value }; }} />
</div>` : nothing}
${this._renderEnvFields()}
${this._renderVerifyBox()}
<div class="d-flex gap-2 flex-wrap" style="margin-top:.5rem">
${hasVerify && canManage ? html`
<button class="btn btn-sm btn-outline-secondary" ?disabled=${this._test === 'running' || this._busy}
@click=${() => this._testCreds()}>
<i class="bi bi-${this._test === 'running' ? 'arrow-repeat' : 'check2-gear'} me-1"></i>
${this._test === 'running' ? 'Testing…' : 'Test credentials'}
</button>` : nothing}
${this._isGlobal
? html`
<button class="btn btn-sm btn-primary" ?disabled=${this._busy} @click=${() => this._enableGlobal()}>
<i class="bi bi-globe me-1"></i>${this._glob ? 'Save & restart' : 'Enable globally'}
</button>
${this._glob ? html`
<button class="btn btn-sm btn-outline-danger" ?disabled=${this._busy} @click=${() => this._disableGlobal()}>
<i class="bi bi-trash me-1"></i>Disable
</button>` : nothing}`
: html`
<button class="btn btn-sm btn-primary" ?disabled=${this._busy} @click=${() => this._activate()}>
<i class="bi bi-plug me-1"></i>${this._act ? 'Save & restart' : 'Activate'}
</button>
${this._act ? html`
<button class="btn btn-sm btn-outline-danger" ?disabled=${this._busy} @click=${() => this._deactivate()}>
<i class="bi bi-trash me-1"></i>Deactivate
</button>` : nothing}`}
</div>
</div>`;
}
_renderOauth() {
const provider = this._entry?.oauth_provider || 'provider';
const label = provider.charAt(0).toUpperCase() + provider.slice(1);
const active = this._act && this._act.auth_state === 'ready';
const pending = this._act && this._act.auth_state === 'pending';
const scopes = parseJson(this._entry?.oauth_scopes_json, []);
return html`
<div class="text-muted mb-3" style="font-size:.78rem">
Signs in with ${label}. You approve access in a browser tab, then paste back the
code the page shows you — nothing is stored on this box until you do.
</div>
${scopes.length ? html`
<div class="mb-3" style="font-size:.72rem">
<div class="text-muted mb-1">It will request access to:</div>
<ul class="mb-0 ps-3">${scopes.map(s => html`<li><code style="font-size:.68rem">${s}</code></li>`)}</ul>
</div>` : nothing}
${active ? html`
<div class="alert alert-success py-2 mb-3" style="font-size:.82rem">
<i class="bi bi-check-circle-fill me-1"></i>Signed in and active.
</div>` : nothing}
${!this._oauth ? html`
<div class="d-flex gap-2 flex-wrap">
<button class="btn btn-sm btn-primary" ?disabled=${this._busy} @click=${() => this._startOauth()}>
<i class="bi bi-box-arrow-in-right me-1"></i>${active ? 'Sign in again' : (pending ? 'Finish sign-in' : `Sign in with ${label}`)}
</button>
${this._act ? html`
<button class="btn btn-sm btn-outline-danger" ?disabled=${this._busy} @click=${() => this._deactivate()}>
<i class="bi bi-trash me-1"></i>Deactivate
</button>` : nothing}
</div>`
: html`
<div class="connector-card" style="margin-top:.25rem">
<div class="mb-2" style="font-size:.8rem">
<i class="bi bi-1-circle me-1"></i>A tab opened for ${label}. Approve access there.
<div class="mt-1"><a href=${this._oauth.auth_url} target="_blank" rel="noopener">Re-open the sign-in page</a></div>
</div>
<div class="mb-2" style="font-size:.8rem">
<i class="bi bi-2-circle me-1"></i>Paste the code the page gave you:
</div>
<input class="form-control font-monospace mb-2" placeholder="4/0A…"
.value=${this._oauth.code}
@input=${(ev) => { this._oauth = { ...this._oauth, code: ev.target.value }; }} />
<div class="d-flex gap-2">
<button class="btn btn-sm btn-primary" ?disabled=${this._busy || !this._oauth.code.trim()}
@click=${() => this._completeOauth()}>
<i class="bi bi-check-lg me-1"></i>Complete sign-in
</button>
<button class="btn btn-sm btn-outline-secondary" ?disabled=${this._busy}
@click=${() => { this._oauth = null; }}>Cancel</button>
</div>
</div>`}
`;
}
_renderEnvFields() {
if (!this._schema.length) return nothing;
return this._schema.map(f => html`
<div class="mb-3">
<label class="form-label">
${f.label || f.name}
${f.required ? html`<span class="text-danger">*</span>` : nothing}
${f.secret ? html` <span class="badge bg-warning text-dark" style="font-size:.6rem">secret</span>` : nothing}
</label>
<input
class="form-control ${f.secret ? '' : 'font-monospace'}"
type=${f.secret ? 'password' : 'text'}
placeholder=${f.example || ''}
.value=${this._form.env[f.name] ?? ''}
@input=${(ev) => this._patchEnv(f.name, ev.target.value)} />
${f.description ? html`<div class="form-text" style="font-size:.72rem">${f.description}</div>` : nothing}
</div>`);
}
_renderVerifyBox() {
const t = this._test;
if (t === null) return nothing;
if (t === 'running') {
return html`<div class="alert alert-secondary py-2 mb-3" style="font-size:.82rem">
<i class="bi bi-arrow-repeat me-1"></i>Testing credentials…</div>`;
}
if (t.skipped) {
return html`<div class="alert alert-secondary py-2 mb-3" style="font-size:.82rem">
<i class="bi bi-info-circle me-1"></i>${t.message || 'No verification step for this connector.'}</div>`;
}
return html`
<div class="alert alert-${t.ok ? 'success' : 'danger'} py-2 mb-3" style="font-size:.82rem">
<i class="bi ${t.ok ? 'bi-check-circle-fill' : 'bi-x-circle-fill'} me-1"></i>
<strong>${t.ok ? 'OK' : 'Failed'}</strong> — ${t.message}
${t.details ? html`
<pre class="mb-0 mt-1 p-2 rounded bg-dark text-light"
style="font-size:.7rem;white-space:pre-wrap">${JSON.stringify(t.details, null, 2)}</pre>` : nothing}
</div>`;
}
/// Who may use this global connector. Only meaningful once it is enabled — there
/// is no instance to grant access to before that.
_renderAccess() {
if (!this._isGlobal || !this._isAdmin || !this._glob) return nothing;
const users = this._users ?? [];
return html`
<div style="margin-top:1.75rem">
<div class="um-header" style="padding:0 0 .5rem">
<h3 class="um-title" style="font-size:1rem"><i class="bi bi-people me-2"></i>Who can use it</h3>
</div>
<div class="text-muted mb-2" style="font-size:.78rem">
Ticking a box grants this connector's tools to that person's agent. Saving replaces the whole list.
</div>
${users.length === 0
? html`<div class="um-empty" style="padding:1rem"><i class="bi bi-people"></i><p>No users.</p></div>`
: html`
<div class="connector-card">
${users.map(u => html`
<div class="form-check">
<input class="form-check-input" type="checkbox" id=${'acc-' + u.id}
.checked=${this._access?.has(u.id) ?? false}
@change=${() => this._toggleAccess(u.id)} />
<label class="form-check-label" for=${'acc-' + u.id}>
${u.display_name || u.username}
<code class="text-muted" style="font-size:.7rem">${u.id}</code>
</label>
</div>`)}
</div>`}
<button class="btn btn-sm btn-primary mt-2" ?disabled=${this._busy || !this._access}
@click=${() => this._saveAccess()}>
<i class="bi bi-check-lg me-1"></i>Save access
</button>
</div>`;
}
}
+300 -320
View File
@@ -1,28 +1,26 @@
import { html, nothing } from 'lit';
import { LightElement } from '../lib/base.js';
import { connectorIconUrl, statusOf, STATUS_LABEL } from './shared/connector-common.js';
// Connectors (MCP) — blueprint §7/§14/§15.
//
// One question: **what is running, and what can I add?** This is the runtime view —
// literally `UserMcpView` (global per-user) plus the actions that create those
// instances. What this box *offers* is a different question, answered by the
// Connector Catalog page.
// **One row per connector**, not one per runtime instance. A catalog entry is a
// template with two runtimes (§7), and a person thinks in terms of "do I have
// Gmail?" — not "how many `mcp_user_servers` rows named gmail-ish do I own?". So the
// old three-section split (Mine / Global / Available) is gone: the same connector
// used to appear twice, once as a template and once as its instance, and the reader
// had to join the two by eye. Here each connector appears exactly once, and its
// state is a chip on the card.
//
// The same page serves everyone; the admin just has more verbs. A catalog entry is a
// template with two runtimes (§7), so "Available" is one list with the verb that fits
// each row: a `per_user` entry says Activate (anyone), a `global` entry says Enable
// globally (admin only). Enabling a global is the admin's counterpart to activating a
// per-user one — which is why they live side by side instead of in an admin dungeon.
// The card is a link, not a form. Everything that needs typing lives on the
// connector's own page (`#connector?name=X`) — an activation form has as many
// fields as the connector declares (EMAIL has a dozen), which a fixed-size dialog
// could never hold.
//
// Reuses the shared `um-*` / bootstrap styling (no page-specific CSS).
// Reuses the marketplace's card styling (`web/css/connectors.css`).
const ADMIN_ID = 'admin';
function parseJson(s, fallback) {
if (!s) return fallback;
try { return JSON.parse(s); } catch { return fallback; }
}
async function jf(url, opts) {
const res = await fetch(url, opts);
if (!res.ok) throw new Error(await res.text() || `HTTP ${res.status}`);
@@ -38,15 +36,20 @@ export class ConnectorsPage extends LightElement {
_me: { state: true }, // { role_id }
_available: { state: true }, // { catalog: [...], globals: [...] }
_activated: { state: true }, // my per-user server rows
_users: { state: true }, // admin: user summaries (for the access modal)
_error: { state: true },
_modal: { state: true },
_q: { state: true },
_noIcon: { state: true }, // names whose icon failed to load
_providers: { state: true }, // admin: OAuth provider list (modal)
_pForm: { state: true }, // admin: provider being edited, or null
_pError: { state: true },
};
}
constructor() {
super();
this._open = false;
this._q = '';
this._noIcon = new Set();
this._reset();
}
@@ -54,9 +57,10 @@ export class ConnectorsPage extends LightElement {
this._me = null;
this._available = null;
this._activated = null;
this._users = null;
this._error = null;
this._modal = null;
this._providers = null;
this._pForm = null;
this._pError = null;
}
connectedCallback() {
@@ -66,6 +70,9 @@ export class ConnectorsPage extends LightElement {
this.style.display = this._open ? 'flex' : 'none';
if (this._open) this._load();
});
// Coming back from a connector's page must show its new state, not the state
// captured before the user activated it.
window.addEventListener('connectors-changed', () => { if (this._open) this._load(); });
}
get _isAdmin() { return this._me?.role_id === ADMIN_ID; }
@@ -80,130 +87,147 @@ export class ConnectorsPage extends LightElement {
]);
this._available = available;
this._activated = activated;
// Only the access modal needs the user list, and only an admin opens it.
if (this._isAdmin) this._users = await jf('/api/users');
} catch (e) {
this._error = e.message;
}
}
_patch(field, value) {
this._modal = { ...this._modal, form: { ...this._modal.form, [field]: value } };
_go(page, hash) {
history.pushState({ page }, '', hash);
window.dispatchEvent(new CustomEvent('llm-page-change', { detail: { page } }));
}
_closeModal() { this._modal = null; this._error = null; }
_goCatalog() {
history.pushState({ page: 'catalog' }, '', '#catalog');
window.dispatchEvent(new CustomEvent('llm-page-change', { detail: { page: 'catalog' } }));
_openConnector(name) {
this._go('connector', `#connector?name=${encodeURIComponent(name)}`);
}
// ── Activate a per-user connector ──────────────────────────────────────────
// ── admin: OAuth sign-in providers (§15) ─────────────────────────────────────
_openActivate(entry) {
const schema = parseJson(entry.config_schema_json, []) || [];
this._modal = {
kind: 'activate',
entry,
form: { name: entry.name, api_key: '', env: Object.fromEntries(schema.map(k => [k, ''])) },
async _openProviders() {
this._pError = null;
this._pForm = null;
try {
this._providers = await jf('/api/mcp/providers');
} catch (e) { this._pError = e.message; this._providers = []; }
}
_closeProviders() {
this._providers = null;
this._pForm = null;
this._pError = null;
}
_blankProvider() {
return { name: '', display_name: '', auth_url: '', token_url: '',
client_id: '', client_secret: '', redirect_uri: '', extra_params: '' };
}
/// A Google preset — fills everything but the client_id/secret the admin pastes
/// from their Google Cloud console. `prompt=consent` + `access_type=offline` are
/// what make Google return a refresh token (§15).
_presetGoogle() {
this._pError = null;
this._pForm = {
name: 'google',
display_name: 'Google',
auth_url: 'https://accounts.google.com/o/oauth2/v2/auth',
token_url: 'https://oauth2.googleapis.com/token',
client_id: '',
client_secret: '',
redirect_uri: 'https://connectors.skaldagent.net/oauth/show.html',
extra_params: '{"access_type":"offline","prompt":"consent"}',
_isNew: true,
};
}
async _activate() {
const { entry, form } = this._modal;
if (!form.name.trim()) { this._error = 'A name is required.'; return; }
const env = {};
for (const [k, v] of Object.entries(form.env || {})) if (v !== '') env[k] = v;
_editProvider(p) {
// The secret never came back from the server; an empty box means "keep it".
this._pForm = { ...p, client_secret: '', extra_params: p.extra_params || '', _isNew: false };
this._pError = null;
}
_patchProvider(key, value) {
this._pForm = { ...this._pForm, [key]: value };
}
async _saveProvider() {
const f = this._pForm;
if (!f.name.trim() || !f.client_id.trim()) {
this._pError = 'Name and client id are required.';
return;
}
if (f._isNew && !f.client_secret.trim()) {
this._pError = 'A client secret is required for a new provider.';
return;
}
this._pError = null;
try {
await jf('/api/mcp/activate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
catalog_name: entry.name,
name: form.name.trim(),
api_key: form.api_key || null,
env: Object.keys(env).length ? env : null,
}),
const { _isNew, has_client_secret, ...body } = f;
await jf('/api/mcp/providers', {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
this._closeModal();
await this._load();
} catch (e) { this._error = e.message; }
this._pForm = null;
this._providers = await jf('/api/mcp/providers');
} catch (e) { this._pError = e.message; }
}
async _deactivate(row) {
if (!confirm(`Deactivate connector "${row.name}"?`)) return;
async _deleteProvider(name) {
if (!confirm(`Delete the “${name}” sign-in provider?\n\nConnectors that use it will no longer be able to sign in.`)) return;
try {
await jf(`/api/mcp/activated/${row.id}`, { method: 'DELETE' });
await this._load();
} catch (e) { this._error = e.message; }
await jf(`/api/mcp/providers/${encodeURIComponent(name)}`, { method: 'DELETE' });
this._providers = await jf('/api/mcp/providers');
} catch (e) { this._pError = e.message; }
}
// ── Enable a global connector (admin) ──────────────────────────────────────
/// The merged view: every connector the caller can see, exactly once, carrying
/// whichever runtime rows exist for it.
get _rows() {
const catalog = this._available?.catalog ?? [];
const globals = this._available?.globals ?? [];
const activated = this._activated ?? [];
// The entry comes from the row the admin clicked, so there is no catalog picker:
// the old dropdown existed only because this action lived on a page that did not
// show the catalog.
_openEnableGlobal(entry) {
this._modal = {
kind: 'global',
entry,
form: { name: entry.name, api_key: '' },
};
}
const rows = catalog.map(e => ({
...e,
_act: activated.find(r => r.catalog_name === e.name) ?? null,
_glob: globals.find(g => (g.catalog_name ?? g.name) === e.name) ?? null,
}));
async _enableGlobal() {
const { entry, form } = this._modal;
try {
await jf('/api/mcp/global', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
catalog_name: entry.name,
name: form.name.trim() || null,
api_key: form.api_key || null,
}),
// A granted global whose catalog row the caller cannot see. `/api/mcp/available`
// only returns `global` catalog entries to a catalog manager, so without this the
// connector an ordinary user actually uses every day would be missing from their
// own list — visible to the admin, invisible to its user.
for (const g of globals) {
const key = g.catalog_name ?? g.name;
if (rows.some(r => r.name === key)) continue;
rows.push({
name: key,
friendly_name: g.friendly_name,
description: g.description,
scope: 'global',
source: 'remote',
auth_kind: 'none',
_act: null,
_glob: g,
});
this._closeModal();
await this._load();
} catch (e) { this._error = e.message; }
}
const q = this._q.trim().toLowerCase();
return rows
.filter(r => !q
|| r.name.toLowerCase().includes(q)
|| (r.friendly_name ?? '').toLowerCase().includes(q)
|| (r.description ?? '').toLowerCase().includes(q))
.sort((a, b) => (a.friendly_name || a.name).localeCompare(b.friendly_name || b.name));
}
async _deleteGlobal(row) {
if (!confirm(`Disable global connector "${row.name}"?\n\nIt stops for everyone who can use it.`)) return;
try {
await jf(`/api/mcp/global/${row.id}`, { method: 'DELETE' });
await this._load();
} catch (e) { this._error = e.message; }
}
async _openAccess(server) {
this._modal = { kind: 'access', server, selected: new Set() };
try {
const current = await jf(`/api/mcp/global/${server.id}/access`);
// Ignore if the admin already navigated away / opened another modal.
if (this._modal?.kind === 'access' && this._modal.server.id === server.id) {
this._modal = { ...this._modal, selected: new Set(current || []) };
}
} catch (e) { this._error = e.message; }
}
_toggleAccess(userId) {
const sel = new Set(this._modal.selected);
sel.has(userId) ? sel.delete(userId) : sel.add(userId);
this._modal = { ...this._modal, selected: sel };
}
async _saveAccess() {
const { server, selected } = this._modal;
try {
await jf(`/api/mcp/global/${server.id}/access`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ user_ids: [...selected] }),
});
this._closeModal();
await this._load();
} catch (e) { this._error = e.message; }
_iconFailed(name) {
// Re-render with the placeholder. A synthetic row (a granted global whose
// catalog entry the caller cannot read) has no icon path to check up front, so
// the 404 is the check.
const next = new Set(this._noIcon);
next.add(name);
this._noIcon = next;
}
// ── Render ─────────────────────────────────────────────────────────────────
@@ -211,6 +235,7 @@ export class ConnectorsPage extends LightElement {
render() {
if (!this._open) return nothing;
const loading = this._available === null && !this._error;
const rows = loading ? [] : this._rows;
return html`
<div class="um-page">
@@ -218,232 +243,187 @@ export class ConnectorsPage extends LightElement {
<h2 class="um-title"><i class="bi bi-plug me-2"></i>Connectors</h2>
<div class="um-header-right">
${this._isAdmin ? html`
<button class="btn btn-sm btn-outline-secondary" @click=${() => this._goCatalog()}>
<button class="btn btn-sm btn-outline-secondary" @click=${() => this._openProviders()}>
<i class="bi bi-key me-1"></i>Sign-in providers
</button>
<button class="btn btn-sm btn-outline-secondary" @click=${() => this._go('catalog', '#catalog')}>
<i class="bi bi-journal-text me-1"></i>Catalog
</button>
<button class="btn btn-sm btn-primary" @click=${() => this._go('marketplace', '#marketplace')}>
<i class="bi bi-bag me-1"></i>Marketplace
</button>` : nothing}
</div>
</div>
${this._error && !this._modal ? html`
${this._error ? html`
<div class="alert alert-danger py-2 mx-4" style="font-size:.85rem">${this._error}</div>` : nothing}
${loading ? html`<div class="um-empty"><i class="bi bi-hourglass-split"></i> Loading…</div>` : html`
<div style="padding:0 1.25rem 1.5rem; overflow:auto">
${this._renderMine()}
${this._renderGlobals()}
${this._renderAvailable()}
</div>`}
</div>
${this._renderModal()}`;
}
_section(title, icon, right, body) {
return html`
<div style="margin-top:1.5rem">
<div class="um-header" style="padding:0 0 .5rem">
<h3 class="um-title" style="font-size:1rem"><i class="bi ${icon} me-2"></i>${title}</h3>
<div class="um-header-right">${right ?? nothing}</div>
</div>
${body}
${loading
? html`<div class="um-empty"><i class="bi bi-hourglass-split"></i> Loading…</div>`
: html`
<div style="padding:0 1.25rem 1.5rem; overflow:auto">
<div class="connector-filters">
<div class="connector-search">
<i class="bi bi-search"></i>
<input class="form-control form-control-sm" placeholder="Search connectors…"
.value=${this._q} @input=${(e) => { this._q = e.target.value; }} />
</div>
</div>
${rows.length === 0 ? this._renderEmpty() : html`
<div class="connector-grid">${rows.map(r => this._renderCard(r))}</div>`}
</div>`}
${this._providers !== null ? this._renderProvidersModal() : nothing}
</div>`;
}
_renderMine() {
const rows = this._activated ?? [];
return this._section('My connectors', 'bi-check2-circle', nothing,
rows.length === 0
? html`<div class="um-empty" style="padding:1rem"><i class="bi bi-plug"></i>
<p>No per-user connectors activated.</p></div>`
: html`
<table class="um-table">
<thead><tr><th>Name</th><th>Type</th><th>From catalog</th><th></th></tr></thead>
<tbody>
${rows.map(r => html`
<tr>
<td><strong>${r.name}</strong></td>
<td><span class="badge ${r.source === 'local_script' ? 'bg-warning text-dark' : 'bg-secondary'}"
style="font-size:.65rem">${r.source === 'local_script' ? 'local script' : 'remote'}</span></td>
<td>${r.catalog_name ? html`<code>${r.catalog_name}</code>` : html`<span class="text-muted">—</span>`}</td>
<td><div class="um-actions">
<button class="um-btn-icon" title="Deactivate" @click=${() => this._deactivate(r)}>
<i class="bi bi-trash"></i></button>
</div></td>
</tr>`)}
</tbody>
</table>`);
}
_renderGlobals() {
const rows = this._available?.globals ?? [];
if (rows.length === 0 && !this._isAdmin) return nothing;
return this._section('Global connectors', 'bi-globe', nothing,
rows.length === 0
? html`<div class="um-empty" style="padding:1rem"><i class="bi bi-globe"></i>
<p>None enabled. Enable one from Available below.</p></div>`
: html`
${this._isAdmin ? html`
<div class="text-muted mb-2" style="font-size:.75rem">
Shared by the household. You see every one so you can manage it —
<span class="badge bg-success" style="font-size:.6rem">yours</span> marks the ones granted to you.
</div>` : nothing}
<table class="um-table">
<thead><tr><th>Name</th><th>Transport</th><th>Status</th><th></th></tr></thead>
<tbody>
${rows.map(g => html`
<tr>
<td>
<strong>${g.friendly_name || g.name}</strong>
${this._isAdmin && g.can_use ? html`
<span class="badge bg-success ms-1" style="font-size:.6rem">yours</span>` : nothing}
${g.description ? html`
<div class="text-muted" style="font-size:.75rem;max-width:44ch;overflow:hidden;
text-overflow:ellipsis;white-space:nowrap" title=${g.description}>${g.description}</div>` : nothing}
</td>
<td><span class="text-muted" style="font-size:.78rem">${g.transport}</span></td>
<td>${g.enabled
? html`<span class="badge bg-success" style="font-size:.65rem">on</span>`
: html`<span class="badge bg-secondary" style="font-size:.65rem">off</span>`}</td>
<td><div class="um-actions">
${this._isAdmin ? html`
<button class="um-btn-icon" title="Manage access" @click=${() => this._openAccess(g)}>
<i class="bi bi-people"></i></button>
<button class="um-btn-icon" title="Disable" @click=${() => this._deleteGlobal(g)}>
<i class="bi bi-trash"></i></button>
` : nothing}
</div></td>
</tr>`)}
</tbody>
</table>`);
}
_renderAvailable() {
const entries = this._available?.catalog ?? [];
const enabledGlobals = new Set((this._available?.globals ?? []).map(g => g.catalog_name ?? g.name));
const activatedNames = new Set((this._activated ?? []).map(r => r.catalog_name));
const right = this._isAdmin ? html`
<button class="btn btn-sm btn-outline-secondary" @click=${() => this._goCatalog()}>
<i class="bi bi-plus-lg me-1"></i>Add to catalog
</button>` : nothing;
if (entries.length === 0) {
return this._section('Available', 'bi-plus-square', right, html`
<div class="um-empty" style="padding:1rem"><i class="bi bi-journal"></i>
<p>${this._isAdmin ? 'The catalog is empty.' : 'Nothing available to you yet.'}</p>
${this._isAdmin ? html`
<p style="font-size:.8rem;opacity:.7">Add connectors to the catalog first.</p>` : nothing}
</div>`);
}
return this._section('Available', 'bi-plus-square', right, html`
<table class="um-table">
<thead><tr><th>Connector</th><th>Scope</th><th>Auth</th><th></th></tr></thead>
<tbody>
${entries.map(e => {
const isGlobal = e.scope === 'global';
const already = isGlobal ? enabledGlobals.has(e.name) : activatedNames.has(e.name);
return html`
<tr>
<td><strong>${e.friendly_name || e.name}</strong>
${e.description ? html`
<div class="text-muted" style="font-size:.75rem;max-width:44ch;overflow:hidden;
text-overflow:ellipsis;white-space:nowrap" title=${e.description}>${e.description}</div>` : nothing}</td>
<td><span class="badge ${isGlobal ? 'bg-info' : 'bg-secondary'}" style="font-size:.65rem">
${isGlobal ? 'global' : 'per-user'}</span></td>
<td><span class="text-muted" style="font-size:.78rem">${e.auth_kind}</span></td>
<td><div class="um-actions">
${already
? html`<span class="badge bg-success">${isGlobal ? 'enabled' : 'active'}</span>`
: isGlobal
? html`<button class="btn btn-sm btn-primary" @click=${() => this._openEnableGlobal(e)}>
<i class="bi bi-globe me-1"></i>Enable globally</button>`
: html`<button class="btn btn-sm btn-primary" @click=${() => this._openActivate(e)}>
<i class="bi bi-plug me-1"></i>Activate</button>`}
</div></td>
</tr>`;
})}
</tbody>
</table>`);
}
// ── Modals ─────────────────────────────────────────────────────────────────
_modalShell(title, icon, body, onSave, saveLabel) {
_renderProvidersModal() {
return html`
<div class="um-modal-overlay" @click=${(e) => { if (e.target.classList.contains('um-modal-overlay')) this._closeModal(); }}>
<div class="um-modal">
<div class="um-modal-header">
<i class="bi ${icon}"></i><span>${title}</span>
<button class="um-btn-icon ms-auto" @click=${() => this._closeModal()}><i class="bi bi-x-lg"></i></button>
<div style="position:fixed;inset:0;background:rgba(0,0,0,.5);z-index:1050;
display:flex;align-items:flex-start;justify-content:center;overflow:auto;padding:2rem 1rem"
@click=${(e) => { if (e.target === e.currentTarget) this._closeProviders(); }}>
<div class="connector-card" style="width:100%;max-width:560px;cursor:default">
<div class="d-flex align-items-center justify-content-between mb-2">
<h3 class="um-title" style="font-size:1rem;margin:0"><i class="bi bi-key me-2"></i>Sign-in providers</h3>
<button class="btn btn-sm btn-outline-secondary" @click=${() => this._closeProviders()}>
<i class="bi bi-x-lg"></i>
</button>
</div>
<div class="um-modal-body">
${this._error ? html`<div class="alert alert-danger py-2 mb-3" style="font-size:.85rem">${this._error}</div>` : nothing}
${body}
</div>
<div class="um-modal-footer">
<button class="btn btn-sm btn-outline-secondary" @click=${() => this._closeModal()}>Cancel</button>
<button class="btn btn-sm btn-primary" @click=${onSave}><i class="bi bi-check-lg me-1"></i>${saveLabel}</button>
<div class="text-muted mb-3" style="font-size:.78rem">
OAuth apps that per-user connectors sign in through. One app (e.g. Google) covers all of
its services. The client secret is stored on this box and never shown again.
</div>
${this._pError ? html`
<div class="alert alert-danger py-2 mb-2" style="font-size:.82rem">${this._pError}</div>` : nothing}
${this._pForm ? this._renderProviderForm() : this._renderProviderList()}
</div>
</div>`;
}
_field(label, value, oninput, opts = {}) {
return html`<div class="mb-3">
<label class="form-label">${label}${opts.hint ? html` <span class="text-muted">(${opts.hint})</span>` : nothing}</label>
<input class="form-control ${opts.mono ? 'font-monospace' : ''}" type=${opts.type || 'text'}
placeholder=${opts.placeholder || ''} .value=${value} @input=${oninput} />
</div>`;
_renderProviderList() {
const list = this._providers ?? [];
return html`
${list.length === 0 ? html`
<div class="um-empty" style="padding:1rem"><i class="bi bi-key"></i>
<p>No sign-in providers yet.</p></div>` : html`
<div class="d-flex flex-column gap-2 mb-3">
${list.map(p => html`
<div class="d-flex align-items-center justify-content-between p-2 rounded"
style="border:1px solid var(--bs-border-color,#333)">
<div style="min-width:0">
<div style="font-weight:500">${p.display_name || p.name}
<code class="text-muted" style="font-size:.7rem">${p.name}</code></div>
<div class="text-muted" style="font-size:.72rem;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">
${p.has_client_secret
? html`<i class="bi bi-check-circle text-success"></i> secret set`
: html`<i class="bi bi-exclamation-triangle text-warning"></i> no secret`}
· ${p.client_id || '(no client id)'}
</div>
</div>
<div class="d-flex gap-1">
<button class="btn btn-sm btn-outline-secondary" @click=${() => this._editProvider(p)}>
<i class="bi bi-pencil"></i></button>
<button class="btn btn-sm btn-outline-danger" @click=${() => this._deleteProvider(p.name)}>
<i class="bi bi-trash"></i></button>
</div>
</div>`)}
</div>`}
<div class="d-flex gap-2">
<button class="btn btn-sm btn-primary" @click=${() => this._presetGoogle()}>
<i class="bi bi-google me-1"></i>Add Google
</button>
<button class="btn btn-sm btn-outline-secondary" @click=${() => { this._pForm = { ...this._blankProvider(), _isNew: true }; }}>
<i class="bi bi-plus-lg me-1"></i>Add other
</button>
</div>`;
}
_renderModal() {
if (!this._modal) return nothing;
const m = this._modal;
_renderProviderForm() {
const f = this._pForm;
const field = (key, label, opts = {}) => html`
<div class="mb-2">
<label class="form-label" style="font-size:.8rem">${label}${opts.req ? html`<span class="text-danger">*</span>` : nothing}</label>
<input class="form-control form-control-sm ${opts.mono ? 'font-monospace' : ''}"
type=${opts.secret ? 'password' : 'text'}
placeholder=${opts.ph || ''}
.value=${f[key] ?? ''}
@input=${(e) => this._patchProvider(key, e.target.value)} />
${opts.help ? html`<div class="form-text" style="font-size:.7rem">${opts.help}</div>` : nothing}
</div>`;
return html`
${field('name', 'Provider id', { req: true, mono: true, ph: 'google',
help: 'The slug a connector references (must match the manifest\'s auth.provider).' })}
${field('display_name', 'Display name', { ph: 'Google' })}
${field('client_id', 'Client id', { req: true, mono: true })}
${field('client_secret', 'Client secret', { secret: true, mono: true,
help: f._isNew ? 'Required.' : 'Leave blank to keep the stored secret.' })}
${field('auth_url', 'Authorization URL', { mono: true, ph: 'https://accounts.google.com/o/oauth2/v2/auth' })}
${field('token_url', 'Token URL', { mono: true, ph: 'https://oauth2.googleapis.com/token' })}
${field('redirect_uri', 'Redirect URI', { mono: true,
help: 'The copy-paste page. Must be registered as an authorized redirect in the provider\'s console.' })}
${field('extra_params', 'Extra params (JSON)', { mono: true, ph: '{"access_type":"offline","prompt":"consent"}',
help: 'Merged into the consent URL. Google needs these two to return a refresh token.' })}
<div class="d-flex gap-2 mt-3">
<button class="btn btn-sm btn-primary" @click=${() => this._saveProvider()}>
<i class="bi bi-check-lg me-1"></i>Save
</button>
<button class="btn btn-sm btn-outline-secondary" @click=${() => { this._pForm = null; this._pError = null; }}>
Cancel
</button>
</div>`;
}
if (m.kind === 'activate') {
const f = m.form;
const schema = parseJson(m.entry.config_schema_json, []) || [];
return this._modalShell(`Activate ${m.entry.friendly_name || m.entry.name}`, 'bi-plug', html`
${this._field('Name', f.name, e => this._patch('name', e.target.value), { hint: 'unique for you', mono: true })}
${m.entry.auth_kind === 'api_key' ? this._field('API key', f.api_key, e => this._patch('api_key', e.target.value), { type: 'password', mono: true }) : nothing}
${m.entry.auth_kind === 'oauth' ? html`
<div class="alert alert-warning py-2" style="font-size:.78rem">
<i class="bi bi-exclamation-triangle me-1"></i>This connector needs an interactive login,
which is not wired up yet — it will activate but cannot authenticate.
</div>` : nothing}
${schema.map(k => html`<div class="mb-3">
<label class="form-label font-monospace" style="font-size:.8rem">${k}</label>
<input class="form-control font-monospace" .value=${f.env[k] ?? ''}
@input=${e => this._patch('env', { ...f.env, [k]: e.target.value })} />
</div>`)}
`, () => this._activate(), 'Activate');
_renderEmpty() {
if (this._q.trim()) {
return html`<div class="um-empty" style="padding:1rem"><i class="bi bi-search"></i>
<p>No connector matches “${this._q}”.</p></div>`;
}
return html`
<div class="um-empty" style="padding:1rem"><i class="bi bi-plug"></i>
<p>${this._isAdmin ? 'No connectors installed yet.' : 'Nothing available to you yet.'}</p>
${this._isAdmin
? html`<p style="font-size:.8rem;opacity:.7">Install one from the Marketplace to get started.</p>`
: html`<p style="font-size:.8rem;opacity:.7">Ask an admin to make one available.</p>`}
</div>`;
}
if (m.kind === 'global') {
const f = m.form;
return this._modalShell(`Enable ${m.entry.friendly_name || m.entry.name} globally`, 'bi-globe', html`
<div class="text-muted mb-3" style="font-size:.78rem">
Runs once for the household on the host. Nobody reaches it until you grant access.
_renderCard(r) {
const status = statusOf(r);
const isGlobal = r.scope === 'global';
const isScript = r.source === 'local_script';
const showIcon = !this._noIcon.has(r.name);
return html`
<div class="connector-card" role="button" tabindex="0"
style="cursor:pointer"
@click=${() => this._openConnector(r.name)}
@keydown=${(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); this._openConnector(r.name); } }}>
<div class="connector-card-head">
${showIcon
? html`<img class="connector-card-icon" src=${connectorIconUrl(r.name, 'sm')} alt=""
@error=${() => this._iconFailed(r.name)} />`
: html`<div class="connector-card-icon connector-card-icon--empty"><i class="bi bi-plug"></i></div>`}
<div class="connector-card-title">
<div class="connector-card-name">${r.friendly_name || r.name}</div>
<div class="connector-card-sub">${r.name}</div>
</div>
<span class=${`connector-chip${STATUS_LABEL[status].tone ? ` connector-chip--${STATUS_LABEL[status].tone}` : ''}`}>
${STATUS_LABEL[status].text}
</span>
</div>
${this._field('Name', f.name, e => this._patch('name', e.target.value), { hint: 'runtime name', mono: true })}
${m.entry.auth_kind === 'api_key'
? this._field('API key', f.api_key, e => this._patch('api_key', e.target.value), { type: 'password', mono: true })
: nothing}
`, () => this._enableGlobal(), 'Enable');
}
if (m.kind === 'access') {
const users = this._users ?? [];
return this._modalShell(`Access — ${m.server.name}`, 'bi-people', html`
<div class="text-muted mb-2" style="font-size:.8rem">Select who may use this global connector. This replaces the current list.</div>
${users.map(u => html`<div class="form-check">
<input class="form-check-input" type="checkbox" id=${'acc-' + u.id}
.checked=${m.selected.has(u.id)} @change=${() => this._toggleAccess(u.id)} />
<label class="form-check-label" for=${'acc-' + u.id}>${u.display_name || u.username} <code class="text-muted">${u.id}</code></label>
</div>`)}
`, () => this._saveAccess(), 'Save access');
}
${r.description ? html`<div class="connector-card-desc">${r.description}</div>` : nothing}
return nothing;
<div class="connector-chips">
<span class="connector-chip connector-chip--scope">
<i class="bi ${isGlobal ? 'bi-globe' : 'bi-person'}"></i>${isGlobal ? 'global' : 'per-user'}
</span>
${isScript ? html`
<span class="connector-chip connector-chip--script">
<i class="bi bi-file-earmark-code"></i>local script
</span>` : nothing}
${r.auth_kind && r.auth_kind !== 'none' ? html`
<span class="connector-chip"><i class="bi bi-key"></i>${r.auth_kind}</span>` : nothing}
</div>
</div>`;
}
}
+1 -1
View File
@@ -91,7 +91,7 @@ export class MarketplacePage extends LightElement {
async _install(card) {
const warn = card.source === 'local_script'
? `\n\nThis puts code on this box:\n${card.file_count} file(s), each verified against its SHA-256\n • installed into ./scripts/${card.id}/`
? `\n\nThis puts code on this box:\n${card.file_count} file(s), each verified against its SHA-256\n • installed into ./connectors/${card.id}/`
: '';
if (!confirm(`Install "${card.name}" into the catalog?${warn}\n\nInstalling does not activate it.`)) return;
this._installing = card.id;
+88
View File
@@ -0,0 +1,88 @@
// Shared vocabulary for the Connectors list and a connector's own page.
//
// Both surfaces have to answer "what state is this connector in?" and both draw the
// same env/secret form. Deriving that twice is how the two drift, so the derivation
// lives here and each page only decides layout.
/// The icon of an **installed** connector, off the box's own `connectors/` folder —
/// not the marketplace proxy, which is admin-only and dies with the feed.
export function connectorIconUrl(name, size = 'sm') {
return `/api/mcp/catalog/${encodeURIComponent(name)}/icon?size=${size}`;
}
/// How each status reads on a chip. `tone` maps to the `connector-chip--*` accents
/// in `web/css/connectors.css`.
export const STATUS_LABEL = {
active: { text: 'active', tone: 'ok' },
pending: { text: 'needs fix', tone: 'script' },
needs_login: { text: 'needs sign-in', tone: 'script' },
enabled: { text: 'enabled', tone: 'scope' },
off: { text: 'off', tone: '' },
available: { text: 'available', tone: '' },
};
/// The one place that decides what a connector's state *is*, from whichever runtime
/// rows exist for it.
///
/// A per-user activation whose credentials failed verification is `pending`, not
/// `active`: the row exists but is deliberately held out of `all_startable`, and
/// calling that "active" would be a lie the user acts on.
///
/// `enabled` vs `active` for a global is the §7 distinction between *running* and
/// *reachable by me*: an admin can enable a connector for someone else and never
/// grant it to themselves, and their own list must not claim they have it.
export function statusOf(row) {
if (row._act) {
if (row._act.auth_state !== 'pending') return 'active';
// An OAuth connector sitting at `pending` is waiting for its interactive
// sign-in, not for a failed credential to be fixed — a different ask.
return row._act.oauth_provider ? 'needs_login' : 'pending';
}
if (row._glob) {
if (!row._glob.enabled) return 'off';
return row._glob.can_use ? 'active' : 'enabled';
}
return 'available';
}
/// Normalizes a catalog entry's `config_schema_json` into form-field descriptors,
/// whether the feed shipped the object-array form or the legacy bare-name list.
export function normalizeSchema(raw) {
if (!Array.isArray(raw)) return [];
return raw.map(e => {
if (typeof e === 'string') {
return { name: e, label: e, description: '', required: false, secret: false, example: '', default: '' };
}
return {
name: e.name || '',
label: e.label || e.name || '',
description: e.description || '',
required: !!e.required,
secret: !!e.secret,
example: e.example || '',
default: e.default || '',
};
});
}
export function parseJson(s, fallback) {
if (!s) return fallback;
try { return JSON.parse(s); } catch { return fallback; }
}
/// Every schema field seeded with its `default` (empty string when none).
export function seedEnv(schema) {
return Object.fromEntries(schema.map(e => [e.name, e.default || '']));
}
export async function jf(url, opts) {
const res = await fetch(url, opts);
if (!res.ok) throw new Error(await res.text() || `HTTP ${res.status}`);
const ct = res.headers.get('content-type') || '';
return ct.includes('application/json') ? res.json() : null;
}
/// Tells the Connectors list its cached state is stale.
export function announceChange() {
window.dispatchEvent(new CustomEvent('connectors-changed'));
}
+3 -2
View File
@@ -119,7 +119,8 @@ export class AppSidebar extends LightElement {
// Segment ends at the first `/` (e.g. `#session/123`) or `?` (e.g. `#file_viewer?path=...`).
const match = hash.match(/^([^/?]+)/);
const segment = match ? match[1] : '';
return ['inbox', 'tasks', 'projects', 'models', 'providers', 'approval', 'agents', 'users', 'roles', 'connectors', 'catalog', 'marketplace', 'profile', 'config', 'llm-requests', 'session', 'tic', 'file_viewer'].includes(segment) ? segment : 'home';
// `connector` (singular) is the per-connector detail page, `connectors` the list.
return ['inbox', 'tasks', 'projects', 'models', 'providers', 'approval', 'agents', 'users', 'roles', 'connectors', 'connector', 'catalog', 'marketplace', 'profile', 'config', 'llm-requests', 'session', 'tic', 'file_viewer'].includes(segment) ? segment : 'home';
}
_tasksSectionFromHash() {
@@ -299,7 +300,7 @@ export class AppSidebar extends LightElement {
<i class="bi bi-tags"></i>
<span class="sidebar-link-name">Roles</span>
</a>
<a href="#" class="sidebar-link ${this._activePage === 'connectors' ? 'active' : ''}"
<a href="#" class="sidebar-link ${this._activePage === 'connectors' || this._activePage === 'connector' ? 'active' : ''}"
@click=${(e) => this._togglePage('connectors', e)}>
<i class="bi bi-plug"></i>
<span class="sidebar-link-name">Connectors</span>