refactor(completions): improve completion handling and error states

- Move completion logic from App.tsx to useConnection hook
- Replace useCompletion with simpler useCompletionState hook
- Add graceful fallback for servers without completion support
- Improve error handling and state management
- Update PromptsTab and ResourcesTab to use new completion API
- Add type safety improvements across completion interfaces
This commit is contained in:
Gavin Aboulhosn
2025-02-12 19:05:51 -05:00
parent c66feff37d
commit 7f713fe40e
6 changed files with 166 additions and 180 deletions

View File

@@ -0,0 +1,76 @@
import { useState, useCallback, useEffect } from "react";
import { ResourceReference, PromptReference } from "@modelcontextprotocol/sdk/types.js";
interface CompletionState {
completions: Record<string, string[]>;
loading: Record<string, boolean>;
error: Record<string, string | null>;
}
export function useCompletionState(
handleCompletion: (
ref: ResourceReference | PromptReference,
argName: string,
value: string,
) => Promise<string[]>,
completionsSupported: boolean = true,
) {
const [state, setState] = useState<CompletionState>({
completions: {},
loading: {},
error: {},
});
const clearCompletions = useCallback(() => {
setState({
completions: {},
loading: {},
error: {},
});
}, []);
const requestCompletions = useCallback(
async (ref: ResourceReference | PromptReference, argName: string, value: string) => {
if (!completionsSupported) {
return;
}
setState((prev) => ({
...prev,
loading: { ...prev.loading, [argName]: true },
error: { ...prev.error, [argName]: null },
}));
try {
const values = await handleCompletion(ref, argName, value);
setState((prev) => ({
...prev,
completions: { ...prev.completions, [argName]: values },
loading: { ...prev.loading, [argName]: false },
}));
} catch (err) {
const error = err instanceof Error ? err.message : String(err);
setState((prev) => ({
...prev,
loading: { ...prev.loading, [argName]: false },
error: { ...prev.error, [argName]: error },
}));
}
},
[handleCompletion, completionsSupported],
);
// Clear completions when support status changes
useEffect(() => {
if (!completionsSupported) {
clearCompletions();
}
}, [completionsSupported, clearCompletions]);
return {
...state,
clearCompletions,
requestCompletions,
completionsSupported,
};
}