react-mcp-chatbot 0.0.5 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +31 -0
- package/LICENSE +21 -0
- package/README.md +199 -147
- package/dist/index.cjs +16175 -0
- package/dist/index.d.cts +275 -0
- package/dist/index.d.ts +250 -28
- package/dist/index.js +841 -462
- package/package.json +34 -14
- package/dist/send-2CSO66UQ.svg +0 -3
package/dist/index.js
CHANGED
|
@@ -1,128 +1,10 @@
|
|
|
1
1
|
// src/MCPAgent.tsx
|
|
2
|
-
import { useState, useRef, useEffect,
|
|
2
|
+
import { forwardRef, useState as useState2, useRef, useEffect as useEffect2, useImperativeHandle } from "react";
|
|
3
3
|
import ReactMarkdown from "react-markdown";
|
|
4
4
|
import remarkGfm from "remark-gfm";
|
|
5
5
|
|
|
6
|
-
// src/types.ts
|
|
7
|
-
var Agent = class {
|
|
8
|
-
tools;
|
|
9
|
-
model;
|
|
10
|
-
url;
|
|
11
|
-
constructor(model, url, tools = []) {
|
|
12
|
-
this.tools = tools;
|
|
13
|
-
this.url = url;
|
|
14
|
-
this.model = model;
|
|
15
|
-
}
|
|
16
|
-
};
|
|
17
|
-
|
|
18
|
-
// src/helpers/prompts.ts
|
|
19
|
-
var buildToolDecisionPrompt = (tools, message) => `
|
|
20
|
-
You are a tool-selection engine.
|
|
21
|
-
|
|
22
|
-
Your job is to decide whether a tool should be called and extract arguments.
|
|
23
|
-
|
|
24
|
-
Available tools:
|
|
25
|
-
${tools.map(
|
|
26
|
-
(t) => `
|
|
27
|
-
Tool name: ${t.name}
|
|
28
|
-
Description: ${t.description}
|
|
29
|
-
Parameters:
|
|
30
|
-
${Object.entries(t.parameters ?? {}).map(([k, v]) => {
|
|
31
|
-
const optional = typeof v.optional === "boolean" ? v.optional : true;
|
|
32
|
-
return `- ${k}: ${v.type}${optional ? " (optional)" : " (required)"}`;
|
|
33
|
-
}).join("\n")}
|
|
34
|
-
`
|
|
35
|
-
).join("\n")}
|
|
36
|
-
|
|
37
|
-
User request:
|
|
38
|
-
${message}
|
|
39
|
-
|
|
40
|
-
STRICT OUTPUT RULES:
|
|
41
|
-
- Respond with ONLY a single valid JSON object
|
|
42
|
-
- The object MUST have exactly two top-level properties:
|
|
43
|
-
- "tool": string | null
|
|
44
|
-
- "arguments": object
|
|
45
|
-
- Do NOT include any other keys
|
|
46
|
-
- Do NOT include explanations, comments, or markdown
|
|
47
|
-
- If no tool applies, return:
|
|
48
|
-
{ "tool": null, "arguments": {} }
|
|
49
|
-
- If a tool applies:
|
|
50
|
-
- "tool" must be the exact tool name
|
|
51
|
-
- "arguments" must include ONLY parameters required by the request
|
|
52
|
-
|
|
53
|
-
Return ONLY valid JSON.
|
|
54
|
-
`;
|
|
55
|
-
|
|
56
|
-
// src/agents/ollamaAgent.ts
|
|
57
|
-
var OllamaAgent = class extends Agent {
|
|
58
|
-
constructor(model = "llama3.2:latest", providerURL, tools = []) {
|
|
59
|
-
super(model, providerURL, tools);
|
|
60
|
-
}
|
|
61
|
-
async decideTool(message) {
|
|
62
|
-
if (this.tools.length === 0) return { tool: null };
|
|
63
|
-
console.log(this.url);
|
|
64
|
-
const res = await fetch(`${this.url}/api/generate`, {
|
|
65
|
-
method: "POST",
|
|
66
|
-
headers: { "Content-Type": "application/json" },
|
|
67
|
-
body: JSON.stringify({
|
|
68
|
-
model: this.model,
|
|
69
|
-
system: "You select tools and arguments. Output JSON only.",
|
|
70
|
-
prompt: buildToolDecisionPrompt(this.tools, message),
|
|
71
|
-
stream: false
|
|
72
|
-
})
|
|
73
|
-
});
|
|
74
|
-
const data = await res.json();
|
|
75
|
-
try {
|
|
76
|
-
return JSON.parse(data.response);
|
|
77
|
-
} catch {
|
|
78
|
-
return { tool: null };
|
|
79
|
-
}
|
|
80
|
-
}
|
|
81
|
-
async ask(message) {
|
|
82
|
-
let toolContext = "";
|
|
83
|
-
const decision = await this.decideTool(message);
|
|
84
|
-
if (decision.tool) {
|
|
85
|
-
const tool = this.tools.find((t) => t.name === decision.tool);
|
|
86
|
-
console.log(decision);
|
|
87
|
-
if (tool) {
|
|
88
|
-
const result = await tool.call(decision.arguments);
|
|
89
|
-
toolContext = `
|
|
90
|
-
Tool used: ${tool.name}
|
|
91
|
-
Result (partial):
|
|
92
|
-
\`\`\`json
|
|
93
|
-
${JSON.stringify(result, null, 2).slice(0, 4e3)}
|
|
94
|
-
\`\`\`
|
|
95
|
-
`;
|
|
96
|
-
}
|
|
97
|
-
}
|
|
98
|
-
const finalPrompt = `
|
|
99
|
-
User request:
|
|
100
|
-
${message}
|
|
101
|
-
|
|
102
|
-
${toolContext}
|
|
103
|
-
|
|
104
|
-
Respond in clean, well-formatted Markdown.
|
|
105
|
-
Use lists, tables, and headings where appropriate.
|
|
106
|
-
Do NOT mention tools or APIs explicitly.
|
|
107
|
-
`;
|
|
108
|
-
const res = await fetch(`${this.url}/api/generate`, {
|
|
109
|
-
method: "POST",
|
|
110
|
-
headers: { "Content-Type": "application/json" },
|
|
111
|
-
body: JSON.stringify({
|
|
112
|
-
model: this.model,
|
|
113
|
-
system: MARKDOWN_SYSTEM_PROMPT,
|
|
114
|
-
prompt: finalPrompt,
|
|
115
|
-
stream: false,
|
|
116
|
-
temperature: 0
|
|
117
|
-
})
|
|
118
|
-
});
|
|
119
|
-
const data = await res.json();
|
|
120
|
-
return data.response;
|
|
121
|
-
}
|
|
122
|
-
};
|
|
123
|
-
|
|
124
6
|
// src/assets/send.svg
|
|
125
|
-
var send_default = "
|
|
7
|
+
var send_default = 'data:image/svg+xml,<svg width="24px" height="24px" viewBox="0 0 32 32" id="icon" xmlns="http://www.w3.org/2000/svg">%0A <path fill="%23ffffff" d="M27.71,4.29a1,1,0,0,0-1.05-.23l-22,8a1,1,0,0,0,0,1.87l8.59,3.43L19.59,11,21,12.41l-6.37,6.37,3.44,8.59A1,1,0,0,0,19,28h0a1,1,0,0,0,.92-.66l8-22A1,1,0,0,0,27.71,4.29Z"/>%0A</svg>';
|
|
126
8
|
|
|
127
9
|
// src/components/TypingDots.tsx
|
|
128
10
|
import { jsx, jsxs } from "react/jsx-runtime";
|
|
@@ -199,304 +81,765 @@ function buildTokens(accent, dark) {
|
|
|
199
81
|
};
|
|
200
82
|
}
|
|
201
83
|
|
|
202
|
-
// src/
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
}
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
84
|
+
// src/useChat.ts
|
|
85
|
+
import { useCallback, useEffect, useMemo, useState, useSyncExternalStore } from "react";
|
|
86
|
+
|
|
87
|
+
// src/providers/http.ts
|
|
88
|
+
async function postJSON(url, headers, body, signal) {
|
|
89
|
+
const res = await fetch(url, {
|
|
90
|
+
method: "POST",
|
|
91
|
+
headers: { "Content-Type": "application/json", ...headers },
|
|
92
|
+
body: JSON.stringify(body),
|
|
93
|
+
signal
|
|
94
|
+
});
|
|
95
|
+
const text = await res.text();
|
|
96
|
+
let data;
|
|
97
|
+
try {
|
|
98
|
+
data = text ? JSON.parse(text) : {};
|
|
99
|
+
} catch {
|
|
100
|
+
data = { raw: text };
|
|
101
|
+
}
|
|
102
|
+
if (!res.ok) {
|
|
103
|
+
const msg = data?.error?.message ?? data?.error ?? data?.message ?? data?.raw ?? res.statusText;
|
|
104
|
+
throw new Error(`${res.status}: ${typeof msg === "string" ? msg : JSON.stringify(msg)}`);
|
|
105
|
+
}
|
|
106
|
+
return data;
|
|
107
|
+
}
|
|
108
|
+
function parseArgs(raw) {
|
|
109
|
+
if (raw && typeof raw === "object") return raw;
|
|
110
|
+
if (typeof raw !== "string" || !raw.trim()) return {};
|
|
111
|
+
try {
|
|
112
|
+
const v = JSON.parse(raw);
|
|
113
|
+
return v && typeof v === "object" ? v : {};
|
|
114
|
+
} catch {
|
|
115
|
+
return {};
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// src/providers/anthropic.ts
|
|
120
|
+
function toWire(messages) {
|
|
121
|
+
const out = [];
|
|
122
|
+
const push = (role, block) => {
|
|
123
|
+
const last = out[out.length - 1];
|
|
124
|
+
if (last && last.role === role) last.content.push(block);
|
|
125
|
+
else out.push({ role, content: [block] });
|
|
126
|
+
};
|
|
127
|
+
for (const m of messages) {
|
|
128
|
+
if (m.role === "user") push("user", { type: "text", text: m.content });
|
|
129
|
+
else if (m.role === "tool")
|
|
130
|
+
push("user", { type: "tool_result", tool_use_id: m.toolCallId, content: m.content });
|
|
131
|
+
else {
|
|
132
|
+
if (m.content) push("assistant", { type: "text", text: m.content });
|
|
133
|
+
for (const c of m.toolCalls ?? [])
|
|
134
|
+
push("assistant", { type: "tool_use", id: c.id, name: c.name, input: c.args });
|
|
238
135
|
}
|
|
239
136
|
}
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
137
|
+
return out;
|
|
138
|
+
}
|
|
139
|
+
var AnthropicProvider = class {
|
|
140
|
+
constructor(o) {
|
|
141
|
+
this.o = o;
|
|
142
|
+
}
|
|
143
|
+
async complete(req) {
|
|
144
|
+
const body = {
|
|
145
|
+
model: this.o.model,
|
|
146
|
+
max_tokens: 4096,
|
|
147
|
+
system: req.system || void 0,
|
|
148
|
+
messages: toWire(req.messages),
|
|
149
|
+
temperature: req.temperature ?? this.o.temperature ?? 0.2
|
|
150
|
+
};
|
|
151
|
+
if (req.tools.length) {
|
|
152
|
+
body.tools = req.tools.map((t) => ({
|
|
153
|
+
name: t.name,
|
|
154
|
+
description: t.description,
|
|
155
|
+
input_schema: t.parameters
|
|
156
|
+
}));
|
|
255
157
|
}
|
|
256
|
-
const
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
Do NOT mention tools or APIs explicitly.
|
|
265
|
-
Context rules:
|
|
266
|
-
- Respond ONLY using the information provided in the context.
|
|
267
|
-
- Do NOT generate or assume any information not present in the context.
|
|
268
|
-
- If the answer cannot be found in the context, respond exactly: "No relevant information was found."
|
|
269
|
-
`;
|
|
270
|
-
const res = await fetch(`${this.url}/chat/completions`, {
|
|
271
|
-
method: "POST",
|
|
272
|
-
headers: {
|
|
273
|
-
"Content-Type": "application/json",
|
|
274
|
-
Authorization: `Bearer ${this.apiKey}`
|
|
158
|
+
const data = await postJSON(
|
|
159
|
+
`${this.o.baseURL.replace(/\/+$/, "")}/v1/messages`,
|
|
160
|
+
{
|
|
161
|
+
"x-api-key": this.o.apiKey ?? "",
|
|
162
|
+
"anthropic-version": "2023-06-01",
|
|
163
|
+
// Required by Anthropic for calls made straight from a browser.
|
|
164
|
+
"anthropic-dangerous-direct-browser-access": "true",
|
|
165
|
+
...this.o.headers
|
|
275
166
|
},
|
|
276
|
-
body
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
});
|
|
285
|
-
const data = await res.json();
|
|
286
|
-
return data.choices?.[0]?.message?.content ?? "";
|
|
167
|
+
body,
|
|
168
|
+
req.signal
|
|
169
|
+
);
|
|
170
|
+
const blocks = data.content ?? [];
|
|
171
|
+
return {
|
|
172
|
+
content: blocks.filter((b) => b.type === "text").map((b) => b.text).join(""),
|
|
173
|
+
toolCalls: blocks.filter((b) => b.type === "tool_use").map((b) => ({ id: b.id, name: b.name, args: b.input ?? {} }))
|
|
174
|
+
};
|
|
287
175
|
}
|
|
288
176
|
};
|
|
289
177
|
|
|
290
|
-
// src/
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
{
|
|
310
|
-
role: "system",
|
|
311
|
-
content: "You select tools and arguments. Respond ONLY with valid JSON."
|
|
312
|
-
},
|
|
313
|
-
{
|
|
314
|
-
role: "user",
|
|
315
|
-
content: buildToolDecisionPrompt(this.tools, message)
|
|
316
|
-
}
|
|
317
|
-
]
|
|
318
|
-
})
|
|
319
|
-
});
|
|
320
|
-
const data = await res.json();
|
|
321
|
-
const content = data.choices?.[0]?.message?.content;
|
|
322
|
-
try {
|
|
323
|
-
return JSON.parse(content);
|
|
324
|
-
} catch {
|
|
325
|
-
return { tool: null };
|
|
178
|
+
// src/providers/gemini.ts
|
|
179
|
+
function toWire2(messages) {
|
|
180
|
+
const out = [];
|
|
181
|
+
const push = (role, part) => {
|
|
182
|
+
const last = out[out.length - 1];
|
|
183
|
+
if (last && last.role === role) last.parts.push(part);
|
|
184
|
+
else out.push({ role, parts: [part] });
|
|
185
|
+
};
|
|
186
|
+
for (const m of messages) {
|
|
187
|
+
if (m.role === "user") push("user", { text: m.content });
|
|
188
|
+
else if (m.role === "tool")
|
|
189
|
+
push("user", {
|
|
190
|
+
functionResponse: { name: m.name, response: { result: tryParse(m.content) } }
|
|
191
|
+
});
|
|
192
|
+
else {
|
|
193
|
+
if (m.content) push("model", { text: m.content });
|
|
194
|
+
for (const c of m.toolCalls ?? []) {
|
|
195
|
+
push("model", c.raw ?? { functionCall: { name: c.name, args: c.args } });
|
|
196
|
+
}
|
|
326
197
|
}
|
|
327
198
|
}
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
199
|
+
return out;
|
|
200
|
+
}
|
|
201
|
+
function tryParse(s) {
|
|
202
|
+
try {
|
|
203
|
+
const v = JSON.parse(s);
|
|
204
|
+
return v;
|
|
205
|
+
} catch {
|
|
206
|
+
return s;
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
function cleanSchema(s) {
|
|
210
|
+
if (Array.isArray(s)) return s.map(cleanSchema);
|
|
211
|
+
if (!s || typeof s !== "object") return s;
|
|
212
|
+
const allowed = ["type", "description", "enum", "items", "properties", "required", "format", "nullable"];
|
|
213
|
+
const out = {};
|
|
214
|
+
for (const [k, v] of Object.entries(s)) {
|
|
215
|
+
if (!allowed.includes(k)) continue;
|
|
216
|
+
out[k] = k === "properties" ? Object.fromEntries(Object.entries(v).map(([pk, pv]) => [pk, cleanSchema(pv)])) : cleanSchema(v);
|
|
217
|
+
}
|
|
218
|
+
return out;
|
|
219
|
+
}
|
|
220
|
+
var GeminiProvider = class {
|
|
221
|
+
constructor(o) {
|
|
222
|
+
this.o = o;
|
|
223
|
+
}
|
|
224
|
+
async complete(req) {
|
|
225
|
+
const model = this.o.model.startsWith("models/") ? this.o.model : `models/${this.o.model}`;
|
|
226
|
+
const body = {
|
|
227
|
+
contents: toWire2(req.messages),
|
|
228
|
+
generationConfig: { temperature: req.temperature ?? this.o.temperature ?? 0.2 }
|
|
229
|
+
};
|
|
230
|
+
if (req.system) body.systemInstruction = { parts: [{ text: req.system }] };
|
|
231
|
+
if (req.tools.length) {
|
|
232
|
+
body.tools = [
|
|
233
|
+
{
|
|
234
|
+
functionDeclarations: req.tools.map((t) => ({
|
|
235
|
+
name: t.name,
|
|
236
|
+
description: t.description,
|
|
237
|
+
// Gemini errors on an empty `properties` object.
|
|
238
|
+
...Object.keys(t.parameters.properties).length ? {
|
|
239
|
+
parameters: cleanSchema({
|
|
240
|
+
...t.parameters,
|
|
241
|
+
required: t.parameters.required.length ? t.parameters.required : void 0
|
|
242
|
+
})
|
|
243
|
+
} : {}
|
|
244
|
+
}))
|
|
245
|
+
}
|
|
246
|
+
];
|
|
343
247
|
}
|
|
344
|
-
const
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
}
|
|
364
|
-
|
|
365
|
-
model: this.model,
|
|
366
|
-
temperature: 0,
|
|
367
|
-
messages: [
|
|
368
|
-
{ role: "system", content: MARKDOWN_SYSTEM_PROMPT },
|
|
369
|
-
{ role: "user", content: finalPrompt }
|
|
370
|
-
]
|
|
371
|
-
})
|
|
372
|
-
});
|
|
373
|
-
const data = await res.json();
|
|
374
|
-
return data.choices?.[0]?.message?.content ?? "";
|
|
248
|
+
const data = await postJSON(
|
|
249
|
+
`${this.o.baseURL.replace(/\/+$/, "")}/${model}:generateContent`,
|
|
250
|
+
{ "x-goog-api-key": this.o.apiKey ?? "", ...this.o.headers },
|
|
251
|
+
body,
|
|
252
|
+
req.signal
|
|
253
|
+
);
|
|
254
|
+
const cand = data.candidates?.[0];
|
|
255
|
+
if (!cand) {
|
|
256
|
+
throw new Error(data.promptFeedback?.blockReason ? `Blocked by Gemini: ${data.promptFeedback.blockReason}` : "Provider returned no candidates.");
|
|
257
|
+
}
|
|
258
|
+
const parts = cand.content?.parts ?? [];
|
|
259
|
+
return {
|
|
260
|
+
// skip "thought" summary parts
|
|
261
|
+
content: parts.filter((p) => typeof p.text === "string" && !p.thought).map((p) => p.text).join(""),
|
|
262
|
+
toolCalls: parts.filter((p) => p.functionCall).map((p, i) => ({
|
|
263
|
+
id: `call_${i}_${Date.now()}`,
|
|
264
|
+
name: p.functionCall.name,
|
|
265
|
+
args: p.functionCall.args ?? {},
|
|
266
|
+
raw: p
|
|
267
|
+
}))
|
|
268
|
+
};
|
|
375
269
|
}
|
|
376
270
|
};
|
|
377
271
|
|
|
378
|
-
// src/
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
}
|
|
394
|
-
body: JSON.stringify({
|
|
395
|
-
contents: [
|
|
396
|
-
{
|
|
397
|
-
role: "user",
|
|
398
|
-
parts: [
|
|
399
|
-
{
|
|
400
|
-
text: "You select tools and arguments. Respond ONLY with valid JSON.\n\n" + buildToolDecisionPrompt(this.tools, message)
|
|
401
|
-
}
|
|
402
|
-
]
|
|
403
|
-
}
|
|
404
|
-
],
|
|
405
|
-
generationConfig: {
|
|
406
|
-
temperature: 0
|
|
407
|
-
}
|
|
408
|
-
})
|
|
272
|
+
// src/providers/openaiCompatible.ts
|
|
273
|
+
function toWire3(system, messages) {
|
|
274
|
+
const out = [];
|
|
275
|
+
if (system) out.push({ role: "system", content: system });
|
|
276
|
+
for (const m of messages) {
|
|
277
|
+
if (m.role === "user") out.push({ role: "user", content: m.content });
|
|
278
|
+
else if (m.role === "tool")
|
|
279
|
+
out.push({ role: "tool", tool_call_id: m.toolCallId, content: m.content });
|
|
280
|
+
else {
|
|
281
|
+
const msg = { role: "assistant", content: m.content || null };
|
|
282
|
+
if (m.toolCalls?.length) {
|
|
283
|
+
msg.tool_calls = m.toolCalls.map((c) => ({
|
|
284
|
+
id: c.id,
|
|
285
|
+
type: "function",
|
|
286
|
+
function: { name: c.name, arguments: JSON.stringify(c.args) }
|
|
287
|
+
}));
|
|
409
288
|
}
|
|
289
|
+
out.push(msg);
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
return out;
|
|
293
|
+
}
|
|
294
|
+
var OpenAICompatibleProvider = class {
|
|
295
|
+
constructor(o) {
|
|
296
|
+
this.o = o;
|
|
297
|
+
}
|
|
298
|
+
async complete(req) {
|
|
299
|
+
const body = {
|
|
300
|
+
model: this.o.model,
|
|
301
|
+
messages: toWire3(req.system, req.messages),
|
|
302
|
+
temperature: req.temperature ?? this.o.temperature ?? 0.2
|
|
303
|
+
};
|
|
304
|
+
if (req.tools.length) {
|
|
305
|
+
body.tools = req.tools.map((t) => ({
|
|
306
|
+
type: "function",
|
|
307
|
+
function: { name: t.name, description: t.description, parameters: t.parameters }
|
|
308
|
+
}));
|
|
309
|
+
}
|
|
310
|
+
const headers = { ...this.o.headers };
|
|
311
|
+
if (this.o.apiKey) headers.Authorization = `Bearer ${this.o.apiKey}`;
|
|
312
|
+
const data = await postJSON(
|
|
313
|
+
`${this.o.baseURL.replace(/\/+$/, "")}/chat/completions`,
|
|
314
|
+
headers,
|
|
315
|
+
body,
|
|
316
|
+
req.signal
|
|
410
317
|
);
|
|
411
|
-
const
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
318
|
+
const msg = data.choices?.[0]?.message;
|
|
319
|
+
if (!msg) throw new Error("Provider returned no message.");
|
|
320
|
+
return {
|
|
321
|
+
content: msg.content ?? "",
|
|
322
|
+
toolCalls: (msg.tool_calls ?? []).map((c, i) => ({
|
|
323
|
+
id: c.id ?? `call_${i}_${Date.now()}`,
|
|
324
|
+
name: c.function?.name,
|
|
325
|
+
args: parseArgs(c.function?.arguments)
|
|
326
|
+
}))
|
|
327
|
+
};
|
|
328
|
+
}
|
|
329
|
+
};
|
|
330
|
+
|
|
331
|
+
// src/providers/index.ts
|
|
332
|
+
var PROVIDER_URLS = {
|
|
333
|
+
openai: "https://api.openai.com/v1",
|
|
334
|
+
anthropic: "https://api.anthropic.com",
|
|
335
|
+
gemini: "https://generativelanguage.googleapis.com/v1beta",
|
|
336
|
+
deepseek: "https://api.deepseek.com/v1",
|
|
337
|
+
groq: "https://api.groq.com/openai/v1",
|
|
338
|
+
openrouter: "https://openrouter.ai/api/v1",
|
|
339
|
+
mistral: "https://api.mistral.ai/v1",
|
|
340
|
+
xai: "https://api.x.ai/v1",
|
|
341
|
+
together: "https://api.together.xyz/v1"
|
|
342
|
+
};
|
|
343
|
+
function createProvider(cfg) {
|
|
344
|
+
const { provider, model, apiKey, temperature, headers } = cfg;
|
|
345
|
+
const common = { model, apiKey, temperature, headers };
|
|
346
|
+
switch (provider) {
|
|
347
|
+
case "ollama": {
|
|
348
|
+
const root = (cfg.providerURL ?? "http://localhost:11434").replace(/\/+$/, "");
|
|
349
|
+
return new OpenAICompatibleProvider({ ...common, baseURL: root.endsWith("/v1") ? root : `${root}/v1` });
|
|
350
|
+
}
|
|
351
|
+
case "openai-compatible":
|
|
352
|
+
if (!cfg.providerURL) throw new Error('provider "openai-compatible" requires providerURL.');
|
|
353
|
+
return new OpenAICompatibleProvider({ ...common, baseURL: cfg.providerURL });
|
|
354
|
+
case "anthropic":
|
|
355
|
+
return new AnthropicProvider({ ...common, baseURL: cfg.providerURL ?? PROVIDER_URLS.anthropic });
|
|
356
|
+
case "gemini":
|
|
357
|
+
return new GeminiProvider({ ...common, baseURL: cfg.providerURL ?? PROVIDER_URLS.gemini });
|
|
358
|
+
default: {
|
|
359
|
+
const baseURL = cfg.providerURL ?? PROVIDER_URLS[provider];
|
|
360
|
+
if (!baseURL) throw new Error(`Unknown provider "${provider}".`);
|
|
361
|
+
return new OpenAICompatibleProvider({ ...common, baseURL });
|
|
417
362
|
}
|
|
418
363
|
}
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
// src/core/tools.ts
|
|
367
|
+
function toToolSpec(tool) {
|
|
368
|
+
const properties = {};
|
|
369
|
+
const required = [];
|
|
370
|
+
for (const [key, p] of Object.entries(tool.parameters ?? {})) {
|
|
371
|
+
const prop = { type: p.type };
|
|
372
|
+
if (p.description) prop.description = p.description;
|
|
373
|
+
if (p.enum) prop.enum = p.enum;
|
|
374
|
+
if (p.type === "array") prop.items = p.items ?? {};
|
|
375
|
+
if (p.type === "object" && p.properties) prop.properties = p.properties;
|
|
376
|
+
properties[key] = prop;
|
|
377
|
+
if (!p.optional) required.push(key);
|
|
378
|
+
}
|
|
379
|
+
return {
|
|
380
|
+
name: tool.name,
|
|
381
|
+
description: tool.description,
|
|
382
|
+
parameters: { type: "object", properties, required }
|
|
383
|
+
};
|
|
384
|
+
}
|
|
385
|
+
function prepareArgs(tool, raw) {
|
|
386
|
+
const args = { ...raw };
|
|
387
|
+
const params = tool.parameters ?? {};
|
|
388
|
+
for (const [key, p] of Object.entries(params)) {
|
|
389
|
+
let v = args[key];
|
|
390
|
+
if (v === void 0 || v === null || v === "") {
|
|
391
|
+
if (!p.optional) return { error: `Missing required argument "${key}".` };
|
|
392
|
+
delete args[key];
|
|
393
|
+
continue;
|
|
394
|
+
}
|
|
395
|
+
if ((p.type === "number" || p.type === "integer") && typeof v === "string") {
|
|
396
|
+
const n = Number(v);
|
|
397
|
+
if (Number.isNaN(n)) return { error: `Argument "${key}" must be a number.` };
|
|
398
|
+
v = n;
|
|
399
|
+
}
|
|
400
|
+
if (p.type === "boolean" && typeof v === "string") v = v === "true";
|
|
401
|
+
if ((p.type === "object" || p.type === "array") && typeof v === "string") {
|
|
402
|
+
try {
|
|
403
|
+
v = JSON.parse(v);
|
|
404
|
+
} catch {
|
|
405
|
+
return { error: `Argument "${key}" must be valid JSON.` };
|
|
433
406
|
}
|
|
434
407
|
}
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
408
|
+
args[key] = v;
|
|
409
|
+
}
|
|
410
|
+
return { args };
|
|
411
|
+
}
|
|
412
|
+
function defaultLocation(method, path, name) {
|
|
413
|
+
if (path.includes(`{${name}}`)) return "path";
|
|
414
|
+
return method === "GET" || method === "DELETE" ? "query" : "body";
|
|
415
|
+
}
|
|
416
|
+
async function resolveHeaders(h) {
|
|
417
|
+
if (!h) return {};
|
|
418
|
+
return typeof h === "function" ? await h() : h;
|
|
419
|
+
}
|
|
420
|
+
function appendQuery(search, key, v) {
|
|
421
|
+
if (Array.isArray(v)) v.forEach((i) => appendQuery(search, key, i));
|
|
422
|
+
else if (v !== null && typeof v === "object") search.append(key, JSON.stringify(v));
|
|
423
|
+
else search.append(key, String(v));
|
|
424
|
+
}
|
|
425
|
+
function endpointToTool(getApi, ep) {
|
|
426
|
+
const method = ep.method ?? "GET";
|
|
427
|
+
const parameters = {};
|
|
428
|
+
for (const [k, p] of Object.entries(ep.parameters ?? {})) {
|
|
429
|
+
const { in: _in, ...rest } = p;
|
|
430
|
+
parameters[k] = rest;
|
|
431
|
+
}
|
|
432
|
+
return {
|
|
433
|
+
name: ep.name,
|
|
434
|
+
description: `${ep.description}${ep.description.endsWith(".") ? "" : "."} (${method} ${ep.path})`,
|
|
435
|
+
parameters,
|
|
436
|
+
method,
|
|
437
|
+
async call(args) {
|
|
438
|
+
const api = getApi();
|
|
439
|
+
const maxChars = api.maxResponseChars ?? 8e3;
|
|
440
|
+
let path = ep.path;
|
|
441
|
+
const search = new URLSearchParams();
|
|
442
|
+
const body = {};
|
|
443
|
+
const headers = {
|
|
444
|
+
Accept: "application/json",
|
|
445
|
+
...await resolveHeaders(api.headers),
|
|
446
|
+
...ep.headers
|
|
447
|
+
};
|
|
448
|
+
for (const [k, v] of Object.entries(args)) {
|
|
449
|
+
const where = ep.parameters?.[k]?.in ?? defaultLocation(method, ep.path, k);
|
|
450
|
+
if (where === "path") path = path.replace(`{${k}}`, encodeURIComponent(String(v)));
|
|
451
|
+
else if (where === "query") appendQuery(search, k, v);
|
|
452
|
+
else if (where === "header") headers[k] = String(v);
|
|
453
|
+
else body[k] = v;
|
|
454
|
+
}
|
|
455
|
+
const base = api.baseURL.replace(/\/+$/, "");
|
|
456
|
+
const qs = search.toString();
|
|
457
|
+
const url = `${base}${path.startsWith("/") ? "" : "/"}${path}${qs ? (path.includes("?") ? "&" : "?") + qs : ""}`;
|
|
458
|
+
const hasBody = Object.keys(body).length > 0 && method !== "GET";
|
|
459
|
+
if (hasBody) headers["Content-Type"] ??= "application/json";
|
|
460
|
+
const res = await fetch(url, {
|
|
461
|
+
method,
|
|
462
|
+
headers,
|
|
463
|
+
credentials: api.credentials,
|
|
464
|
+
body: hasBody ? JSON.stringify(body) : void 0
|
|
465
|
+
});
|
|
466
|
+
const text = await res.text();
|
|
467
|
+
if (!res.ok) {
|
|
468
|
+
throw new Error(`HTTP ${res.status} ${res.statusText}: ${text.slice(0, 500)}`);
|
|
469
|
+
}
|
|
470
|
+
if (!text) return { status: res.status, ok: true };
|
|
471
|
+
try {
|
|
472
|
+
return JSON.parse(text);
|
|
473
|
+
} catch {
|
|
474
|
+
return text.length > maxChars ? text.slice(0, maxChars) : text;
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
};
|
|
478
|
+
}
|
|
479
|
+
var METHODS = ["get", "post", "put", "patch", "delete"];
|
|
480
|
+
function deref(doc, node, seen = /* @__PURE__ */ new Set()) {
|
|
481
|
+
if (!node || typeof node !== "object") return node;
|
|
482
|
+
if (typeof node.$ref === "string" && node.$ref.startsWith("#/")) {
|
|
483
|
+
if (seen.has(node.$ref)) return {};
|
|
484
|
+
const next = new Set(seen).add(node.$ref);
|
|
485
|
+
const target = node.$ref.slice(2).split("/").reduce((acc, part) => acc?.[part.replace(/~1/g, "/").replace(/~0/g, "~")], doc);
|
|
486
|
+
return deref(doc, target, next);
|
|
487
|
+
}
|
|
488
|
+
if (Array.isArray(node)) return node.map((n) => deref(doc, n, seen));
|
|
489
|
+
const out = {};
|
|
490
|
+
for (const [k, v] of Object.entries(node)) out[k] = deref(doc, v, seen);
|
|
491
|
+
return out;
|
|
492
|
+
}
|
|
493
|
+
function toParam(schema, description, optional = false) {
|
|
494
|
+
const t = schema?.type;
|
|
495
|
+
const type = ["string", "number", "integer", "boolean", "object", "array"].includes(t) ? t : "string";
|
|
496
|
+
const p = { type, optional };
|
|
497
|
+
const d = [description, schema?.description].filter(Boolean).join(" \u2013 ");
|
|
498
|
+
if (d) p.description = d;
|
|
499
|
+
if (Array.isArray(schema?.enum)) p.enum = schema.enum;
|
|
500
|
+
if (type === "array") p.items = schema?.items ?? {};
|
|
501
|
+
if (type === "object" && schema?.properties) p.properties = schema.properties;
|
|
502
|
+
return p;
|
|
503
|
+
}
|
|
504
|
+
function endpointsFromOpenAPI(rawDoc) {
|
|
505
|
+
const doc = rawDoc;
|
|
506
|
+
const endpoints = [];
|
|
507
|
+
const used = /* @__PURE__ */ new Set();
|
|
508
|
+
for (const [path, item] of Object.entries(doc.paths ?? {})) {
|
|
509
|
+
for (const m of METHODS) {
|
|
510
|
+
const op = item?.[m];
|
|
511
|
+
if (!op) continue;
|
|
512
|
+
const method = m.toUpperCase();
|
|
513
|
+
let name = String(op.operationId ?? `${m}_${path}`).replace(/[^a-zA-Z0-9_-]+/g, "_").replace(/_+/g, "_").replace(/^_+|_+$/g, "").slice(0, 64);
|
|
514
|
+
for (let i = 2; used.has(name); i++) name = `${name.slice(0, 60)}_${i}`;
|
|
515
|
+
used.add(name);
|
|
516
|
+
const parameters = {};
|
|
517
|
+
const all = [...item.parameters ?? [], ...op.parameters ?? []].map((p) => deref(doc, p));
|
|
518
|
+
for (const p of all) {
|
|
519
|
+
if (!["path", "query", "header"].includes(p.in)) continue;
|
|
520
|
+
const schema = p.schema ?? p;
|
|
521
|
+
parameters[p.name] = {
|
|
522
|
+
...toParam(schema, p.description, !p.required && p.in !== "path"),
|
|
523
|
+
in: p.in
|
|
524
|
+
};
|
|
525
|
+
}
|
|
526
|
+
const bodySchema = deref(doc, op.requestBody?.content?.["application/json"]?.schema);
|
|
527
|
+
if (bodySchema?.type === "object" && bodySchema.properties) {
|
|
528
|
+
const req = bodySchema.required ?? [];
|
|
529
|
+
for (const [k, s] of Object.entries(bodySchema.properties)) {
|
|
530
|
+
parameters[k] ??= { ...toParam(s, void 0, !req.includes(k)), in: "body" };
|
|
531
|
+
}
|
|
532
|
+
} else if (bodySchema) {
|
|
533
|
+
parameters.body = { ...toParam(bodySchema, "Request body", !op.requestBody?.required), in: "body" };
|
|
534
|
+
}
|
|
535
|
+
const s2 = all.find((p) => p.in === "body");
|
|
536
|
+
if (s2?.schema?.properties) {
|
|
537
|
+
const req = s2.schema.required ?? [];
|
|
538
|
+
for (const [k, s] of Object.entries(s2.schema.properties)) {
|
|
539
|
+
parameters[k] ??= { ...toParam(s, void 0, !req.includes(k)), in: "body" };
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
endpoints.push({
|
|
543
|
+
name,
|
|
544
|
+
description: [op.summary, op.description].filter(Boolean).join(". ") || `${method} ${path}`,
|
|
545
|
+
method,
|
|
546
|
+
path,
|
|
547
|
+
parameters
|
|
548
|
+
});
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
return endpoints;
|
|
552
|
+
}
|
|
553
|
+
async function buildApiTools(api, getApi = () => api) {
|
|
554
|
+
let endpoints = [...api.endpoints ?? []];
|
|
555
|
+
if (api.openapi) {
|
|
556
|
+
let doc = api.openapi;
|
|
557
|
+
if (typeof doc === "string") {
|
|
558
|
+
const res = await fetch(doc, { credentials: api.credentials });
|
|
559
|
+
if (!res.ok) throw new Error(`Could not load OpenAPI document (${res.status}).`);
|
|
560
|
+
doc = await res.json();
|
|
561
|
+
}
|
|
562
|
+
doc = deref(doc, doc);
|
|
563
|
+
let generated = endpointsFromOpenAPI(doc);
|
|
564
|
+
if (api.include) generated = generated.filter((e) => api.include.includes(e.name));
|
|
565
|
+
if (api.exclude) generated = generated.filter((e) => !api.exclude.includes(e.name));
|
|
566
|
+
const names = new Set(endpoints.map((e) => e.name));
|
|
567
|
+
endpoints = [...endpoints, ...generated.filter((e) => !names.has(e.name))];
|
|
568
|
+
}
|
|
569
|
+
return endpoints.map((ep) => endpointToTool(getApi, ep));
|
|
570
|
+
}
|
|
438
571
|
|
|
439
|
-
|
|
572
|
+
// src/core/types.ts
|
|
573
|
+
var DEFAULT_SYSTEM_PROMPT = `You are a helpful assistant embedded in a web application.
|
|
440
574
|
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
575
|
+
- Use the available tools to look up real data or perform actions whenever the user's request needs them. Never invent data that a tool could provide.
|
|
576
|
+
- If a tool fails, read the error, fix the arguments and retry when it makes sense; otherwise explain the problem briefly.
|
|
577
|
+
- Ask a short clarifying question when a required value is missing.
|
|
578
|
+
- Reply in clean Markdown (lists, tables, **bold** for key values). Do not mention tool names or HTTP details unless asked.`;
|
|
444
579
|
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
580
|
+
// src/core/engine.ts
|
|
581
|
+
var DEFAULT_KEY = "react-mcp-chatbot:history";
|
|
582
|
+
var counter = 0;
|
|
583
|
+
var uid = () => `m_${Date.now().toString(36)}_${(counter++).toString(36)}`;
|
|
584
|
+
var ChatEngine = class {
|
|
585
|
+
cfg;
|
|
586
|
+
provider;
|
|
587
|
+
providerSig = "";
|
|
588
|
+
state = { messages: [], loading: false, status: null };
|
|
589
|
+
listeners = /* @__PURE__ */ new Set();
|
|
590
|
+
abortCtl = null;
|
|
591
|
+
apiTools = null;
|
|
592
|
+
apiSig = "";
|
|
593
|
+
constructor(config) {
|
|
594
|
+
this.cfg = config;
|
|
595
|
+
this.provider = this.makeProvider();
|
|
596
|
+
this.state.messages = this.load();
|
|
597
|
+
}
|
|
598
|
+
// ── config ──────────────────────────────────
|
|
599
|
+
/** Update config without losing history. Safe to call on every render. */
|
|
600
|
+
configure(config) {
|
|
601
|
+
const prevKey = this.storageKey();
|
|
602
|
+
this.cfg = config;
|
|
603
|
+
const sig = this.sigOf();
|
|
604
|
+
if (sig !== this.providerSig) this.provider = this.makeProvider();
|
|
605
|
+
const aSig = JSON.stringify(config.api ?? null, (_k, v) => typeof v === "function" ? "fn" : v);
|
|
606
|
+
if (aSig !== this.apiSig) {
|
|
607
|
+
this.apiSig = aSig;
|
|
608
|
+
this.apiTools = null;
|
|
609
|
+
}
|
|
610
|
+
if (this.storageKey() !== prevKey) {
|
|
611
|
+
this.state = { ...this.state, messages: this.load() };
|
|
612
|
+
this.emit();
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
sigOf() {
|
|
616
|
+
const { provider, model, apiKey, providerURL, temperature, headers } = this.cfg;
|
|
617
|
+
return JSON.stringify([provider, model, apiKey, providerURL, temperature, headers]);
|
|
618
|
+
}
|
|
619
|
+
makeProvider() {
|
|
620
|
+
this.providerSig = this.sigOf();
|
|
621
|
+
return createProvider(this.cfg);
|
|
622
|
+
}
|
|
623
|
+
// ── state / subscription ────────────────────
|
|
624
|
+
getState = () => this.state;
|
|
625
|
+
subscribe = (fn) => {
|
|
626
|
+
this.listeners.add(fn);
|
|
627
|
+
return () => {
|
|
628
|
+
this.listeners.delete(fn);
|
|
629
|
+
};
|
|
630
|
+
};
|
|
631
|
+
set(patch) {
|
|
632
|
+
this.state = { ...this.state, ...patch };
|
|
633
|
+
if (patch.messages) this.save();
|
|
634
|
+
this.emit();
|
|
635
|
+
}
|
|
636
|
+
emit() {
|
|
637
|
+
this.listeners.forEach((l) => l());
|
|
638
|
+
}
|
|
639
|
+
// ── persistence ─────────────────────────────
|
|
640
|
+
storageKey() {
|
|
641
|
+
const p = this.cfg.persist;
|
|
642
|
+
if (!p) return null;
|
|
643
|
+
return typeof p === "string" ? p : DEFAULT_KEY;
|
|
644
|
+
}
|
|
645
|
+
load() {
|
|
646
|
+
const key = this.storageKey();
|
|
647
|
+
if (!key || typeof localStorage === "undefined") return [];
|
|
648
|
+
try {
|
|
649
|
+
const parsed = JSON.parse(localStorage.getItem(key) ?? "[]");
|
|
650
|
+
return Array.isArray(parsed) ? parsed : [];
|
|
651
|
+
} catch {
|
|
652
|
+
return [];
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
save() {
|
|
656
|
+
const key = this.storageKey();
|
|
657
|
+
if (!key || typeof localStorage === "undefined") return;
|
|
658
|
+
try {
|
|
659
|
+
localStorage.setItem(key, JSON.stringify(this.state.messages));
|
|
660
|
+
} catch {
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
// ── public actions ──────────────────────────
|
|
664
|
+
/** Wipe the conversation (and the saved copy). Also cancels a request in flight. */
|
|
665
|
+
clear() {
|
|
666
|
+
this.abort();
|
|
667
|
+
const key = this.storageKey();
|
|
668
|
+
if (key && typeof localStorage !== "undefined") {
|
|
669
|
+
try {
|
|
670
|
+
localStorage.removeItem(key);
|
|
671
|
+
} catch {
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
this.set({ messages: [], loading: false, status: null });
|
|
675
|
+
}
|
|
676
|
+
abort() {
|
|
677
|
+
this.abortCtl?.abort();
|
|
678
|
+
}
|
|
679
|
+
async send(text) {
|
|
680
|
+
const content = text.trim();
|
|
681
|
+
if (!content || this.state.loading) return;
|
|
682
|
+
const ctl = new AbortController();
|
|
683
|
+
this.abortCtl = ctl;
|
|
684
|
+
const base = this.state.messages;
|
|
685
|
+
this.set({
|
|
686
|
+
messages: [...base, { id: uid(), role: "user", content }],
|
|
687
|
+
loading: true,
|
|
688
|
+
status: null
|
|
689
|
+
});
|
|
690
|
+
try {
|
|
691
|
+
await this.run(ctl.signal);
|
|
692
|
+
} catch (e) {
|
|
693
|
+
if (ctl.signal.aborted) {
|
|
694
|
+
if (this.abortCtl === ctl) {
|
|
695
|
+
this.set({ messages: this.state.messages.slice(0, this.lastIndexOf("user") + 1) });
|
|
696
|
+
}
|
|
697
|
+
} else {
|
|
698
|
+
const err = e instanceof Error ? e : new Error(String(e));
|
|
699
|
+
this.cfg.onError?.(err);
|
|
700
|
+
const lastUser = this.lastIndexOf("user");
|
|
701
|
+
this.set({
|
|
702
|
+
messages: [
|
|
703
|
+
...this.state.messages.slice(0, lastUser + 1),
|
|
704
|
+
{ id: uid(), role: "assistant", content: `\u26A0\uFE0F **Error:** ${err.message}`, error: true }
|
|
705
|
+
]
|
|
706
|
+
});
|
|
707
|
+
}
|
|
708
|
+
} finally {
|
|
709
|
+
if (this.abortCtl === ctl) {
|
|
710
|
+
this.abortCtl = null;
|
|
711
|
+
this.set({ loading: false, status: null });
|
|
712
|
+
}
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
// ── core loop ───────────────────────────────
|
|
716
|
+
lastIndexOf(role) {
|
|
717
|
+
const m = this.state.messages;
|
|
718
|
+
for (let i = m.length - 1; i >= 0; i--) if (m[i].role === role) return i;
|
|
719
|
+
return -1;
|
|
720
|
+
}
|
|
721
|
+
async getTools() {
|
|
722
|
+
const custom = this.cfg.tools ?? [];
|
|
723
|
+
let api = [];
|
|
724
|
+
if (this.cfg.api) {
|
|
725
|
+
const pending = this.apiTools ??= buildApiTools(this.cfg.api, () => this.cfg.api);
|
|
726
|
+
try {
|
|
727
|
+
api = await pending;
|
|
728
|
+
} catch (e) {
|
|
729
|
+
this.apiTools = null;
|
|
730
|
+
throw e;
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
const names = new Set(custom.map((t) => t.name));
|
|
734
|
+
return [...custom, ...api.filter((t) => !names.has(t.name))];
|
|
735
|
+
}
|
|
736
|
+
/** Messages sent to the model: no UI-only errors, windowed to maxHistoryMessages at a turn boundary. */
|
|
737
|
+
requestMessages() {
|
|
738
|
+
const all = this.state.messages.filter((m) => !(m.role === "assistant" && m.error));
|
|
739
|
+
const max = this.cfg.maxHistoryMessages ?? 40;
|
|
740
|
+
if (all.length <= max) return all;
|
|
741
|
+
let start = all.length - max;
|
|
742
|
+
while (start < all.length && all[start].role !== "user") start++;
|
|
743
|
+
return start < all.length ? all.slice(start) : all.slice(-1);
|
|
744
|
+
}
|
|
745
|
+
async run(signal) {
|
|
746
|
+
const tools = await this.getTools();
|
|
747
|
+
const specs = tools.map(toToolSpec);
|
|
748
|
+
const system = this.cfg.systemPrompt ?? DEFAULT_SYSTEM_PROMPT;
|
|
749
|
+
const maxRounds = this.cfg.maxToolRounds ?? 8;
|
|
750
|
+
for (let round = 0; ; round++) {
|
|
751
|
+
const allowTools = round < maxRounds;
|
|
752
|
+
const res = await this.provider.complete({
|
|
753
|
+
system,
|
|
754
|
+
messages: this.requestMessages(),
|
|
755
|
+
tools: allowTools ? specs : [],
|
|
756
|
+
temperature: this.cfg.temperature,
|
|
757
|
+
signal
|
|
758
|
+
});
|
|
759
|
+
const calls = allowTools ? res.toolCalls.filter((c) => c.name) : [];
|
|
760
|
+
this.set({
|
|
761
|
+
messages: [
|
|
762
|
+
...this.state.messages,
|
|
763
|
+
{
|
|
764
|
+
id: uid(),
|
|
765
|
+
role: "assistant",
|
|
766
|
+
content: res.content,
|
|
767
|
+
...calls.length ? { toolCalls: calls } : {}
|
|
471
768
|
}
|
|
472
|
-
|
|
769
|
+
]
|
|
770
|
+
});
|
|
771
|
+
if (!calls.length) return;
|
|
772
|
+
const results = await Promise.all(calls.map((c) => this.execute(c, tools)));
|
|
773
|
+
if (signal.aborted) throw new Error("aborted");
|
|
774
|
+
this.set({
|
|
775
|
+
messages: [...this.state.messages, ...results],
|
|
776
|
+
status: "Thinking\u2026"
|
|
777
|
+
});
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
async execute(call, tools) {
|
|
781
|
+
const tool = tools.find((t) => t.name === call.name);
|
|
782
|
+
let result;
|
|
783
|
+
let error;
|
|
784
|
+
this.set({ status: `Calling ${call.name}\u2026` });
|
|
785
|
+
if (!tool) {
|
|
786
|
+
error = `Unknown tool "${call.name}". Available: ${tools.map((t) => t.name).join(", ") || "none"}.`;
|
|
787
|
+
} else {
|
|
788
|
+
const prepared = prepareArgs(tool, call.args);
|
|
789
|
+
if ("error" in prepared) error = prepared.error;
|
|
790
|
+
else {
|
|
791
|
+
try {
|
|
792
|
+
const allowed = await this.cfg.beforeToolCall?.({
|
|
793
|
+
name: tool.name,
|
|
794
|
+
args: prepared.args,
|
|
795
|
+
method: tool.method
|
|
796
|
+
});
|
|
797
|
+
if (allowed === false) error = "The user declined to run this action.";
|
|
798
|
+
else result = await tool.call(prepared.args);
|
|
799
|
+
} catch (e) {
|
|
800
|
+
error = e instanceof Error ? e.message : String(e);
|
|
801
|
+
}
|
|
473
802
|
}
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
803
|
+
}
|
|
804
|
+
this.cfg.onToolCall?.({ name: call.name, args: call.args, result, error });
|
|
805
|
+
const max = this.cfg.maxToolResultChars ?? 8e3;
|
|
806
|
+
let content = error ? JSON.stringify({ error }) : safeStringify(result);
|
|
807
|
+
if (content.length > max) {
|
|
808
|
+
content = content.slice(0, max) + `
|
|
809
|
+
\u2026[truncated ${content.length - max} characters]`;
|
|
810
|
+
}
|
|
811
|
+
return { id: uid(), role: "tool", toolCallId: call.id, name: call.name, content };
|
|
477
812
|
}
|
|
478
813
|
};
|
|
814
|
+
function safeStringify(v) {
|
|
815
|
+
if (v === void 0) return "null";
|
|
816
|
+
if (typeof v === "string") return v;
|
|
817
|
+
try {
|
|
818
|
+
return JSON.stringify(v);
|
|
819
|
+
} catch {
|
|
820
|
+
return String(v);
|
|
821
|
+
}
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
// src/useChat.ts
|
|
825
|
+
function useChat(config) {
|
|
826
|
+
const [engine] = useState(() => new ChatEngine(config));
|
|
827
|
+
useEffect(() => {
|
|
828
|
+
engine.configure(config);
|
|
829
|
+
});
|
|
830
|
+
const state = useSyncExternalStore(engine.subscribe, engine.getState, engine.getState);
|
|
831
|
+
const send = useCallback((text) => engine.send(text), [engine]);
|
|
832
|
+
const clear = useCallback(() => engine.clear(), [engine]);
|
|
833
|
+
const stop = useCallback(() => engine.abort(), [engine]);
|
|
834
|
+
return useMemo(
|
|
835
|
+
() => ({ ...state, send, clear, stop, engine }),
|
|
836
|
+
[state, send, clear, stop, engine]
|
|
837
|
+
);
|
|
838
|
+
}
|
|
479
839
|
|
|
480
840
|
// src/MCPAgent.tsx
|
|
481
841
|
import { Fragment, jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
|
|
482
|
-
var
|
|
483
|
-
You are a helpful AI assistant.
|
|
484
|
-
|
|
485
|
-
Formatting rules:
|
|
486
|
-
- Always respond in Markdown
|
|
487
|
-
- Use bullet lists for multiple items
|
|
488
|
-
- Use **bold** for important values
|
|
489
|
-
- Use tables when comparing data
|
|
490
|
-
- Use \`inline code\` for variables or keys
|
|
491
|
-
- Use code blocks only when necessary
|
|
492
|
-
- Keep responses clean and readable
|
|
493
|
-
|
|
494
|
-
Context rules:
|
|
495
|
-
- Respond ONLY using the information provided in the context.
|
|
496
|
-
- Do NOT generate or assume any information not present in the context.
|
|
497
|
-
- If the answer cannot be found in the context, respond exactly: "No relevant information was found."
|
|
498
|
-
`;
|
|
499
|
-
function MCPAgent(props) {
|
|
842
|
+
var MCPAgent = forwardRef(function MCPAgent2(props, ref) {
|
|
500
843
|
const {
|
|
501
844
|
title = "AI Assistant",
|
|
502
845
|
align = "right",
|
|
@@ -506,23 +849,55 @@ function MCPAgent(props) {
|
|
|
506
849
|
theme = "dark",
|
|
507
850
|
buttonLabel,
|
|
508
851
|
placeholder = "Message\u2026",
|
|
509
|
-
borderRadius = 20
|
|
852
|
+
borderRadius = 20,
|
|
853
|
+
showClearButton = true,
|
|
854
|
+
defaultOpen = false,
|
|
855
|
+
suggestions
|
|
510
856
|
} = props;
|
|
511
857
|
const isDark = theme === "dark";
|
|
512
858
|
const t = buildTokens(primaryColor, isDark);
|
|
513
|
-
const
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
859
|
+
const {
|
|
860
|
+
title: _t,
|
|
861
|
+
align: _a,
|
|
862
|
+
primaryColor: _p,
|
|
863
|
+
width: _w,
|
|
864
|
+
height: _h,
|
|
865
|
+
theme: _th,
|
|
866
|
+
buttonLabel: _b,
|
|
867
|
+
placeholder: _ph,
|
|
868
|
+
borderRadius: _br,
|
|
869
|
+
showClearButton: _sc,
|
|
870
|
+
defaultOpen: _do,
|
|
871
|
+
suggestions: _sg,
|
|
872
|
+
...config
|
|
873
|
+
} = props;
|
|
874
|
+
const chat = useChat(config);
|
|
875
|
+
const { loading, status } = chat;
|
|
876
|
+
useImperativeHandle(ref, () => ({
|
|
877
|
+
clear: chat.clear,
|
|
878
|
+
send: chat.send,
|
|
879
|
+
stop: chat.stop
|
|
880
|
+
}), [chat.clear, chat.send, chat.stop]);
|
|
881
|
+
const messages = chat.messages.filter(
|
|
882
|
+
(m) => (m.role === "user" || m.role === "assistant") && m.content.trim()
|
|
883
|
+
);
|
|
884
|
+
async function send() {
|
|
885
|
+
if (!input.trim() || loading) return;
|
|
886
|
+
const text = input;
|
|
887
|
+
setInput("");
|
|
888
|
+
await chat.send(text);
|
|
889
|
+
}
|
|
890
|
+
const [open, setOpen] = useState2(defaultOpen);
|
|
891
|
+
const [input, setInput] = useState2("");
|
|
892
|
+
const [animateIn, setAnimateIn] = useState2(false);
|
|
518
893
|
const scrollRef = useRef(null);
|
|
519
894
|
const inputRef = useRef(null);
|
|
520
|
-
|
|
895
|
+
useEffect2(() => {
|
|
521
896
|
if (scrollRef.current) {
|
|
522
897
|
scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
|
|
523
898
|
}
|
|
524
899
|
}, [messages, loading]);
|
|
525
|
-
|
|
900
|
+
useEffect2(() => {
|
|
526
901
|
if (open) {
|
|
527
902
|
requestAnimationFrame(() => setAnimateIn(true));
|
|
528
903
|
setTimeout(() => inputRef.current?.focus(), 200);
|
|
@@ -530,60 +905,6 @@ function MCPAgent(props) {
|
|
|
530
905
|
setAnimateIn(false);
|
|
531
906
|
}
|
|
532
907
|
}, [open]);
|
|
533
|
-
const agent = useMemo(() => {
|
|
534
|
-
if (props.provider === "ollama") {
|
|
535
|
-
return new OllamaAgent(
|
|
536
|
-
props.model,
|
|
537
|
-
props.providerURL,
|
|
538
|
-
props.tools
|
|
539
|
-
);
|
|
540
|
-
} else if (props.provider === "openai") {
|
|
541
|
-
return new OpenAIAgent(
|
|
542
|
-
props.apiKey,
|
|
543
|
-
props.model,
|
|
544
|
-
void 0,
|
|
545
|
-
props.tools
|
|
546
|
-
);
|
|
547
|
-
} else if (props.provider === "gemini") {
|
|
548
|
-
return new GeminiAgent(
|
|
549
|
-
props.apiKey,
|
|
550
|
-
props.model,
|
|
551
|
-
void 0,
|
|
552
|
-
props.tools
|
|
553
|
-
);
|
|
554
|
-
}
|
|
555
|
-
return new GroqAgent(
|
|
556
|
-
props.apiKey,
|
|
557
|
-
props.model,
|
|
558
|
-
void 0,
|
|
559
|
-
props.tools
|
|
560
|
-
);
|
|
561
|
-
}, [
|
|
562
|
-
props.provider,
|
|
563
|
-
props.model,
|
|
564
|
-
props.providerURL,
|
|
565
|
-
props.apiKey,
|
|
566
|
-
props.tools
|
|
567
|
-
]);
|
|
568
|
-
async function send() {
|
|
569
|
-
if (!input.trim() || loading) return;
|
|
570
|
-
const userMessage = input.trim();
|
|
571
|
-
setInput("");
|
|
572
|
-
setLoading(true);
|
|
573
|
-
setMessages((prev) => [...prev, { role: "user", content: userMessage }]);
|
|
574
|
-
try {
|
|
575
|
-
const response = await agent.ask(userMessage);
|
|
576
|
-
setMessages((prev) => [...prev, { role: "ai", content: response }]);
|
|
577
|
-
} catch (err) {
|
|
578
|
-
console.log(err);
|
|
579
|
-
setMessages((prev) => [
|
|
580
|
-
...prev,
|
|
581
|
-
{ role: "ai", content: "\u26A0\uFE0F **Error:** Unable to fetch response." }
|
|
582
|
-
]);
|
|
583
|
-
} finally {
|
|
584
|
-
setLoading(false);
|
|
585
|
-
}
|
|
586
|
-
}
|
|
587
908
|
const side = align === "right" ? { right: 24 } : { left: 24 };
|
|
588
909
|
const styleTag = `
|
|
589
910
|
.mcp-input:focus { outline: none; box-shadow: 0 0 0 2.5px ${t.inputFocus}33; border-color: ${t.inputFocus} !important; }
|
|
@@ -603,6 +924,8 @@ function MCPAgent(props) {
|
|
|
603
924
|
.mcp-bubble-ai p { margin: 4px 0; }
|
|
604
925
|
.mcp-bubble-ai ul, .mcp-bubble-ai ol { margin: 4px 0; padding-left: 18px; }
|
|
605
926
|
.mcp-bubble-ai li { margin: 2px 0; }
|
|
927
|
+
.mcp-clear-btn:not(:disabled):hover { color: ${t.text} !important; background: ${t.surfaceHover} !important; }
|
|
928
|
+
.mcp-chip:hover:not(:disabled) { border-color: ${t.accent} !important; color: ${t.accent} !important; transform: translateY(-1px); }
|
|
606
929
|
.mcp-float-btn:hover { transform: scale(1.08); box-shadow: 0 14px 36px ${primaryColor}55 !important; }
|
|
607
930
|
.mcp-float-btn:active { transform: scale(0.96); }
|
|
608
931
|
`;
|
|
@@ -646,8 +969,9 @@ function MCPAgent(props) {
|
|
|
646
969
|
position: "fixed",
|
|
647
970
|
bottom: 84,
|
|
648
971
|
...side,
|
|
649
|
-
|
|
650
|
-
|
|
972
|
+
// never wider/taller than the viewport (phones)
|
|
973
|
+
width: `min(${width}px, calc(100vw - 32px))`,
|
|
974
|
+
height: `min(${height}px, calc(100vh - 110px))`,
|
|
651
975
|
background: t.bg,
|
|
652
976
|
borderRadius,
|
|
653
977
|
display: "flex",
|
|
@@ -729,7 +1053,32 @@ function MCPAgent(props) {
|
|
|
729
1053
|
),
|
|
730
1054
|
"Online"
|
|
731
1055
|
] })
|
|
732
|
-
] })
|
|
1056
|
+
] }),
|
|
1057
|
+
showClearButton && /* @__PURE__ */ jsx2(
|
|
1058
|
+
"button",
|
|
1059
|
+
{
|
|
1060
|
+
className: "mcp-clear-btn",
|
|
1061
|
+
onClick: chat.clear,
|
|
1062
|
+
disabled: chat.messages.length === 0,
|
|
1063
|
+
title: "Clear chat",
|
|
1064
|
+
"aria-label": "Clear chat",
|
|
1065
|
+
style: {
|
|
1066
|
+
marginLeft: "auto",
|
|
1067
|
+
position: "relative",
|
|
1068
|
+
zIndex: 1,
|
|
1069
|
+
background: "transparent",
|
|
1070
|
+
border: `1px solid ${t.border}`,
|
|
1071
|
+
color: t.textMuted,
|
|
1072
|
+
borderRadius: 8,
|
|
1073
|
+
padding: "5px 10px",
|
|
1074
|
+
fontSize: 12,
|
|
1075
|
+
cursor: chat.messages.length === 0 ? "default" : "pointer",
|
|
1076
|
+
opacity: chat.messages.length === 0 ? 0.4 : 1,
|
|
1077
|
+
fontFamily: "inherit"
|
|
1078
|
+
},
|
|
1079
|
+
children: "Clear"
|
|
1080
|
+
}
|
|
1081
|
+
)
|
|
733
1082
|
]
|
|
734
1083
|
}
|
|
735
1084
|
),
|
|
@@ -781,11 +1130,32 @@ function MCPAgent(props) {
|
|
|
781
1130
|
}
|
|
782
1131
|
),
|
|
783
1132
|
/* @__PURE__ */ jsx2("span", { style: { fontWeight: 600, color: t.text, fontSize: 14 }, children: "Hey there!" }),
|
|
784
|
-
/* @__PURE__ */ jsx2("span", { children: "How can I help you today?" })
|
|
1133
|
+
/* @__PURE__ */ jsx2("span", { children: "How can I help you today?" }),
|
|
1134
|
+
suggestions && suggestions.length > 0 && /* @__PURE__ */ jsx2("div", { style: { display: "flex", flexWrap: "wrap", gap: 8, justifyContent: "center", marginTop: 6 }, children: suggestions.map((q) => /* @__PURE__ */ jsx2(
|
|
1135
|
+
"button",
|
|
1136
|
+
{
|
|
1137
|
+
className: "mcp-chip",
|
|
1138
|
+
disabled: loading,
|
|
1139
|
+
onClick: () => chat.send(q),
|
|
1140
|
+
style: {
|
|
1141
|
+
background: t.bg,
|
|
1142
|
+
color: t.text,
|
|
1143
|
+
border: `1px solid ${t.border}`,
|
|
1144
|
+
borderRadius: 999,
|
|
1145
|
+
padding: "7px 13px",
|
|
1146
|
+
fontSize: 12.5,
|
|
1147
|
+
cursor: "pointer",
|
|
1148
|
+
fontFamily: "inherit",
|
|
1149
|
+
transition: "all .15s"
|
|
1150
|
+
},
|
|
1151
|
+
children: q
|
|
1152
|
+
},
|
|
1153
|
+
q
|
|
1154
|
+
)) })
|
|
785
1155
|
]
|
|
786
1156
|
}
|
|
787
1157
|
),
|
|
788
|
-
messages.map((m
|
|
1158
|
+
messages.map((m) => {
|
|
789
1159
|
const isUser = m.role === "user";
|
|
790
1160
|
return /* @__PURE__ */ jsx2(
|
|
791
1161
|
"div",
|
|
@@ -814,10 +1184,10 @@ function MCPAgent(props) {
|
|
|
814
1184
|
}
|
|
815
1185
|
)
|
|
816
1186
|
},
|
|
817
|
-
|
|
1187
|
+
m.id
|
|
818
1188
|
);
|
|
819
1189
|
}),
|
|
820
|
-
loading && /* @__PURE__ */ jsx2("div", { style: { display: "flex", justifyContent: "flex-start" }, children: /* @__PURE__ */
|
|
1190
|
+
loading && /* @__PURE__ */ jsx2("div", { style: { display: "flex", justifyContent: "flex-start" }, children: /* @__PURE__ */ jsxs2(
|
|
821
1191
|
"div",
|
|
822
1192
|
{
|
|
823
1193
|
style: {
|
|
@@ -826,7 +1196,10 @@ function MCPAgent(props) {
|
|
|
826
1196
|
borderRadius: "18px 18px 18px 6px",
|
|
827
1197
|
boxShadow: isDark ? "0 2px 10px rgba(0,0,0,.2)" : "0 2px 10px rgba(0,0,0,.07)"
|
|
828
1198
|
},
|
|
829
|
-
children:
|
|
1199
|
+
children: [
|
|
1200
|
+
/* @__PURE__ */ jsx2(TypingDots, { color: primaryColor }),
|
|
1201
|
+
status && /* @__PURE__ */ jsx2("span", { style: { color: t.textMuted, fontSize: 11, marginLeft: 8 }, children: status })
|
|
1202
|
+
]
|
|
830
1203
|
}
|
|
831
1204
|
) })
|
|
832
1205
|
]
|
|
@@ -851,7 +1224,7 @@ function MCPAgent(props) {
|
|
|
851
1224
|
className: "mcp-input",
|
|
852
1225
|
value: input,
|
|
853
1226
|
onChange: (e) => setInput(e.target.value),
|
|
854
|
-
onKeyDown: (e) => e.key === "Enter" && send(),
|
|
1227
|
+
onKeyDown: (e) => e.key === "Enter" && !e.nativeEvent.isComposing && send(),
|
|
855
1228
|
placeholder,
|
|
856
1229
|
disabled: loading,
|
|
857
1230
|
style: {
|
|
@@ -904,7 +1277,13 @@ function MCPAgent(props) {
|
|
|
904
1277
|
}
|
|
905
1278
|
` })
|
|
906
1279
|
] });
|
|
907
|
-
}
|
|
1280
|
+
});
|
|
908
1281
|
export {
|
|
909
|
-
|
|
1282
|
+
ChatEngine,
|
|
1283
|
+
DEFAULT_SYSTEM_PROMPT,
|
|
1284
|
+
MCPAgent,
|
|
1285
|
+
PROVIDER_URLS,
|
|
1286
|
+
createProvider,
|
|
1287
|
+
endpointsFromOpenAPI,
|
|
1288
|
+
useChat
|
|
910
1289
|
};
|