fabro/apps/fabro-web/app/lib/queries.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

556 lines
15 KiB
TypeScript

import useSWR, { type SWRConfiguration } from "swr";
import type {
ApiQuestion,
AuthConfigResponse,
AuthMeResponse,
AuthSessionsResponse,
Automation,
AutomationListResponse,
BoardColumn,
CommandLogResponse,
Environment,
EnvironmentListResponse,
EventEnvelope,
ListRunsDirectionEnum,
ListRunsSortEnum,
McpServer,
McpServerListResponse,
Model,
PaginatedRunCommitList,
PaginatedRunFileList,
PaginatedRunList,
PaginatedRunStageList,
PaginatedWorkflowListResponse,
ProviderList,
PullRequestResponse,
RunArtifactListResponse,
RunBilling,
RunProjection,
Run,
SandboxDetails,
SecretListResponse,
SandboxFileListResponse,
SandboxServiceListResponse,
ServerSettings,
StageContextWindow,
SystemInfoResponse,
SystemIntegrationsResponse,
SystemResourcesResponse,
Variable,
VariableListResponse,
VncPreviewResponse,
WorkflowDetailResponse,
WorkflowSettings,
} from "@qltysh/fabro-api-client";
import {
apiData,
apiNullableData,
apiResponse,
authApi,
automationsApi,
environmentsApi,
fetchAllPages,
fetchAllStageEvents,
generatedAxios,
humanInTheLoopApi,
insightsApi,
mcpServersApi,
modelsApi,
runInternalsApi,
runOutputsApi,
runsApi,
secretsApi,
settingsApi,
systemApi,
variablesApi,
workflowsApi,
type PaginatedEnvelope,
} from "./api-client";
import {
queryKeys,
runFileScopeSelection,
type RunFileSelection,
type RunGraphDirection,
} from "./query-keys";
const immutableOptions: SWRConfiguration = {
revalidateIfStale: false,
revalidateOnFocus: false,
revalidateOnReconnect: false,
};
export interface RunsListFilters {
status?: BoardColumn[];
sort?: ListRunsSortEnum;
direction?: ListRunsDirectionEnum;
includeArchived?: boolean;
}
export interface RunsPageOptions extends RunsListFilters {
limit?: number;
offset?: number;
parentId?: string;
}
export function useAuthConfig() {
return useSWR<AuthConfigResponse>(
queryKeys.auth.config(),
() => apiData(() => authApi.getAuthConfig()),
immutableOptions,
);
}
export function useAuthMe() {
return useSWR<AuthMeResponse>(
queryKeys.auth.me(),
() => apiData(() => authApi.getAuthMe()),
{ dedupingInterval: 10_000 },
);
}
export function useAuthSessions() {
return useSWR<AuthSessionsResponse>(
queryKeys.auth.sessions(),
() => apiData(() => authApi.listAuthSessions()),
);
}
export function useSystemInfo(refreshInterval?: number) {
return useSWR<SystemInfoResponse>(
queryKeys.system.info(),
() => apiData(() => systemApi.getSystemInfo()),
refreshInterval ? { ...immutableOptions, refreshInterval } : immutableOptions,
);
}
export function useSystemIntegrations() {
return useSWR<SystemIntegrationsResponse>(
queryKeys.system.integrations(),
() => apiData(() => systemApi.getSystemIntegrations()),
{ refreshInterval: 5_000 },
);
}
export function useSystemResources() {
return useSWR<SystemResourcesResponse>(
queryKeys.system.resources(),
() => apiData(() => systemApi.getSystemResources()),
{ refreshInterval: 5_000 },
);
}
export function useAllRuns(filters: RunsListFilters = {}, enabled = true) {
return useSWR<PaginatedEnvelope<Run>>(
enabled ? queryKeys.runs.all(filters) : null,
() =>
fetchAllPages("runs", (limit, offset) =>
apiData(() =>
runsApi.listRuns(
limit,
offset,
filters.includeArchived ?? false,
undefined,
filters.status,
filters.sort,
filters.direction,
),
),
),
);
}
export function useRunsPage(opts: RunsPageOptions = {}, enabled = true) {
return useSWR<PaginatedRunList>(
enabled ? queryKeys.runs.page(opts) : null,
() =>
apiData(() =>
runsApi.listRuns(
opts.limit,
opts.offset,
opts.includeArchived ?? false,
opts.parentId,
opts.status,
opts.sort,
opts.direction,
),
),
{ keepPreviousData: true },
);
}
export function useRun(id: string | undefined) {
return useSWR<Run | null>(
id ? queryKeys.runs.detail(id) : null,
() => apiNullableData(() => runsApi.retrieveRun(id!)),
);
}
export function useRunState(id: string | undefined) {
return useSWR<RunProjection | null>(
id ? queryKeys.runs.state(id) : null,
() => apiNullableData(() => runInternalsApi.getRunState(id!)),
);
}
export function useRunFiles(
id: string | undefined,
selection: RunFileSelection = runFileScopeSelection("committed"),
) {
return useSWR<PaginatedRunFileList | null>(
id ? queryKeys.runs.files(id, selection) : null,
() =>
apiNullableData(() =>
selection.kind === "scope"
? runOutputsApi.listRunFiles(
id!,
undefined,
undefined,
selection.scope,
)
: runOutputsApi.listRunFiles(
id!,
undefined,
undefined,
undefined,
selection.fromSha,
selection.toSha,
),
),
{ keepPreviousData: true },
);
}
export function useRunCommits(id: string | undefined) {
return useSWR<PaginatedRunCommitList | null>(
id ? queryKeys.runs.commits(id) : null,
() => apiNullableData(() => runOutputsApi.listRunCommits(id!, 100)),
{ keepPreviousData: true },
);
}
export function useRunStages(id: string | undefined) {
return useSWR<PaginatedRunStageList | null>(
id ? queryKeys.runs.stages(id) : null,
() => apiNullableData(() => runInternalsApi.listRunStages(id!)),
);
}
export function useRunGraph(id: string | undefined, direction?: RunGraphDirection) {
return useSWR<string | null>(
id ? queryKeys.runs.graph(id, direction) : null,
() => apiNullableData(() => runsApi.retrieveRunGraph(id!, direction)),
);
}
export function useRunGraphSource(id: string | undefined, enabled: boolean) {
return useSWR<string | null>(
id && enabled ? queryKeys.runs.graphSource(id) : null,
() => apiNullableData(() => runsApi.retrieveRunGraphSource(id!)),
);
}
export function useRunLogs(id: string | undefined, refreshInterval?: number) {
return useSWR<string | null>(
id ? queryKeys.runs.logs(id) : null,
() => apiNullableData(() => runInternalsApi.getRunLogs(id!)),
refreshInterval ? { refreshInterval } : undefined,
);
}
export function useRunArtifacts(id: string | undefined) {
return useSWR<RunArtifactListResponse | null>(
id ? queryKeys.runs.artifacts(id) : null,
() => apiNullableData(() => runInternalsApi.listRunArtifacts(id!)),
);
}
export function useRunSettings<T = WorkflowSettings>(id: string | undefined) {
return useSWR<T>(
id ? queryKeys.runs.settings(id) : null,
() => apiData(() => runInternalsApi.retrieveRunSettings(id!)) as Promise<T>,
immutableOptions,
);
}
export function useRunBilling(id: string | undefined) {
return useSWR<RunBilling>(
id ? queryKeys.runs.billing(id) : null,
() => apiData(() => runOutputsApi.retrieveRunBilling(id!)),
);
}
export function useRunSandboxDetails(id: string | undefined) {
return useSWR<SandboxDetails | null>(
id ? queryKeys.runs.sandbox(id) : null,
() => apiNullableData(() => humanInTheLoopApi.retrieveRunSandbox(id!)),
);
}
export function useSandboxFiles(
id: string | undefined,
path: string | undefined,
depth?: number,
) {
return useSWR<SandboxFileListResponse>(
id && path ? queryKeys.runs.sandboxFiles(id, path, depth) : null,
() => apiData(() => humanInTheLoopApi.listSandboxFiles(id!, path!, depth)),
{ keepPreviousData: true },
);
}
export function useSandboxServices(id: string | undefined) {
return useSWR<SandboxServiceListResponse>(
id ? queryKeys.runs.sandboxServices(id) : null,
() => apiData(() => humanInTheLoopApi.listSandboxServices(id!)),
{ keepPreviousData: true },
);
}
export function useSandboxVncPreview(id: string | undefined, enabled: boolean) {
return useSWR<VncPreviewResponse>(
id && enabled ? queryKeys.runs.sandboxVnc(id) : null,
() => apiData(() => humanInTheLoopApi.createSandboxVncPreview(id!)),
{ revalidateOnFocus: false, revalidateOnReconnect: false, shouldRetryOnError: false },
);
}
export function useSandboxFile(
id: string | undefined,
path: string | null | undefined,
) {
return useSWR<ArrayBuffer>(
id && path ? queryKeys.runs.sandboxFile(id, path) : null,
async () => {
const url = `/api/v1/runs/${encodeURIComponent(id!)}/sandbox/file`;
const response = await apiResponse(() =>
generatedAxios.get<ArrayBuffer>(url, {
params: { path: path! },
responseType: "arraybuffer",
}),
);
return response.data;
},
{ revalidateOnFocus: false, revalidateOnReconnect: false },
);
}
export function useRunQuestions(id: string | undefined, enabled: boolean) {
return useSWR<ApiQuestion[]>(
id && enabled ? queryKeys.runs.questions(id, 25, 0) : null,
async () => {
const payload = await apiNullableData(() => humanInTheLoopApi.listRunQuestions(id!, 25, 0));
return payload?.data ?? [];
},
);
}
// Fetches live pull request details from GitHub. The header popover mounts the
// consumer of this hook only on hover, so the request stays lazy.
export function useRunPullRequest(id: string | undefined) {
return useSWR<PullRequestResponse | null>(
id ? queryKeys.runs.pullRequest(id) : null,
() => apiNullableData(() => runsApi.getRunPullRequest(id!)),
);
}
export function useRunStageEvents(id: string | undefined, stageId: string | undefined) {
return useSWR<EventEnvelope[]>(
id && stageId ? queryKeys.runs.stageEvents(id, stageId) : null,
() =>
fetchAllStageEvents(`run ${id} stage ${stageId}`, (sinceSeq, limit) =>
apiData(() => runInternalsApi.listStageEvents(id!, stageId!, sinceSeq, limit)),
),
);
}
export function useRunStageContextWindow(
id: string | undefined,
stageId: string | undefined,
) {
return useSWR<StageContextWindow | null>(
id && stageId ? queryKeys.runs.stageContextWindow(id, stageId) : null,
() => apiNullableData(() => runInternalsApi.getRunStageContextWindow(id!, stageId!)),
);
}
export function useRunEventsList(id: string | undefined) {
return useSWR<EventEnvelope[]>(
id ? queryKeys.runs.events(id, 1000) : null,
() =>
fetchAllStageEvents(`run ${id} events`, (sinceSeq, limit) =>
apiData(() => runInternalsApi.listRunEvents(id!, sinceSeq, limit)),
),
);
}
function fetchRunCommandLog(
id: string,
stageId: string,
offset: number,
limit?: number,
) {
return apiData<CommandLogResponse>(() =>
runInternalsApi.getRunStageCommandLog(id, stageId, offset, limit),
);
}
export function useRunStageLog(
id: string | undefined,
stageId: string | undefined,
enabled: boolean,
) {
return useSWR<CommandLogResponse>(
enabled && id && stageId ? queryKeys.runs.stageLog(id, stageId) : null,
() => apiData(() => runInternalsApi.getRunStageCommandLog(id!, stageId!)),
);
}
export function useAutomations() {
return useSWR<AutomationListResponse>(
queryKeys.automations.list(),
() => apiData(() => automationsApi.listAutomations()),
);
}
export function useAutomation(id: string | undefined) {
return useSWR<Automation | null>(
id ? queryKeys.automations.detail(id) : null,
() => apiNullableData(() => automationsApi.retrieveAutomation(id!)),
);
}
export interface AutomationRunsPageOptions {
limit?: number;
offset?: number;
}
export function useAutomationRuns(id: string | undefined, opts: AutomationRunsPageOptions = {}) {
return useSWR<PaginatedRunList | null>(
id ? queryKeys.automations.runs(id, opts) : null,
() => apiNullableData(() => automationsApi.listAutomationRuns(id!, opts.limit, opts.offset)),
{ keepPreviousData: true },
);
}
export function useEnvironments() {
return useSWR<EnvironmentListResponse>(
queryKeys.environments.list(),
() => apiData(() => environmentsApi.listEnvironments()),
);
}
export function useEnvironment(id: string | undefined) {
return useSWR<Environment | null>(
id ? queryKeys.environments.detail(id) : null,
id ? () => apiNullableData(() => environmentsApi.retrieveEnvironment(id)) : null,
);
}
export function useMcpServers() {
return useSWR<McpServerListResponse>(
queryKeys.mcpServers.list(),
() => apiData(() => mcpServersApi.listMcpServers()),
);
}
export function useMcpServer(id: string | undefined) {
return useSWR<McpServer | null>(
id ? queryKeys.mcpServers.detail(id) : null,
id ? () => apiNullableData(() => mcpServersApi.retrieveMcpServer(id)) : null,
);
}
export function useWorkflows() {
return useSWR<PaginatedWorkflowListResponse | null>(
queryKeys.workflows.list(),
() => apiNullableData(() => workflowsApi.listWorkflows()),
immutableOptions,
);
}
export function useWorkflow(name: string | undefined) {
return useSWR<WorkflowDetailResponse | null>(
name ? queryKeys.workflows.detail(name) : null,
() => apiNullableData(() => workflowsApi.retrieveWorkflow(name!)),
immutableOptions,
);
}
export function useWorkflowRuns(name: string | undefined) {
return useSWR<PaginatedRunList | null>(
name ? queryKeys.workflows.runs(name) : null,
() => apiNullableData(() => workflowsApi.listWorkflowRuns(name!)),
);
}
export function useInsightsQueries() {
return useSWR(
queryKeys.insights.queries(),
() => apiData(() => insightsApi.listSavedQueries()),
immutableOptions,
);
}
export function useInsightsHistory() {
return useSWR(
queryKeys.insights.history(),
() => apiData(() => insightsApi.listQueryHistory()),
immutableOptions,
);
}
export function useServerSettings() {
return useSWR<ServerSettings>(
queryKeys.settings.server(),
() => apiData(() => settingsApi.retrieveServerSettings()),
immutableOptions,
);
}
export function useProviders() {
return useSWR<ProviderList>(
queryKeys.providers.list(),
() => apiData(() => modelsApi.listProviders()),
immutableOptions,
);
}
export function useModels(provider: string, query: string) {
return useSWR<PaginatedEnvelope<Model>>(
queryKeys.models.list(provider, query),
() =>
fetchAllPages("models", (limit, offset) =>
apiData(() =>
modelsApi.listModels(
provider || undefined,
query || undefined,
limit,
offset,
),
),
),
immutableOptions,
);
}
export function useSecrets() {
return useSWR<SecretListResponse>(
queryKeys.secrets.list(),
() => apiData(() => secretsApi.listSecrets()),
);
}
export function useVariables() {
return useSWR<VariableListResponse>(
queryKeys.variables.list(),
() => apiData(() => variablesApi.listVariables()),
);
}
export function useVariable(name: string | undefined) {
return useSWR<Variable | null>(
name ? queryKeys.variables.detail(name) : null,
() => apiNullableData(() => variablesApi.getVariable(name!)),
);
}