prism-mcp-server 20.0.6 → 20.0.7

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.
@@ -0,0 +1,453 @@
1
+ /**
2
+ * Agent Tools — Local workspace tools for the Prism Agent Terminal
3
+ * =================================================================
4
+ *
5
+ * Provides file system, shell, and memory access tools that the AI agent
6
+ * can invoke during an interactive `prism prompt` session. These are
7
+ * declared as Gemini Function Declarations and executed locally.
8
+ *
9
+ * Mirrors the Synalux VS Code extension's local-tools.ts capabilities
10
+ * but runs in a terminal context (no VS Code API dependency).
11
+ */
12
+ import * as fs from "fs";
13
+ import * as path from "path";
14
+ import { exec } from "child_process";
15
+ import { promisify } from "util";
16
+ import { SchemaType } from "@google/generative-ai";
17
+ import { openUrlCommand, fetchUrlCommand, listFilesCommand, searchFilesCommand, resolveCli, IS_WINDOWS, } from "./platformUtils.js";
18
+ const execAsync = promisify(exec);
19
+ // ---------------------------------------------------------------------------
20
+ // Tool Declarations (Gemini Function Calling Schema)
21
+ // ---------------------------------------------------------------------------
22
+ export const AGENT_TOOL_DECLARATIONS = [
23
+ {
24
+ name: "read_file",
25
+ description: "Read the contents of a file. Use when the user asks about code, configs, or any file. Supports optional line range.",
26
+ parameters: {
27
+ type: SchemaType.OBJECT,
28
+ properties: {
29
+ path: {
30
+ type: SchemaType.STRING,
31
+ description: "Absolute or relative file path to read",
32
+ },
33
+ start_line: {
34
+ type: SchemaType.INTEGER,
35
+ description: "Optional start line (1-indexed)",
36
+ },
37
+ end_line: {
38
+ type: SchemaType.INTEGER,
39
+ description: "Optional end line (1-indexed, inclusive)",
40
+ },
41
+ },
42
+ required: ["path"],
43
+ },
44
+ },
45
+ {
46
+ name: "list_files",
47
+ description: "List files and directories. Use when the user asks about project structure or wants to find files.",
48
+ parameters: {
49
+ type: SchemaType.OBJECT,
50
+ properties: {
51
+ directory: {
52
+ type: SchemaType.STRING,
53
+ description: "Directory path to list (default: current working directory)",
54
+ },
55
+ pattern: {
56
+ type: SchemaType.STRING,
57
+ description: "Optional glob pattern filter (e.g., '**/*.ts')",
58
+ },
59
+ max_depth: {
60
+ type: SchemaType.INTEGER,
61
+ description: "Maximum directory depth to traverse (default: 3)",
62
+ },
63
+ },
64
+ },
65
+ },
66
+ {
67
+ name: "search_files",
68
+ description: "Search for text or patterns across files using ripgrep. Use when the user wants to find where something is defined or used.",
69
+ parameters: {
70
+ type: SchemaType.OBJECT,
71
+ properties: {
72
+ query: {
73
+ type: SchemaType.STRING,
74
+ description: "Text or regex pattern to search for",
75
+ },
76
+ directory: {
77
+ type: SchemaType.STRING,
78
+ description: "Directory to search in (default: cwd)",
79
+ },
80
+ file_pattern: {
81
+ type: SchemaType.STRING,
82
+ description: "Glob to filter files (e.g., '*.ts')",
83
+ },
84
+ max_results: {
85
+ type: SchemaType.INTEGER,
86
+ description: "Maximum results (default: 20)",
87
+ },
88
+ },
89
+ required: ["query"],
90
+ },
91
+ },
92
+ {
93
+ name: "run_command",
94
+ description: "Execute a shell command and return stdout/stderr. Use for running tests, builds, git commands, etc. Commands have a 30-second timeout.",
95
+ parameters: {
96
+ type: SchemaType.OBJECT,
97
+ properties: {
98
+ command: {
99
+ type: SchemaType.STRING,
100
+ description: "Shell command to execute",
101
+ },
102
+ cwd: {
103
+ type: SchemaType.STRING,
104
+ description: "Working directory (default: cwd)",
105
+ },
106
+ },
107
+ required: ["command"],
108
+ },
109
+ },
110
+ {
111
+ name: "write_file",
112
+ description: "Create or overwrite a file with the given content. Creates parent directories if needed.",
113
+ parameters: {
114
+ type: SchemaType.OBJECT,
115
+ properties: {
116
+ path: {
117
+ type: SchemaType.STRING,
118
+ description: "File path to write to",
119
+ },
120
+ content: {
121
+ type: SchemaType.STRING,
122
+ description: "Content to write",
123
+ },
124
+ },
125
+ required: ["path", "content"],
126
+ },
127
+ },
128
+ {
129
+ name: "edit_file",
130
+ description: "Apply a targeted search-and-replace edit to a file. Use instead of write_file when making small changes.",
131
+ parameters: {
132
+ type: SchemaType.OBJECT,
133
+ properties: {
134
+ path: {
135
+ type: SchemaType.STRING,
136
+ description: "File path to edit",
137
+ },
138
+ search: {
139
+ type: SchemaType.STRING,
140
+ description: "Exact text to find and replace",
141
+ },
142
+ replace: {
143
+ type: SchemaType.STRING,
144
+ description: "Replacement text",
145
+ },
146
+ },
147
+ required: ["path", "search", "replace"],
148
+ },
149
+ },
150
+ {
151
+ name: "memory_search",
152
+ description: "Search the user's Prism memory (past sessions, decisions, TODOs). Use when the user asks about previous work or project history.",
153
+ parameters: {
154
+ type: SchemaType.OBJECT,
155
+ properties: {
156
+ query: {
157
+ type: SchemaType.STRING,
158
+ description: "Search query",
159
+ },
160
+ project: {
161
+ type: SchemaType.STRING,
162
+ description: "Project to search within",
163
+ },
164
+ limit: {
165
+ type: SchemaType.INTEGER,
166
+ description: "Max results (default: 5)",
167
+ },
168
+ },
169
+ required: ["query"],
170
+ },
171
+ },
172
+ {
173
+ name: "open_url",
174
+ description: "Open a URL in the user's default browser.",
175
+ parameters: {
176
+ type: SchemaType.OBJECT,
177
+ properties: {
178
+ url: {
179
+ type: SchemaType.STRING,
180
+ description: "URL to open",
181
+ },
182
+ },
183
+ required: ["url"],
184
+ },
185
+ },
186
+ {
187
+ name: "fetch_url",
188
+ description: "Fetch the text content of a web page and return it. Use when the user wants you to read, summarize, or analyze a web page.",
189
+ parameters: {
190
+ type: SchemaType.OBJECT,
191
+ properties: {
192
+ url: {
193
+ type: SchemaType.STRING,
194
+ description: "The URL to fetch content from",
195
+ },
196
+ },
197
+ required: ["url"],
198
+ },
199
+ },
200
+ {
201
+ name: "supabase_cli",
202
+ description: "Execute Supabase CLI commands (e.g., status, diff, push, db pull). Always use this for Supabase database management.",
203
+ parameters: {
204
+ type: SchemaType.OBJECT,
205
+ properties: {
206
+ args: {
207
+ type: SchemaType.STRING,
208
+ description: 'The arguments to pass to the supabase CLI (e.g., "db pull", "status")',
209
+ },
210
+ },
211
+ required: ["args"],
212
+ },
213
+ },
214
+ {
215
+ name: "stripe_cli",
216
+ description: "Execute Stripe CLI commands (e.g., listen, trigger, login). Always use this for Stripe operations.",
217
+ parameters: {
218
+ type: SchemaType.OBJECT,
219
+ properties: {
220
+ args: {
221
+ type: SchemaType.STRING,
222
+ description: 'The arguments to pass to the stripe CLI (e.g., "listen --forward-to localhost:3000/api/webhook")',
223
+ },
224
+ },
225
+ required: ["args"],
226
+ },
227
+ },
228
+ ];
229
+ // ---------------------------------------------------------------------------
230
+ // Tool Executor
231
+ // ---------------------------------------------------------------------------
232
+ /**
233
+ * Resolve a path — if relative, resolve against cwd.
234
+ */
235
+ function resolvePath(filePath) {
236
+ if (path.isAbsolute(filePath))
237
+ return filePath;
238
+ return path.resolve(process.cwd(), filePath);
239
+ }
240
+ /**
241
+ * Execute an agent tool and return the result as a string.
242
+ */
243
+ export async function executeAgentTool(toolName, args, project) {
244
+ switch (toolName) {
245
+ // ─── read_file ─────────────────────────────────────────────
246
+ case "read_file": {
247
+ const filePath = resolvePath(args.path);
248
+ if (!fs.existsSync(filePath))
249
+ return `Error: File not found: ${filePath}`;
250
+ const content = fs.readFileSync(filePath, "utf-8");
251
+ const lines = content.split("\n");
252
+ const start = Math.max(1, args.start_line || 1);
253
+ const end = Math.min(lines.length, args.end_line || lines.length);
254
+ const slice = lines.slice(start - 1, end);
255
+ // Add line numbers
256
+ const numbered = slice.map((l, i) => `${start + i}: ${l}`).join("\n");
257
+ return `File: ${filePath} (${lines.length} lines total, showing ${start}-${end})\n\n${numbered}`;
258
+ }
259
+ // ─── list_files ────────────────────────────────────────────
260
+ case "list_files": {
261
+ const dir = resolvePath(args.directory || ".");
262
+ if (!fs.existsSync(dir))
263
+ return `Error: Directory not found: ${dir}`;
264
+ const maxDepth = args.max_depth || 3;
265
+ const pattern = args.pattern;
266
+ const cmd = listFilesCommand(dir, maxDepth, pattern);
267
+ try {
268
+ const { stdout } = await execAsync(cmd, { timeout: 10000, shell: IS_WINDOWS ? "powershell.exe" : undefined });
269
+ const entries = stdout.trim().split("\n").filter(Boolean);
270
+ return `Directory: ${dir}\n${entries.length} items found:\n\n${entries.join("\n")}`;
271
+ }
272
+ catch {
273
+ // Fallback to Node.js readdir
274
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
275
+ const lines = entries
276
+ .slice(0, 50)
277
+ .map((e) => `${e.isDirectory() ? "📁" : "📄"} ${e.name}`);
278
+ return `Directory: ${dir}\n${lines.join("\n")}`;
279
+ }
280
+ }
281
+ // ─── search_files ──────────────────────────────────────────
282
+ case "search_files": {
283
+ const query = args.query;
284
+ const dir = resolvePath(args.directory || ".");
285
+ const maxResults = args.max_results || 20;
286
+ const filePattern = args.file_pattern;
287
+ const cmd = searchFilesCommand(query, dir, maxResults, filePattern);
288
+ try {
289
+ const { stdout } = await execAsync(cmd, { timeout: 15000 });
290
+ if (!stdout.trim())
291
+ return `No matches found for "${query}" in ${dir}`;
292
+ return `Search: "${query}" in ${dir}\n\n${stdout.trim()}`;
293
+ }
294
+ catch {
295
+ return `No matches found for "${query}" in ${dir}`;
296
+ }
297
+ }
298
+ // ─── run_command ───────────────────────────────────────────
299
+ case "run_command": {
300
+ const command = args.command;
301
+ const cwd = resolvePath(args.cwd || ".");
302
+ // Safety: block obviously dangerous commands
303
+ const blocked = ["rm -rf /", "mkfs", "dd if=", ":(){"];
304
+ if (blocked.some((b) => command.includes(b))) {
305
+ return "Error: Command blocked for safety reasons.";
306
+ }
307
+ try {
308
+ const { stdout, stderr } = await execAsync(command, {
309
+ cwd,
310
+ timeout: 30000,
311
+ maxBuffer: 1024 * 1024,
312
+ env: { ...process.env, PAGER: "cat" },
313
+ });
314
+ let result = "";
315
+ if (stdout.trim())
316
+ result += `stdout:\n${stdout.trim()}\n`;
317
+ if (stderr.trim())
318
+ result += `stderr:\n${stderr.trim()}\n`;
319
+ if (!result)
320
+ result = "(command completed with no output)";
321
+ return result;
322
+ }
323
+ catch (err) {
324
+ const e = err;
325
+ let msg = `Command failed: ${command}\n`;
326
+ if (e.stdout)
327
+ msg += `stdout:\n${e.stdout}\n`;
328
+ if (e.stderr)
329
+ msg += `stderr:\n${e.stderr}\n`;
330
+ if (e.message && !e.stderr)
331
+ msg += `error: ${e.message}`;
332
+ return msg;
333
+ }
334
+ }
335
+ // ─── write_file ────────────────────────────────────────────
336
+ case "write_file": {
337
+ const filePath = resolvePath(args.path);
338
+ const content = args.content;
339
+ // Create parent dirs
340
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
341
+ fs.writeFileSync(filePath, content, "utf-8");
342
+ return `✅ Written ${content.length} chars to ${filePath}`;
343
+ }
344
+ // ─── edit_file ─────────────────────────────────────────────
345
+ case "edit_file": {
346
+ const filePath = resolvePath(args.path);
347
+ if (!fs.existsSync(filePath))
348
+ return `Error: File not found: ${filePath}`;
349
+ const original = fs.readFileSync(filePath, "utf-8");
350
+ const search = args.search;
351
+ const replace = args.replace;
352
+ if (!original.includes(search)) {
353
+ return `Error: Search text not found in ${filePath}`;
354
+ }
355
+ const updated = original.replace(search, replace);
356
+ fs.writeFileSync(filePath, updated, "utf-8");
357
+ return `✅ Edited ${filePath} — replaced ${search.length} chars`;
358
+ }
359
+ // ─── memory_search ─────────────────────────────────────────
360
+ case "memory_search": {
361
+ const { knowledgeSearchHandler } = await import("../tools/graphHandlers.js");
362
+ const result = await knowledgeSearchHandler({
363
+ query: args.query,
364
+ project: args.project || project || "prism-mcp",
365
+ limit: args.limit || 5,
366
+ });
367
+ const text = result.content?.[0] && "text" in result.content[0]
368
+ ? result.content[0].text
369
+ : "No results found.";
370
+ return text;
371
+ }
372
+ // ─── open_url ──────────────────────────────────────────────
373
+ case "open_url": {
374
+ const url = args.url;
375
+ try {
376
+ await execAsync(openUrlCommand(url));
377
+ return `✅ Opened ${url} in default browser`;
378
+ }
379
+ catch {
380
+ return `Error: Failed to open ${url}`;
381
+ }
382
+ }
383
+ // ─── fetch_url ─────────────────────────────────────────────
384
+ case "fetch_url": {
385
+ const fetchUrl = args.url;
386
+ if (!fetchUrl?.match(/^https?:\/\//i)) {
387
+ return "Error: Invalid URL. Must start with http:// or https://";
388
+ }
389
+ try {
390
+ const cmd = fetchUrlCommand(fetchUrl);
391
+ const { stdout } = await execAsync(cmd, {
392
+ timeout: 20000,
393
+ maxBuffer: 1024 * 1024,
394
+ shell: IS_WINDOWS ? "powershell.exe" : undefined,
395
+ });
396
+ const text = stdout.trim().slice(0, 8000);
397
+ return `Content from ${fetchUrl}:\n\n${text}${text.length >= 8000 ? "\n\n... (truncated)" : ""}`;
398
+ }
399
+ catch (err) {
400
+ const e = err;
401
+ return `Error: Failed to fetch ${fetchUrl} — ${e.message?.slice(0, 200) || "unknown error"}`;
402
+ }
403
+ }
404
+ // ─── supabase_cli ──────────────────────────────────────────
405
+ case "supabase_cli": {
406
+ const sbArgs = args.args;
407
+ const sbBin = resolveCli("supabase");
408
+ try {
409
+ const { stdout } = await execAsync(`${sbBin} ${sbArgs}`, {
410
+ cwd: process.cwd(),
411
+ timeout: 60000,
412
+ maxBuffer: 1024 * 512,
413
+ env: { ...process.env, PAGER: "cat" },
414
+ });
415
+ return `supabase ${sbArgs}:\n${stdout.trim().slice(0, 5000)}`;
416
+ }
417
+ catch (err) {
418
+ const e = err;
419
+ let msg = `supabase ${sbArgs} failed:\n`;
420
+ if (e.stdout)
421
+ msg += e.stdout.slice(0, 3000);
422
+ if (e.stderr)
423
+ msg += `\nstderr: ${e.stderr.slice(0, 1000)}`;
424
+ return msg;
425
+ }
426
+ }
427
+ // ─── stripe_cli ───────────────────────────────────────────
428
+ case "stripe_cli": {
429
+ const stripeArgs = args.args;
430
+ const stripeBin = resolveCli("stripe");
431
+ try {
432
+ const { stdout } = await execAsync(`${stripeBin} ${stripeArgs}`, {
433
+ cwd: process.cwd(),
434
+ timeout: 60000,
435
+ maxBuffer: 1024 * 512,
436
+ env: { ...process.env, PAGER: "cat" },
437
+ });
438
+ return `stripe ${stripeArgs}:\n${stdout.trim().slice(0, 5000)}`;
439
+ }
440
+ catch (err) {
441
+ const e = err;
442
+ let msg = `stripe ${stripeArgs} failed:\n`;
443
+ if (e.stdout)
444
+ msg += e.stdout.slice(0, 3000);
445
+ if (e.stderr)
446
+ msg += `\nstderr: ${e.stderr.slice(0, 1000)}`;
447
+ return msg;
448
+ }
449
+ }
450
+ default:
451
+ return `Error: Unknown tool \"${toolName}\"`;
452
+ }
453
+ }
@@ -0,0 +1,234 @@
1
+ /**
2
+ * MCP Bridge — Connect external MCP servers to the Prism Agent Terminal
3
+ * ======================================================================
4
+ *
5
+ * Allows `prism prompt` to discover and connect to MCP servers configured
6
+ * in standard config files (.cursor/mcp.json, .vscode/mcp.json) or via
7
+ * manual `prism prompt --mcp <command>`.
8
+ *
9
+ * Connected MCP server tools are automatically injected into Gemini's
10
+ * function declarations so the AI can call them during conversation.
11
+ *
12
+ * Config format (standard MCP convention):
13
+ * ```json
14
+ * {
15
+ * "mcpServers": {
16
+ * "my-server": {
17
+ * "command": "node",
18
+ * "args": ["path/to/server.js"],
19
+ * "env": { "API_KEY": "..." }
20
+ * }
21
+ * }
22
+ * }
23
+ * ```
24
+ */
25
+ import * as fs from "fs";
26
+ import * as path from "path";
27
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
28
+ import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
29
+ import { SchemaType } from "@google/generative-ai";
30
+ // ---------------------------------------------------------------------------
31
+ // MCP Bridge
32
+ // ---------------------------------------------------------------------------
33
+ export class McpBridge {
34
+ connections = new Map();
35
+ /**
36
+ * Connect to an MCP server via stdio.
37
+ */
38
+ async connect(serverName, config) {
39
+ // Don't double-connect
40
+ if (this.connections.has(serverName)) {
41
+ const existing = this.connections.get(serverName);
42
+ return existing.tools;
43
+ }
44
+ const client = new Client({ name: "prism-agent", version: "12.0.0" }, { capabilities: {} });
45
+ const transport = new StdioClientTransport({
46
+ command: config.command,
47
+ args: config.args || [],
48
+ env: { ...process.env, ...(config.env || {}) },
49
+ });
50
+ await client.connect(transport);
51
+ // Discover tools
52
+ const toolsResult = await client.listTools();
53
+ const tools = toolsResult.tools.map((t) => ({
54
+ name: t.name,
55
+ description: t.description || "",
56
+ inputSchema: t.inputSchema,
57
+ }));
58
+ this.connections.set(serverName, { name: serverName, client, transport, tools });
59
+ return tools;
60
+ }
61
+ /**
62
+ * Call a tool on a connected MCP server.
63
+ */
64
+ async callTool(toolName, args) {
65
+ // Find which server owns this tool
66
+ for (const conn of this.connections.values()) {
67
+ const tool = conn.tools.find((t) => t.name === toolName);
68
+ if (!tool)
69
+ continue;
70
+ const result = await conn.client.callTool({
71
+ name: toolName,
72
+ arguments: args,
73
+ });
74
+ if (result.isError) {
75
+ const errText = result.content
76
+ .filter((c) => c.type === "text")
77
+ .map((c) => c.text)
78
+ .join("\n");
79
+ return `Error: ${errText || "Tool returned an error"}`;
80
+ }
81
+ // Extract text content
82
+ const texts = result.content
83
+ .filter((c) => c.type === "text")
84
+ .map((c) => c.text || "");
85
+ return texts.join("\n") || "(no output)";
86
+ }
87
+ return `Error: No MCP server has tool "${toolName}"`;
88
+ }
89
+ /**
90
+ * Get all tools from all connected servers as Gemini FunctionDeclarations.
91
+ * Prefixes tool names with server name to avoid collisions.
92
+ */
93
+ getGeminiFunctionDeclarations() {
94
+ const declarations = [];
95
+ for (const conn of this.connections.values()) {
96
+ for (const tool of conn.tools) {
97
+ // Convert JSON Schema to Gemini's FunctionDeclaration format
98
+ declarations.push({
99
+ name: tool.name,
100
+ description: `[MCP:${conn.name}] ${tool.description}`,
101
+ parameters: convertJsonSchemaToGemini(tool.inputSchema),
102
+ });
103
+ }
104
+ }
105
+ return declarations;
106
+ }
107
+ /**
108
+ * Check if a tool name belongs to an MCP server.
109
+ */
110
+ hasToolName(toolName) {
111
+ for (const conn of this.connections.values()) {
112
+ if (conn.tools.some((t) => t.name === toolName))
113
+ return true;
114
+ }
115
+ return false;
116
+ }
117
+ /**
118
+ * List all connected servers and their tools.
119
+ */
120
+ listServers() {
121
+ return Array.from(this.connections.values()).map((c) => ({
122
+ name: c.name,
123
+ toolCount: c.tools.length,
124
+ tools: c.tools.map((t) => t.name),
125
+ }));
126
+ }
127
+ /**
128
+ * Disconnect all servers gracefully.
129
+ */
130
+ async disconnectAll() {
131
+ for (const conn of this.connections.values()) {
132
+ try {
133
+ await conn.client.close();
134
+ }
135
+ catch {
136
+ // Ignore cleanup errors
137
+ }
138
+ }
139
+ this.connections.clear();
140
+ }
141
+ }
142
+ // ---------------------------------------------------------------------------
143
+ // Config Discovery
144
+ // ---------------------------------------------------------------------------
145
+ /**
146
+ * Search for MCP server configurations in standard locations.
147
+ * Returns merged config from all discovered files.
148
+ */
149
+ export function discoverMcpConfigs(cwd = process.cwd()) {
150
+ const configs = {};
151
+ // Search paths in order of priority (later overrides earlier)
152
+ const searchPaths = [
153
+ // Global configs
154
+ path.join(process.env.HOME || "~", ".cursor", "mcp.json"),
155
+ path.join(process.env.HOME || "~", ".vscode", "mcp.json"),
156
+ // Project-level configs (higher priority)
157
+ path.join(cwd, ".cursor", "mcp.json"),
158
+ path.join(cwd, ".vscode", "mcp.json"),
159
+ path.join(cwd, "mcp.json"),
160
+ ];
161
+ for (const configPath of searchPaths) {
162
+ try {
163
+ if (!fs.existsSync(configPath))
164
+ continue;
165
+ const raw = fs.readFileSync(configPath, "utf-8");
166
+ const parsed = JSON.parse(raw);
167
+ // Support both { mcpServers: {...} } and { servers: {...} } formats
168
+ const servers = parsed.mcpServers || parsed.servers || {};
169
+ for (const [name, config] of Object.entries(servers)) {
170
+ const c = config;
171
+ if (c.command) {
172
+ configs[name] = c;
173
+ }
174
+ }
175
+ }
176
+ catch {
177
+ // Skip invalid config files
178
+ }
179
+ }
180
+ return configs;
181
+ }
182
+ // ---------------------------------------------------------------------------
183
+ // Schema Conversion
184
+ // ---------------------------------------------------------------------------
185
+ /**
186
+ * Convert a JSON Schema object to Gemini's FunctionDeclaration parameters format.
187
+ * Gemini uses its own SchemaType enum instead of standard JSON Schema type strings.
188
+ */
189
+ function convertJsonSchemaToGemini(schema) {
190
+ if (!schema || typeof schema !== "object") {
191
+ return { type: SchemaType.OBJECT, properties: {} };
192
+ }
193
+ const properties = {};
194
+ const schemaProps = (schema.properties || {});
195
+ for (const [key, prop] of Object.entries(schemaProps)) {
196
+ properties[key] = convertPropertyToGemini(prop);
197
+ }
198
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- dynamic JSON Schema conversion
199
+ return {
200
+ type: SchemaType.OBJECT,
201
+ properties,
202
+ required: schema.required || [],
203
+ };
204
+ }
205
+ function convertPropertyToGemini(prop) {
206
+ const typeMap = {
207
+ string: SchemaType.STRING,
208
+ number: SchemaType.NUMBER,
209
+ integer: SchemaType.INTEGER,
210
+ boolean: SchemaType.BOOLEAN,
211
+ array: SchemaType.ARRAY,
212
+ object: SchemaType.OBJECT,
213
+ };
214
+ const result = {
215
+ type: typeMap[prop.type] || SchemaType.STRING,
216
+ };
217
+ if (prop.description)
218
+ result.description = prop.description;
219
+ if (prop.enum)
220
+ result.enum = prop.enum;
221
+ // Handle array items
222
+ if (prop.type === "array" && prop.items) {
223
+ result.items = convertPropertyToGemini(prop.items);
224
+ }
225
+ // Handle nested objects
226
+ if (prop.type === "object" && prop.properties) {
227
+ const nestedProps = {};
228
+ for (const [k, v] of Object.entries(prop.properties)) {
229
+ nestedProps[k] = convertPropertyToGemini(v);
230
+ }
231
+ result.properties = nestedProps;
232
+ }
233
+ return result;
234
+ }