File size: 2,358 Bytes
5193b92
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import { useState, useEffect, useCallback } from 'react';
import api from '../services/api-wrapper.ts';
import type { MCPTool } from '../types/index.ts';
import { API_ENDPOINTS } from '../constants/index.ts';
import { cacheMcpTools, getCachedMcpTools } from '../utils/cache.utils.ts';

type MCPToolsState = {
  tools: MCPTool[];
  loading: boolean;
  error: Error | null;
};

const INITIAL_STATE = {
  tools: [] as MCPTool[],
  loading: false,
  error: null,
} as MCPToolsState;

const isMCPTool = (value: unknown): value is MCPTool => {
  if (!value || typeof value !== 'object') {
    return false;
  }

  const candidate = value as { name?: unknown; description?: unknown };
  return typeof candidate.name === 'string' &&
    (candidate.description === undefined || typeof candidate.description === 'string');
};

const normalizeToolsResponse = (payload: unknown): MCPTool[] | null => {
  if (Array.isArray(payload)) {
    return payload.filter(isMCPTool);
  }

  if (payload && typeof payload === 'object') {
    const candidate = payload as { tools?: unknown; data?: unknown };
    if (Array.isArray(candidate.tools)) {
      return candidate.tools.filter(isMCPTool);
    }

    if (Array.isArray(candidate.data)) {
      return candidate.data.filter(isMCPTool);
    }
  }

  return null;
};

export const useMCPTools = () => {
  const [state, setState] = useState(INITIAL_STATE);

  const fetchTools = useCallback(async () => {
    try {
      const cachedTools = getCachedMcpTools();
      if (cachedTools && cachedTools.length > 0) {
        setState({ tools: cachedTools, loading: false, error: null });
      } else {
        setState((prev) => ({ ...prev, loading: true, error: null }));
      }

      const payload = await api.get<unknown>(API_ENDPOINTS.MCP_TOOLS);
      const parsedTools = normalizeToolsResponse(payload);

      if (!parsedTools) {
        throw new Error('Invalid MCP tools response shape');
      }

      setState({ tools: parsedTools, loading: false, error: null });
      cacheMcpTools(parsedTools);
    } catch (err) {
      setState({
        tools: getCachedMcpTools() ?? [],
        loading: false,
        error: err instanceof Error ? err : new Error('Failed to fetch MCP tools'),
      });
    }
  }, []);

  useEffect(() => {
    fetchTools();
  }, [fetchTools]);

  return { ...state, refetch: fetchTools };
};