-
Notifications
You must be signed in to change notification settings - Fork 0
feat: add saved MCP connection diagnostics and approval controls #523
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
6b74b9f
feat: add saved MCP connection tests and permission controls
charlesrhoward 46ff2d2
fix(mcp): preserve diagnostics during bounded session cleanup
charlesrhoward 43d6a30
fix(mcp): validate transport changes and cancel stale tests
charlesrhoward 85e8222
fix(mcp): distinguish saved settings outages from server failures
charlesrhoward File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,26 @@ | ||
| import { NextResponse } from "next/server"; | ||
| import { z } from "zod"; | ||
| import { requireUserId } from "@/lib/auth"; | ||
| import { testSavedMcpServer } from "@/lib/mcp-servers/diagnostics"; | ||
|
|
||
| const defaultDeps = { requireUserId }; | ||
|
|
||
| export function createMcpServerTestHandler(deps = defaultDeps) { | ||
| return async function POST( | ||
| request: Request, | ||
| { params }: { params: Promise<{ id: string }> } | ||
| ) { | ||
| const userId = await deps.requireUserId(); | ||
| if (userId instanceof Response) return userId; | ||
| const { id } = await params; | ||
| if (!z.string().uuid().safeParse(id).success) | ||
| return NextResponse.json({ error: "Invalid server id" }, { status: 400 }); | ||
| const result = await testSavedMcpServer(userId, id, request.signal); | ||
| return NextResponse.json(result ?? { error: "Server not found" }, { | ||
| status: result ? 200 : 404, | ||
| headers: { "Cache-Control": "no-store" }, | ||
| }); | ||
| }; | ||
| } | ||
|
|
||
| export const POST = createMcpServerTestHandler(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,70 @@ | ||
| "use client"; | ||
|
|
||
| import { useEffect, useRef, useState } from "react"; | ||
| import { Button } from "@/components/ui/button"; | ||
| import { diagnosticMessages, diagnosticResultSchema, type McpDiagnosticResult } from "@/lib/mcp-servers/diagnostic-result"; | ||
| import type { McpServer } from "./types"; | ||
|
|
||
| export function ConnectionTest({ server, onResult }: { | ||
| server: McpServer; | ||
| onResult: (result: McpDiagnosticResult) => void; | ||
| }) { | ||
| const [testing, setTesting] = useState(false); | ||
| const [result, setResult] = useState<McpDiagnosticResult | null>(null); | ||
| const [error, setError] = useState<string | null>(null); | ||
| const activeTest = useRef<AbortController | null>(null); | ||
| useEffect(() => () => activeTest.current?.abort(), []); | ||
| async function testConnection() { | ||
| const controller = new AbortController(); | ||
| activeTest.current = controller; | ||
| setTesting(true); | ||
| setResult(null); | ||
| setError(null); | ||
| try { | ||
| const response = await fetch(`/api/mcp-servers/${server.id}/test`, { method: "POST", signal: controller.signal }); | ||
| if (controller.signal.aborted) return; | ||
| if (!response.ok) { | ||
| setError(response.status === 401 ? "Sign in again to test this connection." : response.status === 404 ? "This server no longer exists. Refresh the page." : "The test could not complete. Try again."); | ||
| return; | ||
| } | ||
| const data = diagnosticResultSchema.parse(await response.json()); | ||
| if (controller.signal.aborted) return; | ||
| if (data.serverUpdatedAt && data.serverUpdatedAt !== server.updatedAt) { | ||
| setError("The saved settings changed. Refresh the page, then test again."); | ||
| return; | ||
| } | ||
| setResult(data); | ||
| onResult(data); | ||
| } catch { | ||
| if (!controller.signal.aborted) setError("The test could not complete. Check your connection and try again."); | ||
| } finally { | ||
| if (!controller.signal.aborted) setTesting(false); | ||
| } | ||
| } | ||
| if (server.transport === "stdio") return null; | ||
| const success = result?.status === "success" ? result : null; | ||
| const available = success?.tools.filter((tool) => tool.approval !== "deny") ?? []; | ||
| const automatic = available.filter((tool) => tool.approval !== "prompt").length; | ||
| const prompts = available.length - automatic; | ||
| return <div className="space-y-2 border-t border-border pt-3"> | ||
| <div className="flex flex-wrap items-center gap-3"> | ||
| <Button type="button" size="sm" variant="outline" disabled={testing} onClick={() => void testConnection()}>{testing ? "Testing connection..." : "Test connection"}</Button> | ||
| <p className="text-xs text-muted-foreground">Lists tools without running them.</p> | ||
| </div> | ||
| <div role="status" aria-live="polite" className="space-y-1 text-sm"> | ||
| {!result && !error && !testing && <p className="text-muted-foreground">Not tested in this visit.</p>} | ||
| {error && <p className="text-destructive">{error}</p>} | ||
| {result?.status === "error" && <p className="text-destructive">{diagnosticMessages[result.code]}</p>} | ||
| {success && <> | ||
| <p>Connection test passed. {success.tools.length} {success.tools.length === 1 ? "tool" : "tools"} found.</p> | ||
| {success.enabled ? <p className="text-muted-foreground">{automatic} available in workspace chat. Control approval required: {prompts}. Blocked: {success.tools.length - available.length}.</p> : <p className="text-muted-foreground">This server is disabled. Enable it to make its allowed tools available.</p>} | ||
| {success.tools.length === 0 && <p className="text-muted-foreground">The server did not advertise any tools.</p>} | ||
| {success.tools.length > 0 && <details> | ||
| <summary className="cursor-pointer text-sm">Discovered tools</summary> | ||
| <ul className="mt-2 space-y-1">{success.tools.map((tool) => <li key={tool.name} className="break-words"><span className="font-mono">{tool.name}</span>: {tool.approval === "deny" ? "Blocked" : tool.approval === "prompt" ? "Control only: approval required" : "Runs automatically"}</li>)}</ul> | ||
| </details>} | ||
| </>} | ||
| {result && <p className="text-xs text-muted-foreground">Last test: {new Date(result.checkedAt).toLocaleString()}. Availability can change.</p>} | ||
| </div> | ||
| </div>; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,103 @@ | ||
| "use client"; | ||
|
|
||
| import { useState } from "react"; | ||
| import { Button } from "@/components/ui/button"; | ||
| import { Input } from "@/components/ui/input"; | ||
| import { Label } from "@/components/ui/label"; | ||
| import { Switch } from "@/components/ui/switch"; | ||
| import { Textarea } from "@/components/ui/textarea"; | ||
| import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; | ||
| import { readToolPolicy, toolApproval, updateToolPolicy, normalizeToolNames, type ToolApproval } from "@/lib/mcp-servers/policy"; | ||
| import { parseExtra } from "./helpers"; | ||
|
|
||
| export function PermissionsEditor({ extraText, onChange, toolNames = [] }: { | ||
| extraText: string; | ||
| onChange: (value: string) => void; | ||
| toolNames?: string[]; | ||
| }) { | ||
| const [newTool, setNewTool] = useState(""); | ||
| let extra: Record<string, unknown>; | ||
| let policy: ReturnType<typeof readToolPolicy>; | ||
| try { | ||
| extra = parseExtra(extraText); | ||
| policy = readToolPolicy(extra); | ||
| } catch { | ||
| return <p role="alert" className="text-sm text-destructive">Tool permissions are invalid. Correct the permission fields in Extra JSON before saving.</p>; | ||
| } | ||
| const write = (value: Record<string, unknown>) => onChange(JSON.stringify(value, null, 2)); | ||
| const names = [...new Set([...toolNames, ...Object.keys(policy.tools ?? {}), ...(policy.enabled_tools ?? []), ...(policy.disabled_tools ?? [])])].filter(Boolean).sort(); | ||
| const setMode = (mode: ToolApproval | "inherit", tool?: string) => write(updateToolPolicy(extra, { mode, tool })); | ||
| const lines = (value: string) => value ? value.split("\n") : []; | ||
|
|
||
| return <section aria-label="Tool permissions" className="space-y-4 border-t border-border pt-4"> | ||
| <div> | ||
| <h3 className="text-sm font-medium">Tool permissions</h3> | ||
| <p className="text-sm text-muted-foreground">Choose which tools agents can use. Changes apply on the next turn.</p> | ||
| </div> | ||
| <div className="space-y-2"> | ||
| <Label htmlFor="mcp-default-approval">Default approval</Label> | ||
| <Select value={policy.default_tools_approval_mode === "approve" ? "auto" : policy.default_tools_approval_mode ?? "auto"} onValueChange={(value) => setMode(value as ToolApproval)}> | ||
| <SelectTrigger id="mcp-default-approval"><SelectValue /></SelectTrigger> | ||
| <SelectContent> | ||
| <SelectItem value="auto">Run automatically</SelectItem> | ||
| <SelectItem value="prompt">Ask in Control</SelectItem> | ||
| </SelectContent> | ||
| </Select> | ||
| <p className="text-sm text-muted-foreground">Tools that need approval are available in Control only, not workspace chat. The CLI also receives these permissions.</p> | ||
| </div> | ||
| <div className="flex items-center gap-3"> | ||
| <Switch id="mcp-all-tools" checked={policy.enabled_tools === undefined} onCheckedChange={(checked) => { | ||
| const next = { ...extra }; | ||
| if (checked) delete next.enabled_tools; | ||
| else next.enabled_tools = []; | ||
| write(next); | ||
| }} /> | ||
| <Label htmlFor="mcp-all-tools">Allow all tools unless blocked</Label> | ||
| </div> | ||
| {policy.enabled_tools !== undefined && <div className="space-y-2"> | ||
| <Label htmlFor="mcp-allowed-tools">Allowed tools (one name per line)</Label> | ||
| <Textarea id="mcp-allowed-tools" value={policy.enabled_tools.join("\n")} onChange={(event) => write({ ...extra, enabled_tools: lines(event.target.value) })} onBlur={(event) => write({ ...extra, enabled_tools: normalizeToolNames(lines(event.target.value)) })} /> | ||
| <p className="text-sm text-muted-foreground">An empty list allows no tools. New tools stay unavailable until added here.</p> | ||
| </div>} | ||
| <div className="space-y-2"> | ||
| <Label htmlFor="mcp-blocked-tools">Blocked tools (one name per line)</Label> | ||
| <Textarea id="mcp-blocked-tools" value={(policy.disabled_tools ?? []).join("\n")} onChange={(event) => write({ ...extra, disabled_tools: lines(event.target.value) })} onBlur={(event) => write({ ...extra, disabled_tools: normalizeToolNames(lines(event.target.value)) })} /> | ||
| <p className="text-sm text-muted-foreground">Blocked tools remain unavailable even if their approval allows them.</p> | ||
| </div> | ||
| <div className="space-y-3"> | ||
| <h4 className="text-sm font-medium">Per-tool approval</h4> | ||
| {names.map((name) => { | ||
| const entry = policy.tools?.[name]; | ||
| const mode = entry?.approval_mode === "approve" ? "auto" : entry?.approval_mode ?? "inherit"; | ||
| const effective = toolApproval(policy, name); | ||
| return <div key={name} className="grid gap-2 border-b border-border pb-3 sm:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]"> | ||
| <div className="min-w-0"> | ||
| <p className="break-all font-mono text-sm">{name}</p> | ||
| <p className="text-xs text-muted-foreground">{effective === "deny" ? "Blocked" : effective === "prompt" ? "Control only: approval required" : "Workspace chat and Control"}</p> | ||
| {entry?.enabled === false && <div className="mt-2 flex items-center gap-2"> | ||
| <Switch aria-label={`Enable ${name}`} checked={false} onCheckedChange={() => { | ||
| const tools = (extra.tools ?? {}) as Record<string, Record<string, unknown>>; | ||
| write({ ...extra, tools: { ...tools, [name]: { ...tools[name], enabled: true } } }); | ||
| }} /> | ||
| <span className="text-xs">Disabled in saved settings</span> | ||
| </div>} | ||
| </div> | ||
| <Select disabled={entry?.enabled === false} value={mode} onValueChange={(value) => setMode(value as ToolApproval | "inherit", name)}> | ||
| <SelectTrigger aria-label={`Approval for ${name}`}><SelectValue /></SelectTrigger> | ||
| <SelectContent> | ||
| <SelectItem value="inherit">Use default</SelectItem> | ||
| <SelectItem value="auto">Run automatically</SelectItem> | ||
| <SelectItem value="prompt">Ask in Control</SelectItem> | ||
| <SelectItem value="deny">Block</SelectItem> | ||
| </SelectContent> | ||
| </Select> | ||
| </div>; | ||
| })} | ||
| <div className="flex flex-col gap-2 sm:flex-row"> | ||
| <Input aria-label="Tool name for approval override" placeholder="Exact tool name" value={newTool} onChange={(event) => setNewTool(event.target.value)} /> | ||
| <Button type="button" variant="outline" disabled={!newTool.trim() || names.includes(newTool.trim())} onClick={() => { setMode("inherit", newTool.trim()); setNewTool(""); }}>Add tool rule</Button> | ||
| </div> | ||
| <p className="text-xs text-muted-foreground">Test the saved connection to list its tools, or enter an exact tool name.</p> | ||
| </div> | ||
| </section>; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.