Merge branch 'main' into fix/validate-json-on-tool-execution
This commit is contained in:
commit
119922b8b5
16 changed files with 6549 additions and 1285 deletions
|
|
@ -6,6 +6,7 @@ import { AuthDebuggerState, EMPTY_DEBUGGER_STATE } from "../lib/auth-types";
|
|||
import { OAuthFlowProgress } from "./OAuthFlowProgress";
|
||||
import { OAuthStateMachine } from "../lib/oauth-state-machine";
|
||||
import { SESSION_KEYS } from "../lib/constants";
|
||||
import { validateRedirectUrl } from "@/utils/urlValidation";
|
||||
|
||||
export interface AuthDebuggerProps {
|
||||
serverUrl: string;
|
||||
|
|
@ -163,13 +164,30 @@ const AuthDebugger = ({
|
|||
currentState.oauthStep === "authorization_code" &&
|
||||
currentState.authorizationUrl
|
||||
) {
|
||||
// Validate the URL before redirecting
|
||||
try {
|
||||
validateRedirectUrl(currentState.authorizationUrl);
|
||||
} catch (error) {
|
||||
updateAuthState({
|
||||
...currentState,
|
||||
isInitiatingAuth: false,
|
||||
latestError:
|
||||
error instanceof Error ? error : new Error(String(error)),
|
||||
statusMessage: {
|
||||
type: "error",
|
||||
message: `Invalid authorization URL: ${error instanceof Error ? error.message : String(error)}`,
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Store the current auth state before redirecting
|
||||
sessionStorage.setItem(
|
||||
SESSION_KEYS.AUTH_DEBUGGER_STATE,
|
||||
JSON.stringify(currentState),
|
||||
);
|
||||
// Open the authorization URL automatically
|
||||
window.location.href = currentState.authorizationUrl;
|
||||
window.location.href = currentState.authorizationUrl.toString();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
241
client/src/components/CustomHeaders.tsx
Normal file
241
client/src/components/CustomHeaders.tsx
Normal file
|
|
@ -0,0 +1,241 @@
|
|||
import { useState } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { Plus, Trash2, Eye, EyeOff } from "lucide-react";
|
||||
import {
|
||||
CustomHeaders as CustomHeadersType,
|
||||
CustomHeader,
|
||||
createEmptyHeader,
|
||||
} from "@/lib/types/customHeaders";
|
||||
|
||||
interface CustomHeadersProps {
|
||||
headers: CustomHeadersType;
|
||||
onChange: (headers: CustomHeadersType) => void;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
const CustomHeaders = ({
|
||||
headers,
|
||||
onChange,
|
||||
className,
|
||||
}: CustomHeadersProps) => {
|
||||
const [isJsonMode, setIsJsonMode] = useState(false);
|
||||
const [jsonValue, setJsonValue] = useState("");
|
||||
const [jsonError, setJsonError] = useState<string | null>(null);
|
||||
const [visibleValues, setVisibleValues] = useState<Set<number>>(new Set());
|
||||
|
||||
const updateHeader = (
|
||||
index: number,
|
||||
field: keyof CustomHeader,
|
||||
value: string | boolean,
|
||||
) => {
|
||||
const newHeaders = [...headers];
|
||||
newHeaders[index] = { ...newHeaders[index], [field]: value };
|
||||
onChange(newHeaders);
|
||||
};
|
||||
|
||||
const addHeader = () => {
|
||||
onChange([...headers, createEmptyHeader()]);
|
||||
};
|
||||
|
||||
const removeHeader = (index: number) => {
|
||||
const newHeaders = headers.filter((_, i) => i !== index);
|
||||
onChange(newHeaders);
|
||||
};
|
||||
|
||||
const toggleValueVisibility = (index: number) => {
|
||||
const newVisible = new Set(visibleValues);
|
||||
if (newVisible.has(index)) {
|
||||
newVisible.delete(index);
|
||||
} else {
|
||||
newVisible.add(index);
|
||||
}
|
||||
setVisibleValues(newVisible);
|
||||
};
|
||||
|
||||
const switchToJsonMode = () => {
|
||||
const jsonObject: Record<string, string> = {};
|
||||
headers.forEach((header) => {
|
||||
if (header.enabled && header.name.trim() && header.value.trim()) {
|
||||
jsonObject[header.name.trim()] = header.value.trim();
|
||||
}
|
||||
});
|
||||
setJsonValue(JSON.stringify(jsonObject, null, 2));
|
||||
setJsonError(null);
|
||||
setIsJsonMode(true);
|
||||
};
|
||||
|
||||
const switchToFormMode = () => {
|
||||
try {
|
||||
const parsed = JSON.parse(jsonValue);
|
||||
if (
|
||||
typeof parsed !== "object" ||
|
||||
parsed === null ||
|
||||
Array.isArray(parsed)
|
||||
) {
|
||||
setJsonError("JSON must be an object with string key-value pairs");
|
||||
return;
|
||||
}
|
||||
|
||||
const newHeaders: CustomHeadersType = Object.entries(parsed).map(
|
||||
([name, value]) => ({
|
||||
name,
|
||||
value: String(value),
|
||||
enabled: true,
|
||||
}),
|
||||
);
|
||||
|
||||
onChange(newHeaders);
|
||||
setJsonError(null);
|
||||
setIsJsonMode(false);
|
||||
} catch {
|
||||
setJsonError("Invalid JSON format");
|
||||
}
|
||||
};
|
||||
|
||||
const handleJsonChange = (value: string) => {
|
||||
setJsonValue(value);
|
||||
setJsonError(null);
|
||||
};
|
||||
|
||||
if (isJsonMode) {
|
||||
return (
|
||||
<div className={`space-y-3 ${className}`}>
|
||||
<div className="flex justify-between items-center gap-2">
|
||||
<h4 className="text-sm font-semibold flex-shrink-0">
|
||||
Custom Headers (JSON)
|
||||
</h4>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={switchToFormMode}
|
||||
className="flex-shrink-0"
|
||||
>
|
||||
Switch to Form
|
||||
</Button>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Textarea
|
||||
value={jsonValue}
|
||||
onChange={(e) => handleJsonChange(e.target.value)}
|
||||
placeholder='{\n "Authorization": "Bearer token123",\n "X-Tenant-ID": "acme-inc",\n "X-Environment": "staging"\n}'
|
||||
className="font-mono text-sm min-h-[100px] resize-none"
|
||||
/>
|
||||
{jsonError && <p className="text-sm text-red-600">{jsonError}</p>}
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Enter headers as a JSON object with string key-value pairs.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={`space-y-3 ${className}`}>
|
||||
<div className="flex justify-between items-center gap-2">
|
||||
<h4 className="text-sm font-semibold flex-shrink-0">Custom Headers</h4>
|
||||
<div className="flex gap-1 flex-shrink-0">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={switchToJsonMode}
|
||||
className="text-xs px-2"
|
||||
>
|
||||
JSON
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={addHeader}
|
||||
className="text-xs px-2"
|
||||
data-testid="add-header-button"
|
||||
>
|
||||
<Plus className="w-3 h-3 mr-1" />
|
||||
Add
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{headers.length === 0 ? (
|
||||
<div className="text-center py-4 text-muted-foreground">
|
||||
<p className="text-sm">No custom headers configured</p>
|
||||
<p className="text-xs mt-1">Click "Add" to get started</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2 max-h-[300px] overflow-y-auto">
|
||||
{headers.map((header, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className="flex items-start gap-2 p-2 border rounded-md"
|
||||
>
|
||||
<Switch
|
||||
checked={header.enabled}
|
||||
onCheckedChange={(enabled) =>
|
||||
updateHeader(index, "enabled", enabled)
|
||||
}
|
||||
className="shrink-0 mt-2"
|
||||
/>
|
||||
<div className="flex-1 min-w-0 space-y-2">
|
||||
<Input
|
||||
placeholder="Header Name"
|
||||
value={header.name}
|
||||
onChange={(e) => updateHeader(index, "name", e.target.value)}
|
||||
className="font-mono text-xs"
|
||||
data-testid={`header-name-input-${index}`}
|
||||
/>
|
||||
<div className="relative">
|
||||
<Input
|
||||
placeholder="Header Value"
|
||||
value={header.value}
|
||||
onChange={(e) =>
|
||||
updateHeader(index, "value", e.target.value)
|
||||
}
|
||||
type={visibleValues.has(index) ? "text" : "password"}
|
||||
className="font-mono text-xs pr-8"
|
||||
data-testid={`header-value-input-${index}`}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => toggleValueVisibility(index)}
|
||||
className="absolute right-1 top-1/2 -translate-y-1/2 h-6 w-6 p-0"
|
||||
>
|
||||
{visibleValues.has(index) ? (
|
||||
<EyeOff className="w-3 h-3" />
|
||||
) : (
|
||||
<Eye className="w-3 h-3" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => removeHeader(index)}
|
||||
className="shrink-0 text-red-600 hover:text-red-700 hover:bg-red-50 h-6 w-6 p-0 mt-2"
|
||||
>
|
||||
<Trash2 className="w-3 h-3" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{headers.length > 0 && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Use the toggle to enable/disable headers. Only enabled headers with
|
||||
both name and value will be sent.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default CustomHeaders;
|
||||
|
|
@ -26,12 +26,22 @@ export interface DynamicJsonFormRef {
|
|||
validateJson: () => { isValid: boolean; error: string | null };
|
||||
}
|
||||
|
||||
const isTypeSupported = (
|
||||
type: JsonSchemaType["type"],
|
||||
supportedTypes: string[],
|
||||
): boolean => {
|
||||
if (Array.isArray(type)) {
|
||||
return type.every((t) => supportedTypes.includes(t));
|
||||
}
|
||||
return typeof type === "string" && supportedTypes.includes(type);
|
||||
};
|
||||
|
||||
const isSimpleObject = (schema: JsonSchemaType): boolean => {
|
||||
const supportedTypes = ["string", "number", "integer", "boolean", "null"];
|
||||
if (schema.type && supportedTypes.includes(schema.type)) return true;
|
||||
if (schema.type && isTypeSupported(schema.type, supportedTypes)) return true;
|
||||
if (schema.type === "object") {
|
||||
return Object.values(schema.properties ?? {}).every(
|
||||
(prop) => prop.type && supportedTypes.includes(prop.type),
|
||||
(prop) => prop.type && isTypeSupported(prop.type, supportedTypes),
|
||||
);
|
||||
}
|
||||
if (schema.type === "array") {
|
||||
|
|
@ -235,7 +245,13 @@ const DynamicJsonForm = forwardRef<DynamicJsonFormRef, DynamicJsonFormProps>(
|
|||
const isRequired =
|
||||
parentSchema?.required?.includes(propertyName || "") ?? false;
|
||||
|
||||
switch (propSchema.type) {
|
||||
let fieldType = propSchema.type;
|
||||
if (Array.isArray(fieldType)) {
|
||||
// Of the possible types, find the first non-null type to determine the control to render
|
||||
fieldType = fieldType.find((t) => t !== "null") ?? fieldType[0];
|
||||
}
|
||||
|
||||
switch (fieldType) {
|
||||
case "string": {
|
||||
if (
|
||||
propSchema.oneOf &&
|
||||
|
|
@ -391,6 +407,8 @@ const DynamicJsonForm = forwardRef<DynamicJsonFormRef, DynamicJsonFormProps>(
|
|||
required={isRequired}
|
||||
/>
|
||||
);
|
||||
case "null":
|
||||
return null;
|
||||
case "object":
|
||||
if (!propSchema.properties) {
|
||||
return (
|
||||
|
|
|
|||
|
|
@ -1,13 +1,18 @@
|
|||
import { ServerNotification } from "@modelcontextprotocol/sdk/types.js";
|
||||
import { useState } from "react";
|
||||
import JsonView from "./JsonView";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
const HistoryAndNotifications = ({
|
||||
requestHistory,
|
||||
serverNotifications,
|
||||
onClearHistory,
|
||||
onClearNotifications,
|
||||
}: {
|
||||
requestHistory: Array<{ request: string; response?: string }>;
|
||||
serverNotifications: ServerNotification[];
|
||||
onClearHistory?: () => void;
|
||||
onClearNotifications?: () => void;
|
||||
}) => {
|
||||
const [expandedRequests, setExpandedRequests] = useState<{
|
||||
[key: number]: boolean;
|
||||
|
|
@ -27,7 +32,17 @@ const HistoryAndNotifications = ({
|
|||
return (
|
||||
<div className="bg-card overflow-hidden flex h-full">
|
||||
<div className="flex-1 overflow-y-auto p-4 border-r">
|
||||
<h2 className="text-lg font-semibold mb-4">History</h2>
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h2 className="text-lg font-semibold">History</h2>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={onClearHistory}
|
||||
disabled={requestHistory.length === 0}
|
||||
>
|
||||
Clear
|
||||
</Button>
|
||||
</div>
|
||||
{requestHistory.length === 0 ? (
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400 italic">
|
||||
No history yet
|
||||
|
|
@ -93,7 +108,17 @@ const HistoryAndNotifications = ({
|
|||
)}
|
||||
</div>
|
||||
<div className="flex-1 overflow-y-auto p-4">
|
||||
<h2 className="text-lg font-semibold mb-4">Server Notifications</h2>
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h2 className="text-lg font-semibold">Server Notifications</h2>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={onClearNotifications}
|
||||
disabled={serverNotifications.length === 0}
|
||||
>
|
||||
Clear
|
||||
</Button>
|
||||
</div>
|
||||
{serverNotifications.length === 0 ? (
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400 italic">
|
||||
No notifications yet
|
||||
|
|
|
|||
|
|
@ -1,10 +1,11 @@
|
|||
import { useState, memo, useMemo, useCallback, useEffect } from "react";
|
||||
import { useState, memo, useMemo, useCallback } from "react";
|
||||
import type { JsonValue } from "@/utils/jsonUtils";
|
||||
import clsx from "clsx";
|
||||
import { Copy, CheckCheck } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useToast } from "@/lib/hooks/useToast";
|
||||
import { getDataType, tryParseJson } from "@/utils/jsonUtils";
|
||||
import useCopy from "@/lib/hooks/useCopy";
|
||||
|
||||
interface JsonViewProps {
|
||||
data: unknown;
|
||||
|
|
@ -25,21 +26,7 @@ const JsonView = memo(
|
|||
isError = false,
|
||||
}: JsonViewProps) => {
|
||||
const { toast } = useToast();
|
||||
const [copied, setCopied] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
let timeoutId: NodeJS.Timeout;
|
||||
if (copied) {
|
||||
timeoutId = setTimeout(() => {
|
||||
setCopied(false);
|
||||
}, 500);
|
||||
}
|
||||
return () => {
|
||||
if (timeoutId) {
|
||||
clearTimeout(timeoutId);
|
||||
}
|
||||
};
|
||||
}, [copied]);
|
||||
const { copied, setCopied } = useCopy();
|
||||
|
||||
const normalizedData = useMemo(() => {
|
||||
return typeof data === "string"
|
||||
|
|
|
|||
|
|
@ -1,4 +1,7 @@
|
|||
import { Search } from "lucide-react";
|
||||
import { Button } from "./ui/button";
|
||||
import { Input } from "./ui/input";
|
||||
import { useState, useMemo, useRef } from "react";
|
||||
|
||||
type ListPaneProps<T> = {
|
||||
items: T[];
|
||||
|
|
@ -20,41 +23,111 @@ const ListPane = <T extends object>({
|
|||
title,
|
||||
buttonText,
|
||||
isButtonDisabled,
|
||||
}: ListPaneProps<T>) => (
|
||||
<div className="bg-card border border-border rounded-lg shadow">
|
||||
<div className="p-4 border-b border-gray-200 dark:border-border">
|
||||
<h3 className="font-semibold dark:text-white">{title}</h3>
|
||||
</div>
|
||||
<div className="p-4">
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full mb-4"
|
||||
onClick={listItems}
|
||||
disabled={isButtonDisabled}
|
||||
>
|
||||
{buttonText}
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full mb-4"
|
||||
onClick={clearItems}
|
||||
disabled={items.length === 0}
|
||||
>
|
||||
Clear
|
||||
</Button>
|
||||
<div className="space-y-2 overflow-y-auto max-h-96">
|
||||
{items.map((item, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className="flex items-center py-2 px-4 rounded hover:bg-gray-50 dark:hover:bg-secondary cursor-pointer"
|
||||
onClick={() => setSelectedItem(item)}
|
||||
>
|
||||
{renderItem(item)}
|
||||
}: ListPaneProps<T>) => {
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
const [isSearchExpanded, setIsSearchExpanded] = useState(false);
|
||||
const searchInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const filteredItems = useMemo(() => {
|
||||
if (!searchQuery.trim()) return items;
|
||||
|
||||
return items.filter((item) => {
|
||||
const searchableText = [
|
||||
(item as { name?: string }).name || "",
|
||||
(item as { description?: string }).description || "",
|
||||
]
|
||||
.join(" ")
|
||||
.toLowerCase();
|
||||
return searchableText.includes(searchQuery.toLowerCase());
|
||||
});
|
||||
}, [items, searchQuery]);
|
||||
|
||||
const handleSearchClick = () => {
|
||||
setIsSearchExpanded(true);
|
||||
setTimeout(() => {
|
||||
searchInputRef.current?.focus();
|
||||
}, 100);
|
||||
};
|
||||
|
||||
const handleSearchBlur = () => {
|
||||
if (!searchQuery.trim()) {
|
||||
setIsSearchExpanded(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="bg-card border border-border rounded-lg shadow">
|
||||
<div className="p-4 border-b border-gray-200 dark:border-border">
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<h3 className="font-semibold dark:text-white flex-shrink-0">
|
||||
{title}
|
||||
</h3>
|
||||
<div className="flex items-center justify-end min-w-0 flex-1">
|
||||
{!isSearchExpanded ? (
|
||||
<button
|
||||
name="search"
|
||||
aria-label="Search"
|
||||
onClick={handleSearchClick}
|
||||
className="p-2 hover:bg-gray-100 dark:hover:bg-secondary rounded-md transition-all duration-300 ease-in-out"
|
||||
>
|
||||
<Search className="w-4 h-4 text-muted-foreground" />
|
||||
</button>
|
||||
) : (
|
||||
<div className="flex items-center w-full max-w-xs">
|
||||
<div className="relative w-full">
|
||||
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground pointer-events-none z-10" />
|
||||
<Input
|
||||
ref={searchInputRef}
|
||||
name="search"
|
||||
type="text"
|
||||
placeholder="Search..."
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
onBlur={handleSearchBlur}
|
||||
className="pl-10 w-full transition-all duration-300 ease-in-out"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="p-4">
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full mb-4"
|
||||
onClick={listItems}
|
||||
disabled={isButtonDisabled}
|
||||
>
|
||||
{buttonText}
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full mb-4"
|
||||
onClick={clearItems}
|
||||
disabled={items.length === 0}
|
||||
>
|
||||
Clear
|
||||
</Button>
|
||||
<div className="space-y-2 overflow-y-auto max-h-96">
|
||||
{filteredItems.map((item, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className="flex items-center py-2 px-4 rounded hover:bg-gray-50 dark:hover:bg-secondary cursor-pointer"
|
||||
onClick={() => setSelectedItem(item)}
|
||||
>
|
||||
{renderItem(item)}
|
||||
</div>
|
||||
))}
|
||||
{filteredItems.length === 0 && searchQuery && items.length > 0 && (
|
||||
<div className="text-center py-4 text-muted-foreground">
|
||||
No items found matching "{searchQuery}"
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
);
|
||||
};
|
||||
|
||||
export default ListPane;
|
||||
|
|
|
|||
|
|
@ -46,6 +46,17 @@ const OAuthDebugCallback = ({ onConnect }: OAuthCallbackProps) => {
|
|||
if (storedState) {
|
||||
try {
|
||||
restoredState = JSON.parse(storedState);
|
||||
if (restoredState && typeof restoredState.resource === "string") {
|
||||
restoredState.resource = new URL(restoredState.resource);
|
||||
}
|
||||
if (
|
||||
restoredState &&
|
||||
typeof restoredState.authorizationUrl === "string"
|
||||
) {
|
||||
restoredState.authorizationUrl = new URL(
|
||||
restoredState.authorizationUrl,
|
||||
);
|
||||
}
|
||||
// Clean up the stored state
|
||||
sessionStorage.removeItem(SESSION_KEYS.AUTH_DEBUGGER_STATE);
|
||||
} catch (e) {
|
||||
|
|
|
|||
|
|
@ -4,6 +4,8 @@ import { Button } from "./ui/button";
|
|||
import { DebugInspectorOAuthClientProvider } from "@/lib/auth";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { OAuthClientInformation } from "@modelcontextprotocol/sdk/shared/auth.js";
|
||||
import { validateRedirectUrl } from "@/utils/urlValidation";
|
||||
import { useToast } from "@/lib/hooks/useToast";
|
||||
|
||||
interface OAuthStepProps {
|
||||
label: string;
|
||||
|
|
@ -71,6 +73,7 @@ export const OAuthFlowProgress = ({
|
|||
updateAuthState,
|
||||
proceedToNextStep,
|
||||
}: OAuthFlowProgressProps) => {
|
||||
const { toast } = useToast();
|
||||
const provider = useMemo(
|
||||
() => new DebugInspectorOAuthClientProvider(serverUrl),
|
||||
[serverUrl],
|
||||
|
|
@ -237,18 +240,34 @@ export const OAuthFlowProgress = ({
|
|||
<p className="font-medium mb-2 text-sm">Authorization URL:</p>
|
||||
<div className="flex items-center gap-2">
|
||||
<p className="text-xs break-all">
|
||||
{authState.authorizationUrl}
|
||||
{String(authState.authorizationUrl)}
|
||||
</p>
|
||||
<a
|
||||
href={authState.authorizationUrl}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
<button
|
||||
onClick={() => {
|
||||
try {
|
||||
validateRedirectUrl(authState.authorizationUrl!);
|
||||
window.open(
|
||||
authState.authorizationUrl!,
|
||||
"_blank",
|
||||
"noopener noreferrer",
|
||||
);
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: "Invalid URL",
|
||||
description:
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: "The authorization URL is not valid",
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
}}
|
||||
className="flex items-center text-blue-500 hover:text-blue-700"
|
||||
aria-label="Open authorization URL in new tab"
|
||||
title="Open authorization URL"
|
||||
>
|
||||
<ExternalLink className="h-4 w-4" />
|
||||
</a>
|
||||
</button>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground mt-2">
|
||||
Click the link to authorize in your browser. After
|
||||
|
|
@ -354,7 +373,21 @@ export const OAuthFlowProgress = ({
|
|||
authState.authorizationUrl && (
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => window.open(authState.authorizationUrl!, "_blank")}
|
||||
onClick={() => {
|
||||
try {
|
||||
validateRedirectUrl(authState.authorizationUrl!);
|
||||
window.open(authState.authorizationUrl!, "_blank");
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: "Invalid URL",
|
||||
description:
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: "The authorization URL is not valid",
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
}}
|
||||
>
|
||||
Open in New Tab
|
||||
</Button>
|
||||
|
|
|
|||
|
|
@ -24,7 +24,6 @@ import {
|
|||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { StdErrNotification } from "@/lib/notificationTypes";
|
||||
import {
|
||||
LoggingLevel,
|
||||
LoggingLevelSchema,
|
||||
|
|
@ -38,6 +37,8 @@ import {
|
|||
TooltipTrigger,
|
||||
TooltipContent,
|
||||
} from "@/components/ui/tooltip";
|
||||
import CustomHeaders from "./CustomHeaders";
|
||||
import { CustomHeaders as CustomHeadersType } from "@/lib/types/customHeaders";
|
||||
import { useToast } from "../lib/hooks/useToast";
|
||||
|
||||
interface SidebarProps {
|
||||
|
|
@ -52,23 +53,22 @@ interface SidebarProps {
|
|||
setSseUrl: (url: string) => void;
|
||||
env: Record<string, string>;
|
||||
setEnv: (env: Record<string, string>) => void;
|
||||
bearerToken: string;
|
||||
setBearerToken: (token: string) => void;
|
||||
headerName?: string;
|
||||
setHeaderName?: (name: string) => void;
|
||||
// Custom headers support
|
||||
customHeaders: CustomHeadersType;
|
||||
setCustomHeaders: (headers: CustomHeadersType) => void;
|
||||
oauthClientId: string;
|
||||
setOauthClientId: (id: string) => void;
|
||||
oauthScope: string;
|
||||
setOauthScope: (scope: string) => void;
|
||||
onConnect: () => void;
|
||||
onDisconnect: () => void;
|
||||
stdErrNotifications: StdErrNotification[];
|
||||
clearStdErrNotifications: () => void;
|
||||
logLevel: LoggingLevel;
|
||||
sendLogLevelRequest: (level: LoggingLevel) => void;
|
||||
loggingSupported: boolean;
|
||||
config: InspectorConfig;
|
||||
setConfig: (config: InspectorConfig) => void;
|
||||
connectionType: "direct" | "proxy";
|
||||
setConnectionType: (type: "direct" | "proxy") => void;
|
||||
}
|
||||
|
||||
const Sidebar = ({
|
||||
|
|
@ -83,23 +83,21 @@ const Sidebar = ({
|
|||
setSseUrl,
|
||||
env,
|
||||
setEnv,
|
||||
bearerToken,
|
||||
setBearerToken,
|
||||
headerName,
|
||||
setHeaderName,
|
||||
customHeaders,
|
||||
setCustomHeaders,
|
||||
oauthClientId,
|
||||
setOauthClientId,
|
||||
oauthScope,
|
||||
setOauthScope,
|
||||
onConnect,
|
||||
onDisconnect,
|
||||
stdErrNotifications,
|
||||
clearStdErrNotifications,
|
||||
logLevel,
|
||||
sendLogLevelRequest,
|
||||
loggingSupported,
|
||||
config,
|
||||
setConfig,
|
||||
connectionType,
|
||||
setConnectionType,
|
||||
}: SidebarProps) => {
|
||||
const [theme, setTheme] = useTheme();
|
||||
const [showEnvVars, setShowEnvVars] = useState(false);
|
||||
|
|
@ -110,6 +108,8 @@ const Sidebar = ({
|
|||
const [copiedServerFile, setCopiedServerFile] = useState(false);
|
||||
const { toast } = useToast();
|
||||
|
||||
const connectionTypeTip =
|
||||
"Connect to server directly (requires CORS config on server) or via MCP Inspector Proxy";
|
||||
// Reusable error reporter for copy actions
|
||||
const reportError = useCallback(
|
||||
(error: unknown) => {
|
||||
|
|
@ -180,7 +180,9 @@ const Sidebar = ({
|
|||
description:
|
||||
transportType === "stdio"
|
||||
? "Server configuration has been copied to clipboard. Add this to your mcp.json inside the 'mcpServers' object with your preferred server name."
|
||||
: "SSE URL has been copied. Use this URL directly in your MCP Client.",
|
||||
: transportType === "streamable-http"
|
||||
? "Streamable HTTP URL has been copied. Use this URL directly in your MCP Client."
|
||||
: "SSE URL has been copied. Use this URL directly in your MCP Client.",
|
||||
});
|
||||
|
||||
setTimeout(() => {
|
||||
|
|
@ -268,6 +270,7 @@ const Sidebar = ({
|
|||
placeholder="Command"
|
||||
value={command}
|
||||
onChange={(e) => setCommand(e.target.value)}
|
||||
onBlur={(e) => setCommand(e.target.value.trim())}
|
||||
className="font-mono"
|
||||
/>
|
||||
</div>
|
||||
|
|
@ -316,6 +319,35 @@ const Sidebar = ({
|
|||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Connection Type switch - only visible for non-STDIO transport types */}
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<div className="space-y-2">
|
||||
<label
|
||||
className="text-sm font-medium"
|
||||
htmlFor="connection-type-select"
|
||||
>
|
||||
Connection Type
|
||||
</label>
|
||||
<Select
|
||||
value={connectionType}
|
||||
onValueChange={(value: "direct" | "proxy") =>
|
||||
setConnectionType(value)
|
||||
}
|
||||
>
|
||||
<SelectTrigger id="connection-type-select">
|
||||
<SelectValue placeholder="Select connection type" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="proxy">Via Proxy</SelectItem>
|
||||
<SelectItem value="direct">Direct</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{connectionTypeTip}</TooltipContent>
|
||||
</Tooltip>
|
||||
</>
|
||||
)}
|
||||
|
||||
|
|
@ -501,38 +533,12 @@ const Sidebar = ({
|
|||
</Button>
|
||||
{showAuthConfig && (
|
||||
<>
|
||||
{/* Bearer Token Section */}
|
||||
<div className="space-y-2 p-3 rounded border">
|
||||
<h4 className="text-sm font-semibold flex items-center">
|
||||
API Token Authentication
|
||||
</h4>
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium">Header Name</label>
|
||||
<Input
|
||||
placeholder="Authorization"
|
||||
onChange={(e) =>
|
||||
setHeaderName && setHeaderName(e.target.value)
|
||||
}
|
||||
data-testid="header-input"
|
||||
className="font-mono"
|
||||
value={headerName}
|
||||
/>
|
||||
<label
|
||||
className="text-sm font-medium"
|
||||
htmlFor="bearer-token-input"
|
||||
>
|
||||
Bearer Token
|
||||
</label>
|
||||
<Input
|
||||
id="bearer-token-input"
|
||||
placeholder="Bearer Token"
|
||||
value={bearerToken}
|
||||
onChange={(e) => setBearerToken(e.target.value)}
|
||||
data-testid="bearer-token-input"
|
||||
className="font-mono"
|
||||
type="password"
|
||||
/>
|
||||
</div>
|
||||
{/* Custom Headers Section */}
|
||||
<div className="p-3 rounded border overflow-hidden">
|
||||
<CustomHeaders
|
||||
headers={customHeaders}
|
||||
onChange={setCustomHeaders}
|
||||
/>
|
||||
</div>
|
||||
{transportType !== "stdio" && (
|
||||
// OAuth Configuration
|
||||
|
|
@ -760,36 +766,6 @@ const Sidebar = ({
|
|||
</Select>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{stdErrNotifications.length > 0 && (
|
||||
<>
|
||||
<div className="mt-4 border-t border-gray-200 pt-4">
|
||||
<div className="flex justify-between items-center">
|
||||
<h3 className="text-sm font-medium">
|
||||
Error output from MCP server
|
||||
</h3>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={clearStdErrNotifications}
|
||||
className="h-8 px-2"
|
||||
>
|
||||
Clear
|
||||
</Button>
|
||||
</div>
|
||||
<div className="mt-2 max-h-80 overflow-y-auto">
|
||||
{stdErrNotifications.map((notification, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className="text-sm text-red-500 font-mono py-2 border-b border-gray-200 last:border-b-0"
|
||||
>
|
||||
{notification.params.content}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -7,7 +7,11 @@ import { TabsContent } from "@/components/ui/tabs";
|
|||
import { Textarea } from "@/components/ui/textarea";
|
||||
import DynamicJsonForm, { DynamicJsonFormRef } from "./DynamicJsonForm";
|
||||
import type { JsonValue, JsonSchemaType } from "@/utils/jsonUtils";
|
||||
import { generateDefaultValue, isPropertyRequired } from "@/utils/schemaUtils";
|
||||
import {
|
||||
generateDefaultValue,
|
||||
isPropertyRequired,
|
||||
normalizeUnionType,
|
||||
} from "@/utils/schemaUtils";
|
||||
import {
|
||||
CompatibilityCallToolResult,
|
||||
ListToolsResult,
|
||||
|
|
@ -19,11 +23,15 @@ import {
|
|||
ChevronDown,
|
||||
ChevronUp,
|
||||
AlertCircle,
|
||||
Copy,
|
||||
CheckCheck,
|
||||
} from "lucide-react";
|
||||
import { useEffect, useState, useRef } from "react";
|
||||
import ListPane from "./ListPane";
|
||||
import JsonView from "./JsonView";
|
||||
import ToolResults from "./ToolResults";
|
||||
import { useToast } from "@/lib/hooks/useToast";
|
||||
import useCopy from "@/lib/hooks/useCopy";
|
||||
|
||||
// Type guard to safely detect the optional _meta field without using `any`
|
||||
const hasMeta = (tool: Tool): tool is Tool & { _meta: unknown } =>
|
||||
|
|
@ -59,6 +67,8 @@ const ToolsTab = ({
|
|||
const [isOutputSchemaExpanded, setIsOutputSchemaExpanded] = useState(false);
|
||||
const [isMetaExpanded, setIsMetaExpanded] = useState(false);
|
||||
const formRefs = useRef<Record<string, DynamicJsonFormRef | null>>({});
|
||||
const { toast } = useToast();
|
||||
const { copied, setCopied } = useCopy();
|
||||
|
||||
useEffect(() => {
|
||||
const params = Object.entries(
|
||||
|
|
@ -118,7 +128,7 @@ const ToolsTab = ({
|
|||
</p>
|
||||
{Object.entries(selectedTool.inputSchema.properties ?? []).map(
|
||||
([key, value]) => {
|
||||
const prop = value as JsonSchemaType;
|
||||
const prop = normalizeUnionType(value as JsonSchemaType);
|
||||
const inputSchema =
|
||||
selectedTool.inputSchema as JsonSchemaType;
|
||||
const required = isPropertyRequired(key, inputSchema);
|
||||
|
|
@ -162,7 +172,10 @@ const ToolsTab = ({
|
|||
onChange={(e) =>
|
||||
setParams({
|
||||
...params,
|
||||
[key]: e.target.value,
|
||||
[key]:
|
||||
e.target.value === ""
|
||||
? undefined
|
||||
: e.target.value,
|
||||
})
|
||||
}
|
||||
className="mt-1"
|
||||
|
|
@ -300,35 +313,60 @@ const ToolsTab = ({
|
|||
</div>
|
||||
</div>
|
||||
)}
|
||||
<Button
|
||||
onClick={async () => {
|
||||
// Validate JSON inputs before calling tool
|
||||
const hasValidationErrors = Object.values(
|
||||
formRefs.current,
|
||||
).some((ref) => ref && !ref.validateJson().isValid);
|
||||
if (hasValidationErrors) return;
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
onClick={async () => {
|
||||
// Validate JSON inputs before calling tool
|
||||
const hasValidationErrors = Object.values(
|
||||
formRefs.current,
|
||||
).some((ref) => ref && !ref.validateJson().isValid);
|
||||
if (hasValidationErrors) return;
|
||||
|
||||
try {
|
||||
setIsToolRunning(true);
|
||||
await callTool(selectedTool.name, params);
|
||||
} finally {
|
||||
setIsToolRunning(false);
|
||||
}
|
||||
}}
|
||||
disabled={isToolRunning}
|
||||
>
|
||||
{isToolRunning ? (
|
||||
<>
|
||||
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
|
||||
Running...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Send className="w-4 h-4 mr-2" />
|
||||
Run Tool
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
try {
|
||||
setIsToolRunning(true);
|
||||
await callTool(selectedTool.name, params);
|
||||
} finally {
|
||||
setIsToolRunning(false);
|
||||
}
|
||||
}}
|
||||
disabled={isToolRunning}
|
||||
>
|
||||
{isToolRunning ? (
|
||||
<>
|
||||
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
|
||||
Running...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Send className="w-4 h-4 mr-2" />
|
||||
Run Tool
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
<Button
|
||||
onClick={async () => {
|
||||
try {
|
||||
navigator.clipboard.writeText(
|
||||
JSON.stringify(params, null, 2),
|
||||
);
|
||||
setCopied(true);
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: "Error",
|
||||
description: `There was an error copying input to the clipboard: ${error instanceof Error ? error.message : String(error)}`,
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
}}
|
||||
>
|
||||
{copied ? (
|
||||
<CheckCheck className="h-4 w-4 mr-2 dark:text-green-700 text-green-600" />
|
||||
) : (
|
||||
<Copy className="h-4 w-4 mr-2" />
|
||||
)}
|
||||
Copy Input
|
||||
</Button>
|
||||
</div>
|
||||
<ToolResults
|
||||
toolResult={toolResult}
|
||||
selectedTool={selectedTool}
|
||||
|
|
|
|||
|
|
@ -25,6 +25,7 @@ const mockOAuthMetadata = {
|
|||
token_endpoint: "https://oauth.example.com/token",
|
||||
response_types_supported: ["code"],
|
||||
grant_types_supported: ["authorization_code"],
|
||||
scopes_supported: ["read", "write"],
|
||||
};
|
||||
|
||||
const mockOAuthClientInfo = {
|
||||
|
|
@ -36,7 +37,7 @@ const mockOAuthClientInfo = {
|
|||
// Mock MCP SDK functions - must be before imports
|
||||
jest.mock("@modelcontextprotocol/sdk/client/auth.js", () => ({
|
||||
auth: jest.fn(),
|
||||
discoverOAuthMetadata: jest.fn(),
|
||||
discoverAuthorizationServerMetadata: jest.fn(),
|
||||
registerClient: jest.fn(),
|
||||
startAuthorization: jest.fn(),
|
||||
exchangeAuthorization: jest.fn(),
|
||||
|
|
@ -46,7 +47,7 @@ jest.mock("@modelcontextprotocol/sdk/client/auth.js", () => ({
|
|||
|
||||
// Import the functions to get their types
|
||||
import {
|
||||
discoverOAuthMetadata,
|
||||
discoverAuthorizationServerMetadata,
|
||||
registerClient,
|
||||
startAuthorization,
|
||||
exchangeAuthorization,
|
||||
|
|
@ -56,10 +57,62 @@ import {
|
|||
import { OAuthMetadata } from "@modelcontextprotocol/sdk/shared/auth.js";
|
||||
import { EMPTY_DEBUGGER_STATE } from "@/lib/auth-types";
|
||||
|
||||
// Mock local auth module
|
||||
jest.mock("@/lib/auth", () => ({
|
||||
DebugInspectorOAuthClientProvider: jest.fn().mockImplementation(() => ({
|
||||
tokens: jest.fn().mockImplementation(() => Promise.resolve(undefined)),
|
||||
clear: jest.fn().mockImplementation(() => {
|
||||
// Mock the real clear() behavior which removes items from sessionStorage
|
||||
sessionStorage.removeItem("[https://example.com/mcp] mcp_tokens");
|
||||
sessionStorage.removeItem("[https://example.com/mcp] mcp_client_info");
|
||||
sessionStorage.removeItem(
|
||||
"[https://example.com/mcp] mcp_server_metadata",
|
||||
);
|
||||
}),
|
||||
redirectUrl: "http://localhost:3000/oauth/callback/debug",
|
||||
clientMetadata: {
|
||||
redirect_uris: ["http://localhost:3000/oauth/callback/debug"],
|
||||
token_endpoint_auth_method: "none",
|
||||
grant_types: ["authorization_code", "refresh_token"],
|
||||
response_types: ["code"],
|
||||
client_name: "MCP Inspector",
|
||||
},
|
||||
clientInformation: jest.fn().mockImplementation(async () => {
|
||||
const serverUrl = "https://example.com/mcp";
|
||||
const preregisteredKey = `[${serverUrl}] ${SESSION_KEYS.PREREGISTERED_CLIENT_INFORMATION}`;
|
||||
const preregisteredData = sessionStorage.getItem(preregisteredKey);
|
||||
if (preregisteredData) {
|
||||
return JSON.parse(preregisteredData);
|
||||
}
|
||||
const dynamicKey = `[${serverUrl}] ${SESSION_KEYS.CLIENT_INFORMATION}`;
|
||||
const dynamicData = sessionStorage.getItem(dynamicKey);
|
||||
if (dynamicData) {
|
||||
return JSON.parse(dynamicData);
|
||||
}
|
||||
return undefined;
|
||||
}),
|
||||
saveClientInformation: jest.fn().mockImplementation((clientInfo) => {
|
||||
const serverUrl = "https://example.com/mcp";
|
||||
const key = `[${serverUrl}] ${SESSION_KEYS.CLIENT_INFORMATION}`;
|
||||
sessionStorage.setItem(key, JSON.stringify(clientInfo));
|
||||
}),
|
||||
saveTokens: jest.fn(),
|
||||
redirectToAuthorization: jest.fn(),
|
||||
saveCodeVerifier: jest.fn(),
|
||||
codeVerifier: jest.fn(),
|
||||
saveServerMetadata: jest.fn(),
|
||||
getServerMetadata: jest.fn(),
|
||||
})),
|
||||
discoverScopes: jest.fn().mockResolvedValue("read write" as never),
|
||||
}));
|
||||
|
||||
import { discoverScopes } from "@/lib/auth";
|
||||
|
||||
// Type the mocked functions properly
|
||||
const mockDiscoverOAuthMetadata = discoverOAuthMetadata as jest.MockedFunction<
|
||||
typeof discoverOAuthMetadata
|
||||
>;
|
||||
const mockDiscoverAuthorizationServerMetadata =
|
||||
discoverAuthorizationServerMetadata as jest.MockedFunction<
|
||||
typeof discoverAuthorizationServerMetadata
|
||||
>;
|
||||
const mockRegisterClient = registerClient as jest.MockedFunction<
|
||||
typeof registerClient
|
||||
>;
|
||||
|
|
@ -74,6 +127,9 @@ const mockDiscoverOAuthProtectedResourceMetadata =
|
|||
discoverOAuthProtectedResourceMetadata as jest.MockedFunction<
|
||||
typeof discoverOAuthProtectedResourceMetadata
|
||||
>;
|
||||
const mockDiscoverScopes = discoverScopes as jest.MockedFunction<
|
||||
typeof discoverScopes
|
||||
>;
|
||||
|
||||
const sessionStorageMock = {
|
||||
getItem: jest.fn(),
|
||||
|
|
@ -102,7 +158,15 @@ describe("AuthDebugger", () => {
|
|||
// Suppress console errors in tests to avoid JSDOM navigation noise
|
||||
jest.spyOn(console, "error").mockImplementation(() => {});
|
||||
|
||||
mockDiscoverOAuthMetadata.mockResolvedValue(mockOAuthMetadata);
|
||||
// Set default mock behaviors with complete OAuth metadata
|
||||
mockDiscoverAuthorizationServerMetadata.mockResolvedValue({
|
||||
issuer: "https://oauth.example.com",
|
||||
authorization_endpoint: "https://oauth.example.com/authorize",
|
||||
token_endpoint: "https://oauth.example.com/token",
|
||||
response_types_supported: ["code"],
|
||||
grant_types_supported: ["authorization_code"],
|
||||
scopes_supported: ["read", "write"],
|
||||
});
|
||||
mockRegisterClient.mockResolvedValue(mockOAuthClientInfo);
|
||||
mockDiscoverOAuthProtectedResourceMetadata.mockRejectedValue(
|
||||
new Error("No protected resource metadata found"),
|
||||
|
|
@ -203,7 +267,7 @@ describe("AuthDebugger", () => {
|
|||
});
|
||||
|
||||
// Should first discover and save OAuth metadata
|
||||
expect(mockDiscoverOAuthMetadata).toHaveBeenCalledWith(
|
||||
expect(mockDiscoverAuthorizationServerMetadata).toHaveBeenCalledWith(
|
||||
new URL("https://example.com/"),
|
||||
);
|
||||
|
||||
|
|
@ -216,7 +280,7 @@ describe("AuthDebugger", () => {
|
|||
});
|
||||
|
||||
it("should show error when quick OAuth flow fails to discover metadata", async () => {
|
||||
mockDiscoverOAuthMetadata.mockRejectedValue(
|
||||
mockDiscoverAuthorizationServerMetadata.mockRejectedValue(
|
||||
new Error("Metadata discovery failed"),
|
||||
);
|
||||
|
||||
|
|
@ -362,7 +426,7 @@ describe("AuthDebugger", () => {
|
|||
fireEvent.click(screen.getByText("Continue"));
|
||||
});
|
||||
|
||||
expect(mockDiscoverOAuthMetadata).toHaveBeenCalledWith(
|
||||
expect(mockDiscoverAuthorizationServerMetadata).toHaveBeenCalledWith(
|
||||
new URL("https://example.com/"),
|
||||
);
|
||||
});
|
||||
|
|
@ -418,13 +482,34 @@ describe("AuthDebugger", () => {
|
|||
await waitFor(() => {
|
||||
expect(updateAuthState).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
authorizationUrl: expect.stringContaining("scope="),
|
||||
authorizationUrl: expect.objectContaining({
|
||||
href: "https://oauth.example.com/authorize?scope=read+write",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it("should not include scope in authorization URL when scopes_supported is not present", async () => {
|
||||
it("should include scope in authorization URL when scopes_supported is not present", async () => {
|
||||
const updateAuthState =
|
||||
await setupAuthorizationUrlTest(mockOAuthMetadata);
|
||||
|
||||
// Wait for the updateAuthState to be called
|
||||
await waitFor(() => {
|
||||
expect(updateAuthState).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
authorizationUrl: expect.objectContaining({
|
||||
href: "https://oauth.example.com/authorize?scope=read+write",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it("should omit scope from authorization URL when discoverScopes returns undefined", async () => {
|
||||
// Mock discoverScopes to return undefined (no scopes available)
|
||||
mockDiscoverScopes.mockResolvedValueOnce(undefined);
|
||||
|
||||
const updateAuthState =
|
||||
await setupAuthorizationUrlTest(mockOAuthMetadata);
|
||||
|
||||
|
|
@ -439,6 +524,103 @@ describe("AuthDebugger", () => {
|
|||
});
|
||||
});
|
||||
|
||||
describe("Client Registration behavior", () => {
|
||||
it("uses preregistered (static) client information without calling DCR", async () => {
|
||||
const preregClientInfo = {
|
||||
client_id: "static_client_id",
|
||||
client_secret: "static_client_secret",
|
||||
redirect_uris: ["http://localhost:3000/oauth/callback/debug"],
|
||||
};
|
||||
|
||||
// Return preregistered client info for the server-specific key
|
||||
sessionStorageMock.getItem.mockImplementation((key) => {
|
||||
if (
|
||||
key ===
|
||||
`[${defaultProps.serverUrl}] ${SESSION_KEYS.PREREGISTERED_CLIENT_INFORMATION}`
|
||||
) {
|
||||
return JSON.stringify(preregClientInfo);
|
||||
}
|
||||
return null;
|
||||
});
|
||||
|
||||
const updateAuthState = jest.fn();
|
||||
|
||||
await act(async () => {
|
||||
renderAuthDebugger({
|
||||
updateAuthState,
|
||||
authState: {
|
||||
...defaultAuthState,
|
||||
isInitiatingAuth: false,
|
||||
oauthStep: "client_registration",
|
||||
oauthMetadata: mockOAuthMetadata as unknown as OAuthMetadata,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
// Proceed from client_registration → authorization_redirect
|
||||
await act(async () => {
|
||||
fireEvent.click(screen.getByText("Continue"));
|
||||
});
|
||||
|
||||
// Should NOT attempt dynamic client registration
|
||||
expect(mockRegisterClient).not.toHaveBeenCalled();
|
||||
|
||||
// Should advance with the preregistered client info
|
||||
expect(updateAuthState).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
oauthClientInfo: expect.objectContaining({
|
||||
client_id: "static_client_id",
|
||||
}),
|
||||
oauthStep: "authorization_redirect",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("falls back to DCR when no static client information is available", async () => {
|
||||
// No preregistered or dynamic client info present in session storage
|
||||
sessionStorageMock.getItem.mockImplementation(() => null);
|
||||
|
||||
// DCR returns a new client
|
||||
mockRegisterClient.mockResolvedValueOnce(mockOAuthClientInfo);
|
||||
|
||||
const updateAuthState = jest.fn();
|
||||
|
||||
await act(async () => {
|
||||
renderAuthDebugger({
|
||||
updateAuthState,
|
||||
authState: {
|
||||
...defaultAuthState,
|
||||
isInitiatingAuth: false,
|
||||
oauthStep: "client_registration",
|
||||
oauthMetadata: mockOAuthMetadata as unknown as OAuthMetadata,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
fireEvent.click(screen.getByText("Continue"));
|
||||
});
|
||||
|
||||
expect(mockRegisterClient).toHaveBeenCalledTimes(1);
|
||||
|
||||
// Should save and advance with the DCR client info
|
||||
expect(updateAuthState).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
oauthClientInfo: expect.objectContaining({
|
||||
client_id: "test_client_id",
|
||||
}),
|
||||
oauthStep: "authorization_redirect",
|
||||
}),
|
||||
);
|
||||
|
||||
// Verify the dynamically registered client info was persisted
|
||||
expect(sessionStorage.setItem).toHaveBeenCalledWith(
|
||||
`[${defaultProps.serverUrl}] ${SESSION_KEYS.CLIENT_INFORMATION}`,
|
||||
expect.any(String),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("OAuth State Persistence", () => {
|
||||
it("should store auth state to sessionStorage before redirect in Quick OAuth Flow", async () => {
|
||||
const updateAuthState = jest.fn();
|
||||
|
|
@ -509,7 +691,9 @@ describe("AuthDebugger", () => {
|
|||
mockDiscoverOAuthProtectedResourceMetadata.mockResolvedValue(
|
||||
mockResourceMetadata,
|
||||
);
|
||||
mockDiscoverOAuthMetadata.mockResolvedValue(mockOAuthMetadata);
|
||||
mockDiscoverAuthorizationServerMetadata.mockResolvedValue(
|
||||
mockOAuthMetadata,
|
||||
);
|
||||
|
||||
await act(async () => {
|
||||
renderAuthDebugger({
|
||||
|
|
@ -563,7 +747,9 @@ describe("AuthDebugger", () => {
|
|||
// Mock failed metadata discovery
|
||||
mockDiscoverOAuthProtectedResourceMetadata.mockRejectedValue(mockError);
|
||||
// But OAuth metadata should still work with the original URL
|
||||
mockDiscoverOAuthMetadata.mockResolvedValue(mockOAuthMetadata);
|
||||
mockDiscoverAuthorizationServerMetadata.mockResolvedValue(
|
||||
mockOAuthMetadata,
|
||||
);
|
||||
|
||||
await act(async () => {
|
||||
renderAuthDebugger({
|
||||
|
|
@ -603,7 +789,7 @@ describe("AuthDebugger", () => {
|
|||
});
|
||||
|
||||
// Verify that regular OAuth metadata discovery was still called
|
||||
expect(mockDiscoverOAuthMetadata).toHaveBeenCalledWith(
|
||||
expect(mockDiscoverAuthorizationServerMetadata).toHaveBeenCalledWith(
|
||||
new URL("https://example.com/"),
|
||||
);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -36,6 +36,18 @@ describe("DynamicJsonForm String Fields", () => {
|
|||
const input = screen.getByRole("textbox");
|
||||
expect(input).toHaveProperty("type", "text");
|
||||
});
|
||||
|
||||
it("should handle a union type of string and null", () => {
|
||||
const schema: JsonSchemaType = {
|
||||
type: ["string", "null"],
|
||||
description: "Test string or null field",
|
||||
};
|
||||
render(
|
||||
<DynamicJsonForm schema={schema} value={null} onChange={jest.fn()} />,
|
||||
);
|
||||
const input = screen.getByRole("textbox");
|
||||
expect(input).toHaveProperty("type", "text");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Format Support", () => {
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import { render, screen, fireEvent } from "@testing-library/react";
|
||||
import { render, screen, fireEvent, within } from "@testing-library/react";
|
||||
import { useState } from "react";
|
||||
import { describe, it, expect, jest } from "@jest/globals";
|
||||
import HistoryAndNotifications from "../HistoryAndNotifications";
|
||||
import { ServerNotification } from "@modelcontextprotocol/sdk/types.js";
|
||||
|
|
@ -223,4 +224,66 @@ describe("HistoryAndNotifications", () => {
|
|||
expect(screen.getByText("No history yet")).toBeTruthy();
|
||||
expect(screen.getByText("No notifications yet")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("clears request history when Clear is clicked", () => {
|
||||
const Wrapper = () => {
|
||||
const [history, setHistory] = useState(mockRequestHistory);
|
||||
return (
|
||||
<HistoryAndNotifications
|
||||
requestHistory={history}
|
||||
serverNotifications={[]}
|
||||
onClearHistory={() => setHistory([])}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
render(<Wrapper />);
|
||||
|
||||
// Verify items are present initially
|
||||
expect(screen.getByText("2. test/method2")).toBeTruthy();
|
||||
expect(screen.getByText("1. test/method1")).toBeTruthy();
|
||||
|
||||
// Click Clear in History header (scoped by the History heading's container)
|
||||
const historyHeader = screen.getByText("History");
|
||||
const historyHeaderContainer = historyHeader.parentElement as HTMLElement;
|
||||
const historyClearButton = within(historyHeaderContainer).getByRole(
|
||||
"button",
|
||||
{ name: "Clear" },
|
||||
);
|
||||
fireEvent.click(historyClearButton);
|
||||
|
||||
// History should now be empty
|
||||
expect(screen.getByText("No history yet")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("clears server notifications when Clear is clicked", () => {
|
||||
const Wrapper = () => {
|
||||
const [notifications, setNotifications] =
|
||||
useState<ServerNotification[]>(mockNotifications);
|
||||
return (
|
||||
<HistoryAndNotifications
|
||||
requestHistory={[]}
|
||||
serverNotifications={notifications}
|
||||
onClearNotifications={() => setNotifications([])}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
render(<Wrapper />);
|
||||
|
||||
// Verify items are present initially
|
||||
expect(screen.getByText("2. notifications/progress")).toBeTruthy();
|
||||
expect(screen.getByText("1. notifications/message")).toBeTruthy();
|
||||
|
||||
// Click Clear in Server Notifications header (scoped by its heading's container)
|
||||
const notifHeader = screen.getByText("Server Notifications");
|
||||
const notifHeaderContainer = notifHeader.parentElement as HTMLElement;
|
||||
const notifClearButton = within(notifHeaderContainer).getByRole("button", {
|
||||
name: "Clear",
|
||||
});
|
||||
fireEvent.click(notifClearButton);
|
||||
|
||||
// Notifications should now be empty
|
||||
expect(screen.getByText("No notifications yet")).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
|
|
|||
203
client/src/components/__tests__/ListPane.test.tsx
Normal file
203
client/src/components/__tests__/ListPane.test.tsx
Normal file
|
|
@ -0,0 +1,203 @@
|
|||
import { render, screen, fireEvent, act } from "@testing-library/react";
|
||||
import "@testing-library/jest-dom";
|
||||
import { describe, it, beforeEach, jest } from "@jest/globals";
|
||||
import ListPane from "../ListPane";
|
||||
|
||||
describe("ListPane", () => {
|
||||
const mockItems = [
|
||||
{ id: 1, name: "Tool 1", description: "First tool" },
|
||||
{ id: 2, name: "Tool 2", description: "Second tool" },
|
||||
{ id: 3, name: "Another Tool", description: "Third tool" },
|
||||
];
|
||||
|
||||
const defaultProps = {
|
||||
items: mockItems,
|
||||
listItems: jest.fn(),
|
||||
clearItems: jest.fn(),
|
||||
setSelectedItem: jest.fn(),
|
||||
renderItem: (item: (typeof mockItems)[0]) => <div>{item.name}</div>,
|
||||
title: "List tools",
|
||||
buttonText: "Load Tools",
|
||||
};
|
||||
|
||||
const renderListPane = (props = {}) => {
|
||||
return render(<ListPane {...defaultProps} {...props} />);
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
describe("Rendering", () => {
|
||||
it("should render with title and button", () => {
|
||||
renderListPane();
|
||||
|
||||
expect(screen.getByText("List tools")).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByRole("button", { name: "Load Tools" }),
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: "Clear" })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("should render items when provided", () => {
|
||||
renderListPane();
|
||||
|
||||
expect(screen.getByText("Tool 1")).toBeInTheDocument();
|
||||
expect(screen.getByText("Tool 2")).toBeInTheDocument();
|
||||
expect(screen.getByText("Another Tool")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("should render empty state when no items", () => {
|
||||
renderListPane({ items: [] });
|
||||
|
||||
expect(screen.queryByText("Tool 1")).not.toBeInTheDocument();
|
||||
expect(screen.queryByText("Tool 2")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("should render custom item content", () => {
|
||||
const customRenderItem = (item: (typeof mockItems)[0]) => (
|
||||
<div>
|
||||
<span>{item.name}</span>
|
||||
<small>{item.description}</small>
|
||||
</div>
|
||||
);
|
||||
|
||||
renderListPane({ renderItem: customRenderItem });
|
||||
|
||||
expect(screen.getByText("Tool 1")).toBeInTheDocument();
|
||||
expect(screen.getByText("First tool")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Search Functionality", () => {
|
||||
it("should show search icon initially", () => {
|
||||
renderListPane();
|
||||
|
||||
const searchButton = screen.getByRole("button", { name: "Search" });
|
||||
expect(searchButton).toBeInTheDocument();
|
||||
expect(searchButton.querySelector("svg")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("should expand search input when search icon is clicked", async () => {
|
||||
renderListPane();
|
||||
|
||||
const searchButton = screen.getByRole("button", { name: "Search" });
|
||||
await act(async () => {
|
||||
fireEvent.click(searchButton);
|
||||
});
|
||||
|
||||
const searchInput = screen.getByPlaceholderText("Search...");
|
||||
expect(searchInput).toBeInTheDocument();
|
||||
|
||||
// Wait for the setTimeout to complete and focus to be set
|
||||
await act(async () => {
|
||||
await new Promise((resolve) => setTimeout(resolve, 150));
|
||||
});
|
||||
|
||||
expect(searchInput).toHaveFocus();
|
||||
});
|
||||
|
||||
it("should filter items based on search query", async () => {
|
||||
renderListPane();
|
||||
|
||||
const searchButton = screen.getByRole("button", { name: "Search" });
|
||||
await act(async () => {
|
||||
fireEvent.click(searchButton);
|
||||
});
|
||||
|
||||
const searchInput = screen.getByPlaceholderText("Search...");
|
||||
await act(async () => {
|
||||
fireEvent.change(searchInput, { target: { value: "Tool" } });
|
||||
});
|
||||
|
||||
expect(screen.getByText("Tool 1")).toBeInTheDocument();
|
||||
expect(screen.getByText("Tool 2")).toBeInTheDocument();
|
||||
expect(screen.getByText("Another Tool")).toBeInTheDocument();
|
||||
|
||||
await act(async () => {
|
||||
fireEvent.change(searchInput, { target: { value: "Another" } });
|
||||
});
|
||||
|
||||
expect(screen.queryByText("Tool 1")).not.toBeInTheDocument();
|
||||
expect(screen.queryByText("Tool 2")).not.toBeInTheDocument();
|
||||
expect(screen.getByText("Another Tool")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("should show 'No items found of matching \"NonExistent\"' when search has no results", async () => {
|
||||
renderListPane();
|
||||
|
||||
const searchButton = screen.getByRole("button", { name: "Search" });
|
||||
await act(async () => {
|
||||
fireEvent.click(searchButton);
|
||||
});
|
||||
|
||||
const searchInput = screen.getByPlaceholderText("Search...");
|
||||
|
||||
await act(async () => {
|
||||
fireEvent.change(searchInput, { target: { value: "NonExistent" } });
|
||||
});
|
||||
|
||||
expect(
|
||||
screen.getByText('No items found matching "NonExistent"'),
|
||||
).toBeInTheDocument();
|
||||
expect(screen.queryByText("Tool 1")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("should collapse search when input is empty and loses focus", async () => {
|
||||
renderListPane();
|
||||
|
||||
const searchButton = screen.getByRole("button", { name: "Search" });
|
||||
await act(async () => {
|
||||
fireEvent.click(searchButton);
|
||||
});
|
||||
|
||||
const searchInput = screen.getByPlaceholderText("Search...");
|
||||
|
||||
await act(async () => {
|
||||
fireEvent.change(searchInput, { target: { value: "test" } });
|
||||
fireEvent.change(searchInput, { target: { value: "" } });
|
||||
fireEvent.blur(searchInput);
|
||||
});
|
||||
|
||||
const searchButtonAfterCollapse = screen.getByRole("button", {
|
||||
name: "Search",
|
||||
});
|
||||
expect(searchButtonAfterCollapse).toBeInTheDocument();
|
||||
expect(searchButtonAfterCollapse).not.toHaveClass("opacity-0");
|
||||
});
|
||||
|
||||
it("should keep search expanded when input has content and loses focus", async () => {
|
||||
renderListPane();
|
||||
|
||||
const searchButton = screen.getByRole("button", { name: "Search" });
|
||||
await act(async () => {
|
||||
fireEvent.click(searchButton);
|
||||
});
|
||||
|
||||
const searchInput = screen.getByPlaceholderText("Search...");
|
||||
await act(async () => {
|
||||
fireEvent.change(searchInput, { target: { value: "test" } });
|
||||
fireEvent.blur(searchInput);
|
||||
});
|
||||
|
||||
expect(screen.getByPlaceholderText("Search...")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("should search through all item properties (description)", async () => {
|
||||
renderListPane();
|
||||
|
||||
const searchButton = screen.getByRole("button", { name: "Search" });
|
||||
await act(async () => {
|
||||
fireEvent.click(searchButton);
|
||||
});
|
||||
|
||||
const searchInput = screen.getByPlaceholderText("Search...");
|
||||
await act(async () => {
|
||||
fireEvent.change(searchInput, { target: { value: "First tool" } });
|
||||
});
|
||||
|
||||
expect(screen.getByText("Tool 1")).toBeInTheDocument();
|
||||
expect(screen.queryByText("Tool 2")).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large
Load diff
27
client/src/components/ui/switch.tsx
Normal file
27
client/src/components/ui/switch.tsx
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
import * as React from "react";
|
||||
import * as SwitchPrimitives from "@radix-ui/react-switch";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const Switch = React.forwardRef<
|
||||
React.ElementRef<typeof SwitchPrimitives.Root>,
|
||||
React.ComponentPropsWithoutRef<typeof SwitchPrimitives.Root>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<SwitchPrimitives.Root
|
||||
className={cn(
|
||||
"peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
ref={ref}
|
||||
>
|
||||
<SwitchPrimitives.Thumb
|
||||
className={cn(
|
||||
"pointer-events-none block h-4 w-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0",
|
||||
)}
|
||||
/>
|
||||
</SwitchPrimitives.Root>
|
||||
));
|
||||
Switch.displayName = SwitchPrimitives.Root.displayName;
|
||||
|
||||
export { Switch };
|
||||
Loading…
Reference in a new issue