File size: 5,614 Bytes
9b72f0d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
db78b1a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b72f0d
 
 
b2847f1
 
9b72f0d
 
 
 
b2847f1
 
9b72f0d
 
b2847f1
 
9b72f0d
 
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
// some helper functions for tool-calling based on the WebMCP API Proposal

type WebMCPProperty =
  | {
      type: "string";
      description: string;
      default?: string;
    }
  | {
      type: "number";
      description: string;
      default?: number;
    }
  | {
      type: "boolean";
      description: string;
      default?: boolean;
    };

export interface WebMCPTool {
  name: string;
  description: string;
  inputSchema: {
    type: "object";
    properties: Record<string, WebMCPProperty>;
    required: Array<string>;
  };
  execute: (args: Record<string, any>) => Promise<string>;
}

export interface ChatTemplateTool {
  name: string;
  description: string;
  parameters: Record<string, any>;
}

export const webMCPToolToChatTemplateTool = (
  webMCPTool: WebMCPTool
): ChatTemplateTool => ({
  name: webMCPTool.name,
  description: webMCPTool.description,
  parameters: webMCPTool.inputSchema,
});

export const validateWebMCPToolArguments = (
  tool: WebMCPTool,
  args: Record<string, any>
): Record<string, any> => {
  const expectedArguments = tool.inputSchema.properties;

  const validArguments = Object.entries(args).filter(([key, value]) => {
    const isValidKey = key in expectedArguments;
    const expectedType = expectedArguments[key]?.type;
    const actualType = typeof value;
    const isValidType = expectedType === actualType;

    return isValidKey && isValidType;
  });

  const returnArgs: Record<string, any> = validArguments.reduce((acc, curr) => {
    return { ...acc, [curr[0]]: curr[1] };
  }, {});

  if (tool.inputSchema.required.length !== 0) {
    const missingArguments = tool.inputSchema.required.filter(
      (argument) => !(argument in returnArgs)
    );

    if (missingArguments.length) {
      throw new Error(
        `Missing required arguments: ${missingArguments.join(", ")}`
      );
    }
  }

  return returnArgs;
};

export const executeWebMCPTool = async (
  tool: WebMCPTool,
  args: Record<string, any> | string | undefined
) => {
  // Handle case where args is a JSON string instead of an object
  let parsedArgs: Record<string, any> = {};

  if (typeof args === "string") {
    try {
      parsedArgs = JSON.parse(args);
    } catch (error) {
      parsedArgs = {};
    }
  } else if (args) {
    parsedArgs = args;
  }

  const validatedArgs = validateWebMCPToolArguments(tool, parsedArgs);
  return await tool.execute(validatedArgs);
};

export interface ToolCallPayload {
  name: string;
  arguments?: Record<string, any> | string;
  id: string;
}

export const extractToolCalls = (
  text: string
): { toolCalls: ToolCallPayload[]; message: string } => {
  const matches = Array.from(
    text.matchAll(/<tool_call>([\s\S]*?)<\/tool_call>/g)
  );
  const toolCalls: ToolCallPayload[] = [];

  for (const match of matches) {
    try {
      const parsed = JSON.parse(match[1].trim());
      if (parsed && typeof parsed.name === "string") {
        toolCalls.push({
          name: parsed.name,
          arguments: parsed.arguments ?? {},
          id: JSON.stringify({
            name: parsed.name,
            arguments: parsed.arguments ?? {},
          }),
        });
      }
    } catch {
      // ignore malformed tool call payloads
    }
  }

  // Remove both complete and incomplete tool calls
  // Complete: <tool_call>...</tool_call>
  // Incomplete: <tool_call>... (no closing tag yet)
  const message = text
    .replace(/<tool_call>[\s\S]*?(?:<\/tool_call>|$)/g, "")
    .trim();

  return { toolCalls, message };
};

export const splitResponse = (
  text: string
): Array<string | ToolCallPayload> => {
  const result: Array<string | ToolCallPayload> = [];
  let lastIndex = 0;

  // Match only complete tool calls (with closing tag)
  const regex = /<tool_call>([\s\S]*?)<\/tool_call>/g;
  let match: RegExpExecArray | null;

  while ((match = regex.exec(text)) !== null) {
    // Add text before the tool call
    const textBefore = text.slice(lastIndex, match.index);
    if (textBefore) {
      result.push(textBefore);
    }

    // Parse and add the tool call
    try {
      const parsed = JSON.parse(match[1].trim());
      if (parsed && typeof parsed.name === "string") {
        result.push({
          name: parsed.name,
          arguments: parsed.arguments ?? {},
          id: JSON.stringify({
            name: parsed.name,
            arguments: parsed.arguments ?? {},
          }),
        });
      }
    } catch {
      // ignore malformed tool call payloads
    }

    lastIndex = regex.lastIndex;
  }

  // Check if there's an incomplete tool call
  const incompleteToolCallIndex = text.indexOf("<tool_call>", lastIndex);

  if (incompleteToolCallIndex !== -1) {
    // There's an incomplete tool call, only add text up to it
    const textBefore = text.slice(lastIndex, incompleteToolCallIndex);
    if (textBefore) {
      result.push(textBefore);
    }
  } else {
    // No incomplete tool call, add remaining text
    const remainingText = text.slice(lastIndex);
    if (remainingText) {
      result.push(remainingText);
    }
  }

  return result;
};

export const executeToolCall = async (
  toolCall: ToolCallPayload,
  tools: Array<WebMCPTool>
): Promise<{ id: string; result: string; time: number }> => {
  const started = performance.now();
  const toolToUse = tools.find((t) => t.name === toolCall.name);
  if (!toolToUse)
    throw new Error(`Tool '${toolCall.name}' not found or is disabled.`);

  const result = await executeWebMCPTool(toolToUse, toolCall.arguments);
  const ended = performance.now();
  return {
    id: toolCall.id,
    result,
    time: ended - started,
  };
};