react-mcp-chatbot 0.0.6 → 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/dist/index.js CHANGED
@@ -1,128 +1,10 @@
1
1
  // src/MCPAgent.tsx
2
- import { useState, useRef, useEffect, useMemo } from "react";
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 = "./send-2CSO66UQ.svg";
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,394 +81,765 @@ function buildTokens(accent, dark) {
199
81
  };
200
82
  }
201
83
 
202
- // src/agents/groqAgent.ts
203
- var GroqAgent = class extends Agent {
204
- apiKey;
205
- constructor(apiKey, model = "llama3-70b-8192", providerURL = "https://api.groq.com/openai/v1", tools = []) {
206
- super(model, providerURL, tools);
207
- this.apiKey = apiKey;
208
- }
209
- async decideTool(message) {
210
- if (this.tools.length === 0) return { tool: null };
211
- const res = await fetch(`${this.url}/chat/completions`, {
212
- method: "POST",
213
- headers: {
214
- "Content-Type": "application/json",
215
- Authorization: `Bearer ${this.apiKey}`
216
- },
217
- body: JSON.stringify({
218
- model: this.model,
219
- temperature: 0,
220
- messages: [
221
- {
222
- role: "system",
223
- content: "You select tools and arguments. Respond ONLY with valid JSON."
224
- },
225
- {
226
- role: "user",
227
- content: buildToolDecisionPrompt(this.tools, message)
228
- }
229
- ]
230
- })
231
- });
232
- const data = await res.json();
233
- const content = data.choices?.[0]?.message?.content;
234
- try {
235
- return JSON.parse(content);
236
- } catch {
237
- return { tool: null };
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
- async ask(message) {
241
- let toolContext = "";
242
- const decision = await this.decideTool(message);
243
- if (decision.tool) {
244
- const tool = this.tools.find((t) => t.name === decision.tool);
245
- if (tool) {
246
- const result = await tool.call(decision.arguments);
247
- toolContext = `
248
- Tool used: ${tool.name}
249
- Result (partial):
250
- \`\`\`json
251
- ${JSON.stringify(result, null, 2).slice(0, 4e3)}
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 finalPrompt = `
257
- User request:
258
- ${message}
259
-
260
- ${toolContext}
261
-
262
- Respond in clean, well-formatted Markdown.
263
- Use lists, tables, and headings where appropriate.
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: JSON.stringify({
277
- model: this.model,
278
- messages: [
279
- { role: "system", content: MARKDOWN_SYSTEM_PROMPT },
280
- { role: "user", content: finalPrompt }
281
- ],
282
- temperature: 0
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/agents/openai.ts
291
- var OpenAIAgent = class extends Agent {
292
- apiKey;
293
- constructor(apiKey, model = "gpt-4o-mini", providerURL = "https://api.openai.com/v1", tools = []) {
294
- super(model, providerURL, tools);
295
- this.apiKey = apiKey;
296
- }
297
- async decideTool(message) {
298
- if (this.tools.length === 0) return { tool: null };
299
- const res = await fetch(`${this.url}/chat/completions`, {
300
- method: "POST",
301
- headers: {
302
- "Content-Type": "application/json",
303
- Authorization: `Bearer ${this.apiKey}`
304
- },
305
- body: JSON.stringify({
306
- model: this.model,
307
- temperature: 0,
308
- messages: [
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
- async ask(message) {
329
- let toolContext = "";
330
- const decision = await this.decideTool(message);
331
- if (decision.tool) {
332
- const tool = this.tools.find((t) => t.name === decision.tool);
333
- if (tool) {
334
- const result = await tool.call(decision.arguments);
335
- toolContext = `
336
- Tool used: ${tool.name}
337
- Result (partial):
338
- \`\`\`json
339
- ${JSON.stringify(result, null, 2).slice(0, 4e3)}
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 finalPrompt = `
345
- User request:
346
- ${message}
347
-
348
- ${toolContext}
349
-
350
- Respond in clean, well-formatted Markdown.
351
- Use lists, tables, and headings where appropriate.
352
- Do NOT mention tools or APIs explicitly.
353
- Context rules:
354
- - Respond ONLY using the information provided in the context.
355
- - Do NOT generate or assume any information not present in the context.
356
- - If the answer cannot be found in the context, respond exactly: "No relevant information was found."
357
- `;
358
- const res = await fetch(`${this.url}/chat/completions`, {
359
- method: "POST",
360
- headers: {
361
- "Content-Type": "application/json",
362
- Authorization: `Bearer ${this.apiKey}`
363
- },
364
- body: JSON.stringify({
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/agents/geminiAgent.ts
379
- var GeminiAgent = class extends Agent {
380
- apiKey;
381
- constructor(apiKey, model = "models/gemini-1.5-pro", providerURL = "https://generativelanguage.googleapis.com/v1beta", tools = []) {
382
- super(model, providerURL, tools);
383
- this.apiKey = apiKey;
384
- }
385
- async decideTool(message) {
386
- if (this.tools.length === 0) return { tool: null };
387
- const res = await fetch(
388
- `${this.url}/${this.model}:generateContent?key=${this.apiKey}`,
389
- {
390
- method: "POST",
391
- headers: {
392
- "Content-Type": "application/json"
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 data = await res.json();
412
- const content = data.candidates?.[0]?.content?.parts?.[0]?.text ?? "";
413
- try {
414
- return JSON.parse(content);
415
- } catch {
416
- return { tool: null };
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 });
362
+ }
363
+ }
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.` };
406
+ }
407
+ }
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
+ }
417
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);
418
487
  }
419
- async ask(message) {
420
- let toolContext = "";
421
- const decision = await this.decideTool(message);
422
- if (decision.tool) {
423
- const tool = this.tools.find((t) => t.name === decision.tool);
424
- if (tool) {
425
- const result = await tool.call(decision.arguments);
426
- toolContext = `
427
- Tool used: ${tool.name}
428
- Result (partial):
429
- \`\`\`json
430
- ${JSON.stringify(result, null, 2).slice(0, 4e3)}
431
- \`\`\`
432
- `;
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
+ }
433
541
  }
542
+ endpoints.push({
543
+ name,
544
+ description: [op.summary, op.description].filter(Boolean).join(". ") || `${method} ${path}`,
545
+ method,
546
+ path,
547
+ parameters
548
+ });
434
549
  }
435
- const finalPrompt = `
436
- User request:
437
- ${message}
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
- ${toolContext}
572
+ // src/core/types.ts
573
+ var DEFAULT_SYSTEM_PROMPT = `You are a helpful assistant embedded in a web application.
440
574
 
441
- Respond in clean, well-formatted Markdown.
442
- Use lists, tables, and headings where appropriate.
443
- Do NOT mention tools or APIs explicitly.
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
- Context rules:
446
- - Respond ONLY using the information provided in the context.
447
- - Do NOT generate or assume any information not present in the context.
448
- - If the answer cannot be found in the context, respond exactly:
449
- "No relevant information was found."
450
- `;
451
- const res = await fetch(
452
- `${this.url}/${this.model}:generateContent?key=${this.apiKey}`,
453
- {
454
- method: "POST",
455
- headers: {
456
- "Content-Type": "application/json"
457
- },
458
- body: JSON.stringify({
459
- contents: [
460
- {
461
- role: "user",
462
- parts: [{ text: MARKDOWN_SYSTEM_PROMPT }]
463
- },
464
- {
465
- role: "user",
466
- parts: [{ text: finalPrompt }]
467
- }
468
- ],
469
- generationConfig: {
470
- temperature: 0
471
- }
472
- })
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 {
473
672
  }
474
- );
475
- const data = await res.json();
476
- return data.candidates?.[0]?.content?.parts?.[0]?.text ?? "";
673
+ }
674
+ this.set({ messages: [], loading: false, status: null });
477
675
  }
478
- };
479
-
480
- // src/agents/deepseekAgent.ts
481
- var DeepSeekAgent = class extends Agent {
482
- apiKey;
483
- constructor(apiKey, model = "deepseek-chat", providerURL = "https://api.deepseek.com/v1", tools = []) {
484
- super(model, providerURL, tools);
485
- this.apiKey = apiKey;
486
- }
487
- async decideTool(message) {
488
- if (this.tools.length === 0) return { tool: null };
489
- const res = await fetch(`${this.url}/chat/completions`, {
490
- method: "POST",
491
- headers: {
492
- "Content-Type": "application/json",
493
- Authorization: `Bearer ${this.apiKey}`
494
- },
495
- body: JSON.stringify({
496
- model: this.model,
497
- temperature: 0,
498
- messages: [
499
- {
500
- role: "system",
501
- content: "You select tools and arguments. Respond ONLY with valid JSON."
502
- },
503
- {
504
- role: "user",
505
- content: buildToolDecisionPrompt(this.tools, message)
506
- }
507
- ]
508
- })
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
509
689
  });
510
- const data = await res.json();
511
- const content = data.choices?.[0]?.message?.content;
512
690
  try {
513
- return JSON.parse(content);
514
- } catch {
515
- return { tool: null };
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
+ }
516
713
  }
517
714
  }
518
- async ask(message) {
519
- let toolContext = "";
520
- const decision = await this.decideTool(message);
521
- if (decision.tool) {
522
- const tool = this.tools.find((t) => t.name === decision.tool);
523
- if (tool) {
524
- const result = await tool.call(decision.arguments);
525
- toolContext = `
526
- Tool used: ${tool.name}
527
- Result (partial):
528
- \`\`\`json
529
- ${JSON.stringify(result, null, 2).slice(0, 4e3)}
530
- \`\`\`
531
- `;
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;
532
731
  }
533
732
  }
534
- const finalPrompt = `
535
- User request:
536
- ${message}
537
-
538
- ${toolContext}
539
-
540
- Respond in clean, well-formatted Markdown.
541
- Use lists, tables, and headings where appropriate.
542
- Do NOT mention tools or APIs explicitly.
543
-
544
- Context rules:
545
- - Respond ONLY using the information provided in the context.
546
- - Do NOT generate or assume any information not present in the context.
547
- - If the answer cannot be found in the context, respond exactly:
548
- "No relevant information was found."
549
- `;
550
- const res = await fetch(`${this.url}/chat/completions`, {
551
- method: "POST",
552
- headers: {
553
- "Content-Type": "application/json",
554
- Authorization: `Bearer ${this.apiKey}`
555
- },
556
- body: JSON.stringify({
557
- model: this.model,
558
- temperature: 0,
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({
559
761
  messages: [
560
- { role: "system", content: MARKDOWN_SYSTEM_PROMPT },
561
- { role: "user", content: finalPrompt }
762
+ ...this.state.messages,
763
+ {
764
+ id: uid(),
765
+ role: "assistant",
766
+ content: res.content,
767
+ ...calls.length ? { toolCalls: calls } : {}
768
+ }
562
769
  ]
563
- })
564
- });
565
- const data = await res.json();
566
- return data.choices?.[0]?.message?.content ?? "";
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
+ }
802
+ }
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 };
567
812
  }
568
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
+ }
569
839
 
570
840
  // src/MCPAgent.tsx
571
841
  import { Fragment, jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
572
- var MARKDOWN_SYSTEM_PROMPT = `
573
- You are a helpful AI assistant.
574
-
575
- Formatting rules:
576
- - Always respond in Markdown
577
- - Use bullet lists for multiple items
578
- - Use **bold** for important values
579
- - Use tables when comparing data
580
- - Use \`inline code\` for variables or keys
581
- - Use code blocks only when necessary
582
- - Keep responses clean and readable
583
-
584
- Context rules:
585
- - Respond ONLY using the information provided in the context.
586
- - Do NOT generate or assume any information not present in the context.
587
- - If the answer cannot be found in the context, respond exactly: "No relevant information was found."
588
- `;
589
- function MCPAgent(props) {
842
+ var MCPAgent = forwardRef(function MCPAgent2(props, ref) {
590
843
  const {
591
844
  title = "AI Assistant",
592
845
  align = "right",
@@ -596,23 +849,55 @@ function MCPAgent(props) {
596
849
  theme = "dark",
597
850
  buttonLabel,
598
851
  placeholder = "Message\u2026",
599
- borderRadius = 20
852
+ borderRadius = 20,
853
+ showClearButton = true,
854
+ defaultOpen = false,
855
+ suggestions
600
856
  } = props;
601
857
  const isDark = theme === "dark";
602
858
  const t = buildTokens(primaryColor, isDark);
603
- const [open, setOpen] = useState(false);
604
- const [messages, setMessages] = useState([]);
605
- const [input, setInput] = useState("");
606
- const [loading, setLoading] = useState(false);
607
- const [animateIn, setAnimateIn] = useState(false);
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);
608
893
  const scrollRef = useRef(null);
609
894
  const inputRef = useRef(null);
610
- useEffect(() => {
895
+ useEffect2(() => {
611
896
  if (scrollRef.current) {
612
897
  scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
613
898
  }
614
899
  }, [messages, loading]);
615
- useEffect(() => {
900
+ useEffect2(() => {
616
901
  if (open) {
617
902
  requestAnimationFrame(() => setAnimateIn(true));
618
903
  setTimeout(() => inputRef.current?.focus(), 200);
@@ -620,67 +905,6 @@ function MCPAgent(props) {
620
905
  setAnimateIn(false);
621
906
  }
622
907
  }, [open]);
623
- const agent = useMemo(() => {
624
- if (props.provider === "ollama") {
625
- return new OllamaAgent(
626
- props.model,
627
- props.providerURL,
628
- props.tools
629
- );
630
- } else if (props.provider === "openai") {
631
- return new OpenAIAgent(
632
- props.apiKey,
633
- props.model,
634
- void 0,
635
- props.tools
636
- );
637
- } else if (props.provider === "gemini") {
638
- return new GeminiAgent(
639
- props.apiKey,
640
- props.model,
641
- void 0,
642
- props.tools
643
- );
644
- } else if (props.provider === "deepseek") {
645
- return new DeepSeekAgent(
646
- props.apiKey,
647
- props.model,
648
- void 0,
649
- props.tools
650
- );
651
- }
652
- return new GroqAgent(
653
- props.apiKey,
654
- props.model,
655
- void 0,
656
- props.tools
657
- );
658
- }, [
659
- props.provider,
660
- props.model,
661
- props.providerURL,
662
- props.apiKey,
663
- props.tools
664
- ]);
665
- async function send() {
666
- if (!input.trim() || loading) return;
667
- const userMessage = input.trim();
668
- setInput("");
669
- setLoading(true);
670
- setMessages((prev) => [...prev, { role: "user", content: userMessage }]);
671
- try {
672
- const response = await agent.ask(userMessage);
673
- setMessages((prev) => [...prev, { role: "ai", content: response }]);
674
- } catch (err) {
675
- console.log(err);
676
- setMessages((prev) => [
677
- ...prev,
678
- { role: "ai", content: "\u26A0\uFE0F **Error:** Unable to fetch response." }
679
- ]);
680
- } finally {
681
- setLoading(false);
682
- }
683
- }
684
908
  const side = align === "right" ? { right: 24 } : { left: 24 };
685
909
  const styleTag = `
686
910
  .mcp-input:focus { outline: none; box-shadow: 0 0 0 2.5px ${t.inputFocus}33; border-color: ${t.inputFocus} !important; }
@@ -700,6 +924,8 @@ function MCPAgent(props) {
700
924
  .mcp-bubble-ai p { margin: 4px 0; }
701
925
  .mcp-bubble-ai ul, .mcp-bubble-ai ol { margin: 4px 0; padding-left: 18px; }
702
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); }
703
929
  .mcp-float-btn:hover { transform: scale(1.08); box-shadow: 0 14px 36px ${primaryColor}55 !important; }
704
930
  .mcp-float-btn:active { transform: scale(0.96); }
705
931
  `;
@@ -743,8 +969,9 @@ function MCPAgent(props) {
743
969
  position: "fixed",
744
970
  bottom: 84,
745
971
  ...side,
746
- width,
747
- height,
972
+ // never wider/taller than the viewport (phones)
973
+ width: `min(${width}px, calc(100vw - 32px))`,
974
+ height: `min(${height}px, calc(100vh - 110px))`,
748
975
  background: t.bg,
749
976
  borderRadius,
750
977
  display: "flex",
@@ -826,7 +1053,32 @@ function MCPAgent(props) {
826
1053
  ),
827
1054
  "Online"
828
1055
  ] })
829
- ] })
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
+ )
830
1082
  ]
831
1083
  }
832
1084
  ),
@@ -878,11 +1130,32 @@ function MCPAgent(props) {
878
1130
  }
879
1131
  ),
880
1132
  /* @__PURE__ */ jsx2("span", { style: { fontWeight: 600, color: t.text, fontSize: 14 }, children: "Hey there!" }),
881
- /* @__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
+ )) })
882
1155
  ]
883
1156
  }
884
1157
  ),
885
- messages.map((m, i) => {
1158
+ messages.map((m) => {
886
1159
  const isUser = m.role === "user";
887
1160
  return /* @__PURE__ */ jsx2(
888
1161
  "div",
@@ -911,10 +1184,10 @@ function MCPAgent(props) {
911
1184
  }
912
1185
  )
913
1186
  },
914
- i
1187
+ m.id
915
1188
  );
916
1189
  }),
917
- loading && /* @__PURE__ */ jsx2("div", { style: { display: "flex", justifyContent: "flex-start" }, children: /* @__PURE__ */ jsx2(
1190
+ loading && /* @__PURE__ */ jsx2("div", { style: { display: "flex", justifyContent: "flex-start" }, children: /* @__PURE__ */ jsxs2(
918
1191
  "div",
919
1192
  {
920
1193
  style: {
@@ -923,7 +1196,10 @@ function MCPAgent(props) {
923
1196
  borderRadius: "18px 18px 18px 6px",
924
1197
  boxShadow: isDark ? "0 2px 10px rgba(0,0,0,.2)" : "0 2px 10px rgba(0,0,0,.07)"
925
1198
  },
926
- children: /* @__PURE__ */ jsx2(TypingDots, { color: primaryColor })
1199
+ children: [
1200
+ /* @__PURE__ */ jsx2(TypingDots, { color: primaryColor }),
1201
+ status && /* @__PURE__ */ jsx2("span", { style: { color: t.textMuted, fontSize: 11, marginLeft: 8 }, children: status })
1202
+ ]
927
1203
  }
928
1204
  ) })
929
1205
  ]
@@ -948,7 +1224,7 @@ function MCPAgent(props) {
948
1224
  className: "mcp-input",
949
1225
  value: input,
950
1226
  onChange: (e) => setInput(e.target.value),
951
- onKeyDown: (e) => e.key === "Enter" && send(),
1227
+ onKeyDown: (e) => e.key === "Enter" && !e.nativeEvent.isComposing && send(),
952
1228
  placeholder,
953
1229
  disabled: loading,
954
1230
  style: {
@@ -1001,7 +1277,13 @@ function MCPAgent(props) {
1001
1277
  }
1002
1278
  ` })
1003
1279
  ] });
1004
- }
1280
+ });
1005
1281
  export {
1006
- MCPAgent
1282
+ ChatEngine,
1283
+ DEFAULT_SYSTEM_PROMPT,
1284
+ MCPAgent,
1285
+ PROVIDER_URLS,
1286
+ createProvider,
1287
+ endpointsFromOpenAPI,
1288
+ useChat
1007
1289
  };