fabro/apps/fabro-web/app/lib/api-client.ts
fabro-sh-fabro[bot] c945fb404b
Some checks are pending
Rust / Format (push) Waiting to run
Rust / Clippy (push) Waiting to run
Rust / Generated Docs (push) Waiting to run
Rust / Test (Linux) (push) Waiting to run
Rust / Test (macOS) (push) Waiting to run
TypeScript / Typecheck (push) Waiting to run
TypeScript / Test (push) Waiting to run
TypeScript / Build (push) Waiting to run
feat: add MCP servers settings UI at /settings/mcps (#540)
## Summary

Adds a full CRUD management UI for server-managed MCP servers at
`/settings/mcps`, consuming the already-shipped `MCPServersApi` backend.
The implementation mirrors the existing `/settings/environments` pages
exactly in structure, naming, and component conventions.

## What changed

### Step 1 — Shared `KeyValueEditor` extracted
`KeyValueEditor`, `KeyValueEntry`, `entriesFromMap`, and
`mapFromEntries` are moved from `environment-form.tsx` into a new
`components/key-value-editor.tsx`. The component gains an optional
`renderEntryHint` prop so per-row warnings can be injected without
coupling the editor to credential logic. `Label` is promoted from
`environment-form.tsx` to `settings-panel.tsx` so both forms can use it.

### Step 2–4 — Query plumbing
- `query-keys.ts`: `mcpServers.{list, detail}` keys.
- `api-client.ts`: `mcpServersApi` instance (same pattern as
`environmentsApi`).
- `queries.ts`: `useMcpServers()` and `useMcpServer(id)` SWR hooks.

### Step 5 — Credential heuristics (`lib/credential-heuristics.ts`)
Pure functions `looksLikeCredential`, `secretNameForKey`,
`secretReference`. Key-name matching covers `authorization`, `password`,
`token`, `api[-_]?key`, `_key`/`_token`/`_secret` suffixes.
Value-entropy fallback fires for strings ≥ 20 chars, no spaces, mixed
case/digit classes. Template references (`{{ secrets.* }}`) are never
flagged.

### Step 6–7 — Form model + component (`components/mcp-server-form.tsx`)
- Flat `McpServerFormValues` discriminated on `McpTransportKind`.
- `defaultMcpServerFormValues`, `mcpServerToFormValues` (populates
`env`/`headers` from `env_keys`/`header_keys` with **empty values** —
the §5 write-only design), `createRequestFromForm`,
`replaceRequestFromForm`, `isMcpServerFormValid`, `credentialWarnings`.
- `McpServerFormFields` renders stdio / http / sandbox panels switching
on `values.transport`. Per-row credential nudge opens the secrets-new
page in a new tab and substitutes a `{{ secrets.NAME }}` reference; save
is never blocked by the heuristic.
- On edit, a row with a non-empty key and empty value blocks save with
an inline error (the intentional overwrite guard).

### Step 8–10 — Route pages
| File | Mirrors |
|---|---|
| `routes/settings-mcps.tsx` | `settings-environments.tsx` |
| `routes/settings-mcps-new.tsx` | `settings-environments-new.tsx` |
| `routes/settings-mcps-edit.tsx` | `settings-environments-edit.tsx` |

The edit page shows a write-only-values banner whenever the transport
has any `env_keys`/`header_keys`, uses `key={server.revision}` to
remount the form on external change, and translates 409 responses into
the `staleAwareMessage` pattern.

### Steps 11–12 — Router + nav
Three routes registered under `settings` children. `PuzzlePieceIcon` nav
entry added to the same section as Environments.

### Plan Summary
- Extract `KeyValueEditor` to shared component with hint-injection slot
- Credential heuristics library (pure, fully unit-tested)
- MCP form model: flat values ↔ discriminated API types, write-only-key
guard
- List / new / edit pages following environments pattern exactly
- Route registration and settings nav link


### Fabro Details

<details>
<summary>Ran 9 stages in 65m 58s for $20.54</summary>

| Stage | Duration | Cost | Retries |
|---|---|---|---|
| start | 0s | – | 0 |
| toolchain | 1s | – | 0 |
| preflight_compile | 2m 47s | – | 0 |
| preflight_lint | 4m 15s | – | 0 |
| implement | 26m 29s | $12.27 | 0 |
| simplify_opus | 7m 41s | $4.95 | 0 |
| simplify_gpt | 6m 51s | $2.69 | 0 |
| verify | 15m 44s | – | 0 |
| fixup | 1m 41s | $0.63 | 0 |
| **Total** | **65m 58s** | **$20.54** | **0** |

</details>

<details>
<summary>Ran <code>ImplementPlan.fabro</code> (11 nodes and 14
edges)</summary>

```dot
digraph ImplementPlan {
    graph [
        goal="Implement and simplify",
        model_stylesheet="
            * { model: claude-opus-4-8; }
        "
    ]
    rankdir=LR

    start [shape=Mdiamond, label="Start"]
    exit  [shape=Msquare, label="Exit"]

    toolchain         [label="Toolchain", shape=parallelogram, script="command -v cargo >/dev/null || { curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y && sudo ln -sf $HOME/.cargo/bin/* /usr/local/bin/; }; cargo --version 2>&1", max_retries=0]
    preflight_compile [label="Preflight Compile", shape=parallelogram, script="cargo check -q --workspace 2>&1", max_retries=0]
    preflight_lint    [label="Preflight Lint", shape=parallelogram, script="cargo +nightly-2026-04-14 clippy -q --workspace --all-targets -- -D warnings 2>&1", max_retries=0]
    fix_lints         [label="Fix Lints", prompt="The preflight lint step failed. Read the build output from context and fix all clippy lint warnings.", max_visits=3]
    implement         [label="Implement", prompt="Read the plan file referenced in the goal and implement every step. Make all the code changes described in the plan. Use red/green TDD.", model="gpt-55", reasoning_effort="xhigh"]
    simplify_opus     [label="Simplify (Opus)", prompt="@prompts/simplify.md"]
    simplify_gpt      [label="Simplify (GPT-55)", prompt="@prompts/simplify.md", model="gpt-55"]
    verify            [label="Verify", shape=parallelogram, script="git fetch origin main 2>&1 && git merge --no-edit --no-stat origin/main 2>&1 && cargo +nightly-2026-04-14 fmt --all 2>&1 && cargo dev docs refresh 2>&1 && cargo +nightly-2026-04-14 fmt --check --all 2>&1 && { command -v rg >/dev/null 2>&1 || { echo 'rg is required for verify'; exit 127; }; } && ! rg -n 'AuthMode::Disabled|RunAuthMethod|RunSubjectProvenance|\bActorRef\b|\bActorKind\b|AuthenticatedSubject|AuthenticatedService|AuthorizeRunScoped|AuthorizeRunBlob|AuthorizeStageArtifact|AuthorizeCommandLog|auth_method\s*==\s*\"disabled\"' lib/crates apps lib/packages docs/public/api-reference/fabro-api.yaml 2>&1 && cargo +nightly-2026-04-14 clippy --workspace --all-targets -- -D warnings 2>&1 && cargo nextest run --workspace --status-level slow --profile ci 2>&1 && cargo dev docs check 2>&1 && bun install --frozen-lockfile 2>&1 && (cd apps/fabro-web && bun run typecheck) 2>&1 && (cd apps/fabro-web && bun run test) 2>&1 && (cd lib/packages/fabro-api-client && bun run typecheck) 2>&1 && cargo dev build -- -p fabro-cli --release 2>&1", goal_gate=true, retry_target="fixup"]
    fixup             [label="Fixup", prompt="The verify step failed. Read the build output from context and fix all format, clippy, Rust test, docs, TypeScript typecheck/test, and build failures.", max_visits=3]

    start -> toolchain
    toolchain -> preflight_compile [condition="outcome=succeeded"]
    toolchain -> exit
    preflight_compile -> preflight_lint [condition="outcome=succeeded"]
    preflight_compile -> exit
    preflight_lint -> implement [condition="outcome=succeeded"]
    preflight_lint -> fix_lints
    fix_lints -> preflight_lint
    implement -> simplify_opus -> simplify_gpt -> verify
    verify -> exit  [condition="outcome=succeeded"]
    verify -> fixup
    fixup -> verify
}

```

</details>

⚒️ Generated with [Fabro](https://fabro.sh)

---------

Co-authored-by: Fabro <noreply@fabro.sh>
2026-07-01 10:32:37 -04:00

424 lines
11 KiB
TypeScript

import axios, {
isAxiosError,
type AxiosPromise,
type AxiosResponse,
type RawAxiosRequestConfig,
} from "axios";
import {
AuthApi,
AutomationsApi,
Configuration,
EnvironmentsApi,
HumanInTheLoopApi,
InsightsApi,
InstallApi,
MCPServersApi,
ModelsApi,
RunInternalsApi,
RunOutputsApi,
RunsApi,
SecretsApi,
SessionsApi,
SettingsApi,
SystemApi,
VariablesApi,
WorkflowsApi,
} from "@qltysh/fabro-api-client";
export interface PaginatedEnvelope<T> {
data: T[];
meta: { has_more: boolean };
}
export class ApiError extends Error {
readonly status: number;
readonly requestId: string | null;
readonly body: unknown;
constructor({
status,
message,
requestId,
body,
}: {
status: number;
message: string;
requestId: string | null;
body: unknown;
}) {
super(message);
this.name = "ApiError";
this.status = status;
this.requestId = requestId;
this.body = body;
}
}
interface ApiCallOptions {
redirectOnUnauthorized?: boolean;
}
const PAGINATED_API_MAX_PAGES = 50;
const PAGINATED_API_MAX_ITEMS = 5000;
export const generatedAxios = axios.create({
baseURL: "",
withCredentials: true,
});
export const generatedApiConfiguration = new Configuration({
basePath: "",
baseOptions: {
withCredentials: true,
},
});
export const authApi = new AuthApi(
generatedApiConfiguration,
"",
generatedAxios,
);
export const automationsApi = new AutomationsApi(
generatedApiConfiguration,
"",
generatedAxios,
);
export const environmentsApi = new EnvironmentsApi(
generatedApiConfiguration,
"",
generatedAxios,
);
export const humanInTheLoopApi = new HumanInTheLoopApi(
generatedApiConfiguration,
"",
generatedAxios,
);
export const insightsApi = new InsightsApi(
generatedApiConfiguration,
"",
generatedAxios,
);
export const mcpServersApi = new MCPServersApi(
generatedApiConfiguration,
"",
generatedAxios,
);
export const installApi = new InstallApi(
generatedApiConfiguration,
"",
generatedAxios,
);
export const modelsApi = new ModelsApi(
generatedApiConfiguration,
"",
generatedAxios,
);
export const runInternalsApi = new RunInternalsApi(
generatedApiConfiguration,
"",
generatedAxios,
);
export const runOutputsApi = new RunOutputsApi(
generatedApiConfiguration,
"",
generatedAxios,
);
export const runsApi = new RunsApi(
generatedApiConfiguration,
"",
generatedAxios,
);
export const secretsApi = new SecretsApi(
generatedApiConfiguration,
"",
generatedAxios,
);
export const sessionsApi = new SessionsApi(
generatedApiConfiguration,
"",
generatedAxios,
);
export const settingsApi = new SettingsApi(
generatedApiConfiguration,
"",
generatedAxios,
);
export const systemApi = new SystemApi(
generatedApiConfiguration,
"",
generatedAxios,
);
export const variablesApi = new VariablesApi(
generatedApiConfiguration,
"",
generatedAxios,
);
export const workflowsApi = new WorkflowsApi(
generatedApiConfiguration,
"",
generatedAxios,
);
export function isNotAvailable(status: number): boolean {
return status === 404 || status === 501;
}
export function extractRequestId(body: unknown): string | null {
if (!body || typeof body !== "object") return null;
const record = body as Record<string, unknown>;
if (typeof record.request_id === "string") return record.request_id;
if (typeof record.requestId === "string") return record.requestId;
const errors = record.errors;
if (!Array.isArray(errors) || errors.length === 0) return null;
const first = errors[0];
if (!first || typeof first !== "object") return null;
const error = first as Record<string, unknown>;
if (typeof error.request_id === "string") return error.request_id;
if (typeof error.requestId === "string") return error.requestId;
if (typeof error.detail === "string") {
const match = error.detail.match(/request[_ ]id[=:]?\s*([a-zA-Z0-9-_]+)/i);
if (match) return match[1];
}
return null;
}
function requestIdFromHeaders(headers: unknown): string | null {
return (
headerValue(headers, "x-request-id")
?? headerValue(headers, "x-fabro-request-id")
?? headerValue(headers, "request-id")
);
}
function headerValue(headers: unknown, name: string): string | null {
if (!headers || typeof headers !== "object") return null;
const getter = (headers as { get?: (key: string) => unknown }).get;
if (typeof getter === "function") {
const value = getter.call(headers, name);
if (typeof value === "string") return value;
}
const wanted = name.toLowerCase();
for (const [key, value] of Object.entries(headers as Record<string, unknown>)) {
if (key.toLowerCase() !== wanted) continue;
if (typeof value === "string") return value;
if (Array.isArray(value) && typeof value[0] === "string") return value[0];
}
return null;
}
function apiErrorFromAxios(error: unknown): ApiError | null {
if (!isAxiosError(error) || !error.response) return null;
const { response } = error;
const requestId = requestIdFromHeaders(response.headers) ?? extractRequestId(response.data);
return new ApiError({
status: response.status,
message: extractErrorDetail(response.data) ?? (response.statusText || `HTTP ${response.status}`),
requestId,
body: response.data ?? null,
});
}
export async function apiErrorFromFetchResponse(response: Response): Promise<ApiError | null> {
if (response.ok) return null;
const body = await readFetchErrorBody(response);
const requestId = requestIdFromHeaders(response.headers) ?? extractRequestId(body);
return new ApiError({
status: response.status,
message: extractErrorDetail(body) ?? (response.statusText || `HTTP ${response.status}`),
requestId,
body,
});
}
async function readFetchErrorBody(response: Response): Promise<unknown> {
const contentType = response.headers.get("content-type") ?? "";
if (contentType.includes("application/json")) {
return response.json().catch(() => null);
}
const text = await response.text().catch(() => "");
if (!text) return null;
try {
return JSON.parse(text);
} catch {
return text;
}
}
function extractErrorDetail(body: unknown): string | null {
if (!body || typeof body !== "object") return null;
const errors = (body as Record<string, unknown>).errors;
if (!Array.isArray(errors) || errors.length === 0) return null;
const first = errors[0];
if (!first || typeof first !== "object") return null;
const detail = (first as Record<string, unknown>).detail;
return typeof detail === "string" && detail.length > 0 ? detail : null;
}
function redirectToLogin(error: ApiError, options: ApiCallOptions) {
if (error.status !== 401 || options.redirectOnUnauthorized === false) return;
if (typeof window !== "undefined") {
window.location.href = "/login";
}
}
export async function apiData<T>(
call: () => AxiosPromise<T>,
options: ApiCallOptions = {},
): Promise<T> {
try {
const response = await call();
return response.data;
} catch (error) {
const apiError = apiErrorFromAxios(error);
if (!apiError) throw error;
redirectToLogin(apiError, options);
throw apiError;
}
}
export async function apiResponse<T>(
call: () => AxiosPromise<T>,
options: ApiCallOptions = {},
): Promise<AxiosResponse<T>> {
try {
return await call();
} catch (error) {
const apiError = apiErrorFromAxios(error);
if (!apiError) throw error;
redirectToLogin(apiError, options);
throw apiError;
}
}
export async function apiNullableData<T>(
call: () => AxiosPromise<T>,
): Promise<T | null> {
try {
return await apiData(call);
} catch (error) {
if (error instanceof ApiError && isNotAvailable(error.status)) return null;
throw error;
}
}
export async function fetchAllPages<TItem, TExtra extends object = {}>(
label: string,
loadPage: (limit: number, offset: number) => Promise<PaginatedEnvelope<TItem> & TExtra>,
): Promise<PaginatedEnvelope<TItem> & TExtra> {
const limit = 100;
let offset = 0;
const data: TItem[] = [];
let extras: TExtra | null = null;
let pagesLoaded = 0;
while (true) {
const page = await loadPage(limit, offset);
if (extras == null) {
const { data: _data, meta: _meta, ...rest } = page as PaginatedEnvelope<TItem> &
Record<string, unknown>;
extras = rest as TExtra;
}
pagesLoaded += 1;
const pageData = page.data;
const remainingItemBudget = PAGINATED_API_MAX_ITEMS - data.length;
const pageItems = remainingItemBudget > 0 ? pageData.slice(0, remainingItemBudget) : [];
data.push(...pageItems);
if (!page.meta.has_more || pageData.length === 0) {
return {
...(extras ?? ({} as TExtra)),
data,
meta: { has_more: false },
};
}
if (
pagesLoaded >= PAGINATED_API_MAX_PAGES
|| pageItems.length < pageData.length
|| data.length >= PAGINATED_API_MAX_ITEMS
) {
console.warn(
`Stopped paginated API fetch for ${label} after ${pagesLoaded} pages and ${data.length} items because the safety cap was reached.`,
);
return {
...(extras ?? ({} as TExtra)),
data,
meta: { has_more: true },
};
}
offset += page.data.length;
}
}
export async function fetchAllStageEvents<TItem extends { seq: number }>(
label: string,
loadPage: (sinceSeq: number, limit: number) => Promise<PaginatedEnvelope<TItem>>,
): Promise<TItem[]> {
const PAGE_LIMIT = 1000;
const MAX_PAGES = 50;
const data: TItem[] = [];
let sinceSeq = 1;
let pagesLoaded = 0;
while (true) {
const page = await loadPage(sinceSeq, PAGE_LIMIT);
pagesLoaded += 1;
if (page.data.length === 0) {
if (page.meta.has_more) {
console.warn(
`Stage events fetch for ${label} returned an empty page with has_more=true; stopping at ${data.length} items to avoid spinning.`,
);
}
return data;
}
data.push(...page.data);
if (!page.meta.has_more) return data;
if (pagesLoaded >= MAX_PAGES) {
console.warn(
`Stopped stage events fetch for ${label} after ${pagesLoaded} pages and ${data.length} items because the safety cap was reached.`,
);
return data;
}
const highestSeq = page.data.reduce((max, event) => Math.max(max, event.seq), sinceSeq - 1);
if (highestSeq < sinceSeq) {
console.warn(
`Stage events fetch for ${label} returned a non-advancing page at since_seq=${sinceSeq}; stopping at ${data.length} items to avoid spinning.`,
);
return data;
}
sinceSeq = highestSeq + 1;
}
}
export function requestSignalOptions(request?: Request): RawAxiosRequestConfig {
return request?.signal ? { signal: request.signal } : {};
}
export function stageArtifactDownloadUrl(
id: string,
stageId: string,
filename: string,
retry: number,
): string {
const searchParams = new URLSearchParams({
filename,
retry: String(retry),
});
return `${generatedApiConfiguration.basePath ?? ""}/api/v1/runs/${
encodeURIComponent(id)
}/stages/${encodeURIComponent(stageId)}/artifacts/download?${searchParams}`;
}