@datagrok/grokky 1.0.4

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.
Files changed (65) hide show
  1. package/.eslintignore +2 -0
  2. package/.eslintrc.json +48 -0
  3. package/CHANGELOG.md +26 -0
  4. package/README.md +3 -0
  5. package/css/ai.css +200 -0
  6. package/detectors.js +9 -0
  7. package/dist/package-test.js +1738 -0
  8. package/dist/package-test.js.map +1 -0
  9. package/dist/package.js +92488 -0
  10. package/dist/package.js.map +1 -0
  11. package/dockerfiles/claude-runtime/.dockerignore +4 -0
  12. package/dockerfiles/claude-runtime/Dockerfile +27 -0
  13. package/dockerfiles/claude-runtime/container.json +5 -0
  14. package/dockerfiles/claude-runtime/package-lock.json +448 -0
  15. package/dockerfiles/claude-runtime/package.json +20 -0
  16. package/dockerfiles/claude-runtime/src/server.ts +273 -0
  17. package/dockerfiles/claude-runtime/src/types.ts +37 -0
  18. package/dockerfiles/claude-runtime/tsconfig.json +15 -0
  19. package/dockerfiles/mcp-server/Dockerfile +12 -0
  20. package/dockerfiles/mcp-server/container.json +1 -0
  21. package/dockerfiles/mcp-server/package-lock.json +1178 -0
  22. package/dockerfiles/mcp-server/package.json +15 -0
  23. package/dockerfiles/mcp-server/src/api-client.ts +100 -0
  24. package/dockerfiles/mcp-server/src/index.ts +155 -0
  25. package/dockerfiles/mcp-server/tsconfig.json +13 -0
  26. package/package.json +126 -0
  27. package/package.png +0 -0
  28. package/src/ai-panel.ts +174 -0
  29. package/src/claude-code/claude-panel.ts +34 -0
  30. package/src/claude-code/claude-runtime-client.ts +148 -0
  31. package/src/llm-utils/LLM-client.ts +251 -0
  32. package/src/llm-utils/combined-search.ts +162 -0
  33. package/src/llm-utils/creds.ts +30 -0
  34. package/src/llm-utils/db-index-tools.ts +642 -0
  35. package/src/llm-utils/deepwikiclient.ts +118 -0
  36. package/src/llm-utils/depr/AI-API-providers/openai-chat-completions-provider.ts +115 -0
  37. package/src/llm-utils/depr/AI-API-providers/openai-responses-provider.ts +108 -0
  38. package/src/llm-utils/depr/AI-API-providers/types.ts +106 -0
  39. package/src/llm-utils/depr/depr.ts +235 -0
  40. package/src/llm-utils/depr/embeddings.ts +58 -0
  41. package/src/llm-utils/depr/sql-utils.ts +377 -0
  42. package/src/llm-utils/indexes/biologics-index.ts +1098 -0
  43. package/src/llm-utils/indexes/chembl-index.ts +10074 -0
  44. package/src/llm-utils/indexes/dg-repository-index.ts +266 -0
  45. package/src/llm-utils/panel.ts +866 -0
  46. package/src/llm-utils/query-matching.ts +370 -0
  47. package/src/llm-utils/query-meta-utils.ts +106 -0
  48. package/src/llm-utils/script-tools.ts +784 -0
  49. package/src/llm-utils/sql-tools.ts +840 -0
  50. package/src/llm-utils/storage.ts +201 -0
  51. package/src/llm-utils/tableview-tools.ts +704 -0
  52. package/src/llm-utils/ui.ts +315 -0
  53. package/src/package-api.ts +83 -0
  54. package/src/package-test.ts +16 -0
  55. package/src/package.g.ts +122 -0
  56. package/src/package.ts +275 -0
  57. package/src/prompt-engine/chatgpt-assistant.ts +257 -0
  58. package/src/prompt-engine/interfaces.ts +170 -0
  59. package/src/prompt-engine/prompt-engine.ts +52 -0
  60. package/src/prompt-engine/rendering-tools.ts +103 -0
  61. package/src/prompts/is-help-request.ts +26 -0
  62. package/src/utils.ts +174 -0
  63. package/src/viewers-ai.ts +67 -0
  64. package/tsconfig.json +72 -0
  65. package/webpack.config.js +49 -0
@@ -0,0 +1,118 @@
1
+ /* eslint-disable max-len */
2
+ import {Client} from '@modelcontextprotocol/sdk/client/index.js';
3
+ import {SSEClientTransport} from '@modelcontextprotocol/sdk/client/sse';
4
+
5
+ interface DeepWikiClientConfig {
6
+ repository: string;
7
+ openaiApiKey: string;
8
+ openaiModel?: string;
9
+ }
10
+
11
+ export const helpAIName = 'WIKITOR GROKOWSKY';
12
+
13
+ class DeepWikiMCPClient {
14
+ private mcpClient: Client;
15
+ private transport: SSEClientTransport | null = null;
16
+ private readonly askTool = {
17
+ name: 'ask_question',
18
+ description: 'Ask a question about the repository and get an answer based on its documentation.',
19
+ };
20
+ private static _instance: DeepWikiMCPClient | null = null;
21
+ static getInstance(repo?: string): DeepWikiMCPClient {
22
+ DeepWikiMCPClient._instance ??= new DeepWikiMCPClient(repo);
23
+ return DeepWikiMCPClient._instance;
24
+ }
25
+ private constructor(private repoName: string = 'datagrok-ai/public') {
26
+ this.mcpClient = new Client(
27
+ {
28
+ name: 'deepwiki-GROKOWSKY-client',
29
+ version: '1.0.0',
30
+ },
31
+ {
32
+ capabilities: {},
33
+ }
34
+ );
35
+ }
36
+
37
+ async connect(): Promise<void> {
38
+ if (this.transport) {
39
+ console.log('Already connected to MCP server');
40
+ return;
41
+ }
42
+ console.log('Connecting to DeepWiki MCP server...');
43
+
44
+ // Connect to DeepWiki's free mcp endpoint
45
+ this.transport = new SSEClientTransport(
46
+ new URL('https://mcp.deepwiki.com/mcp')
47
+ );
48
+
49
+ await this.mcpClient.connect(this.transport);
50
+ }
51
+
52
+ async disconnect(): Promise<void> {
53
+ if (this.transport) {
54
+ await this.transport.close();
55
+ console.log('\n✓ Disconnected from DeepWiki MCP server');
56
+ }
57
+ }
58
+
59
+ async askDeepWiki(question: string): Promise<string> {
60
+ if (!this.transport)
61
+ throw new Error('Not connected to MCP server. Call connect() first.');
62
+
63
+
64
+ const q = `You are a helpful assistant with access to documentation for the ${this.repoName} GitHub repository.
65
+
66
+ VERY IMPORTANT TO REMEMER!!!: you are a UI side assistant for Datagrok platform users, so when asked about how to do something in Datagrok, try to answer with UI in mind and also the code.
67
+
68
+ Make sure the output is nicely formatted with markdown syntax where applicable.
69
+
70
+ Do not repeat the question in your answer, and do not include the deepwiki links!!!.
71
+
72
+ user: ${question}
73
+ `;
74
+ // just call the ask tool directly
75
+ const toolArgs = {
76
+ repoName: this.repoName,
77
+ repository: this.repoName,
78
+ question: q,
79
+ };
80
+
81
+ const result = await this.mcpClient.callTool({
82
+ name: this.askTool.name,
83
+ arguments: toolArgs,
84
+ });
85
+
86
+ const contentArray = Array.isArray(result.content) ? result.content : [];
87
+ const toolResult = contentArray
88
+ .filter((item: any) => item.type === 'text')
89
+ .map((item: any) => item.text || '')
90
+ .join('\n');
91
+ if (!toolResult || toolResult.length === 0)
92
+ return 'No response generated.';
93
+
94
+ // remove deepwiki links from the answer
95
+ const lines = toolResult.split('\n').filter((line) => !line.includes('deepwiki.com')).join('\n');
96
+ return lines;
97
+ }
98
+ }
99
+
100
+ // Example usage
101
+ export async function askDeepWiki(question: string) {
102
+ const client = DeepWikiMCPClient.getInstance('datagrok-ai/public');
103
+
104
+ try {
105
+ await client.connect();
106
+
107
+ const response = await client.askDeepWiki(
108
+ question
109
+ );
110
+
111
+ return response;
112
+ } catch (error) {
113
+ console.error('Error:', error);
114
+ return `Error: ${error}`;
115
+ }
116
+ }
117
+
118
+
@@ -0,0 +1,115 @@
1
+ // /* eslint-disable max-len */
2
+ // import type OpenAI from 'openai';
3
+ // import type {ChatModel} from 'openai/resources/shared';
4
+ // import type {
5
+ // AIAPIProvider,
6
+ // AIProviderRequest,
7
+ // AIProviderResult,
8
+ // AIProviderToolCall,
9
+ // ToolSpec,
10
+ // } from './types';
11
+ // import type {MessageType} from '../panel';
12
+
13
+ // type ChatCreateBody = OpenAI.Chat.ChatCompletionCreateParamsNonStreaming;
14
+ // export type OpenAIChatTool = Exclude<ChatCreateBody['tools'], undefined>[number];
15
+ // export type OpenAIChatMessage = OpenAI.Chat.ChatCompletionMessageParam;
16
+
17
+ // export class OpenAIChatCompletionsProvider
18
+ // implements AIAPIProvider<
19
+ // ChatModel,
20
+ // MessageType,
21
+ // ToolSpec,
22
+ // OpenAI.Chat.ChatCompletion,
23
+ // ChatCreateBody['tool_choice'],
24
+ // ChatCreateBody['response_format'],
25
+ // Partial<ChatCreateBody>
26
+ // > {
27
+ // readonly endpoint = 'openai.chat.completions' as const;
28
+
29
+ // constructor(private readonly openai: OpenAI) {}
30
+
31
+ // createSystemMessage(content: string): MessageType {
32
+ // return {role: 'system', content} as OpenAI.Chat.ChatCompletionMessageParam;
33
+ // }
34
+
35
+ // createUserMessage(content: string): MessageType {
36
+ // return {role: 'user', content} as OpenAI.Chat.ChatCompletionMessageParam;
37
+ // }
38
+
39
+ // createToolOutputMessage(callId: string, output: string): MessageType {
40
+ // return {role: 'tool', tool_call_id: callId, content: output} as OpenAI.Chat.ChatCompletionToolMessageParam;
41
+ // }
42
+
43
+ // async create(
44
+ // request: AIProviderRequest<
45
+ // ChatModel,
46
+ // MessageType,
47
+ // ToolSpec,
48
+ // ChatCreateBody['tool_choice'],
49
+ // ChatCreateBody['response_format'],
50
+ // Partial<ChatCreateBody>
51
+ // >
52
+ // ): Promise<AIProviderResult<MessageType, OpenAI.Chat.ChatCompletion>> {
53
+ // const tools = request.tools?.map((tool) => {
54
+ // if (tool.type !== 'function')
55
+ // throw new Error(`Chat Completions does not support tool type: ${tool.type}`);
56
+ // return {
57
+ // type: 'function',
58
+ // function: {
59
+ // name: tool.name,
60
+ // description: tool.description,
61
+ // parameters: tool.parameters,
62
+ // strict: tool.strict,
63
+ // },
64
+ // } as OpenAIChatTool;
65
+ // });
66
+
67
+ // const body: ChatCreateBody = {
68
+ // model: request.model,
69
+ // messages: request.messages as OpenAIChatMessage[],
70
+ // ...(tools ? {tools} : {}),
71
+ // ...(request.toolChoice ? {tool_choice: request.toolChoice as ChatCreateBody['tool_choice']} : {}),
72
+ // ...(typeof request.temperature === 'number' ? {temperature: request.temperature} : {}),
73
+ // ...(typeof request.maxOutputTokens === 'number' ? {max_completion_tokens: request.maxOutputTokens} : {}),
74
+ // ...(request.reasoning?.effort ? {reasoning_effort: request.reasoning.effort} : {}),
75
+ // ...(request.responseFormat ? {response_format: request.responseFormat as ChatCreateBody['response_format']} : {}),
76
+ // ...(request.extra ?? {}),
77
+ // stream: false,
78
+ // };
79
+
80
+ // const response = await this.openai.chat.completions.create(body);
81
+
82
+ // const outputMessages = response.choices.map((choice: OpenAI.Chat.ChatCompletion.Choice) => choice.message);
83
+ // const toolCalls: AIProviderToolCall[] = [];
84
+
85
+ // for (const message of outputMessages) {
86
+ // if (!message || typeof message !== 'object')
87
+ // continue;
88
+ // const calls = (message as OpenAI.Chat.ChatCompletionMessage).tool_calls;
89
+ // if (Array.isArray(calls)) {
90
+ // for (const call of calls) {
91
+ // if (call.type === 'function') {
92
+ // const id = call.id ?? '';
93
+ // const name = call.function?.name ?? '';
94
+ // const args = call.function?.arguments ?? '{}';
95
+ // toolCalls.push({id, type: 'function', name, arguments: args});
96
+ // }
97
+ // }
98
+ // }
99
+ // }
100
+
101
+ // const firstContent = outputMessages.find((m: OpenAI.Chat.ChatCompletionMessage) => typeof m?.content === 'string')?.content ?? '';
102
+
103
+ // return {
104
+ // raw: response,
105
+ // outputText: firstContent.trim(),
106
+ // outputMessages: outputMessages as MessageType[],
107
+ // toolCalls,
108
+ // usage: response.usage ? {
109
+ // inputTokens: response.usage.prompt_tokens ?? undefined,
110
+ // outputTokens: response.usage.completion_tokens ?? undefined,
111
+ // totalTokens: response.usage.total_tokens ?? undefined,
112
+ // } : undefined,
113
+ // };
114
+ // }
115
+ // }
@@ -0,0 +1,108 @@
1
+ // /* eslint-disable max-len */
2
+ // import type OpenAI from 'openai';
3
+ // import type {ChatModel} from 'openai/resources/shared';
4
+ // import type {
5
+ // AIAPIProvider,
6
+ // AIProviderRequest,
7
+ // AIProviderResult,
8
+ // AIProviderToolCall,
9
+ // ToolSpec,
10
+ // } from './types';
11
+ // import type {MessageType} from '../panel';
12
+
13
+ // function isObjectRecord(value: object | null | undefined): value is Record<string, string | number | boolean | null | object> {
14
+ // return !!value && typeof value === 'object';
15
+ // }
16
+
17
+ // type ResponseCreateBody = OpenAI.Responses.ResponseCreateParamsNonStreaming;
18
+ // export type OpenAIResponsesTool = Exclude<ResponseCreateBody['tools'], undefined>[number];
19
+ // export type OpenAIResponsesInput = Exclude<ResponseCreateBody['input'], string | undefined>;
20
+ // export type OpenAIResponsesOutput = OpenAI.Responses.ResponseOutputItem;
21
+
22
+ // export class OpenAIResponsesProvider
23
+ // implements AIAPIProvider<
24
+ // ChatModel,
25
+ // MessageType,
26
+ // ToolSpec,
27
+ // OpenAI.Responses.Response,
28
+ // ResponseCreateBody['tool_choice'],
29
+ // OpenAI.Responses.ResponseTextConfig | OpenAI.Responses.ResponseTextConfig['format'],
30
+ // Partial<ResponseCreateBody>
31
+ // > {
32
+ // readonly endpoint = 'openai.responses' as const;
33
+
34
+ // constructor(private readonly openai: OpenAI) {}
35
+
36
+ // createSystemMessage(content: string): MessageType {
37
+ // return {role: 'system', content} as OpenAI.Responses.ResponseInputItem;
38
+ // }
39
+
40
+ // createUserMessage(content: string): MessageType {
41
+ // return {role: 'user', content} as OpenAI.Responses.ResponseInputItem;
42
+ // }
43
+
44
+ // createToolOutputMessage(callId: string, output: string): MessageType {
45
+ // return {type: 'function_call_output', call_id: callId, output} as OpenAI.Responses.ResponseInputItem;
46
+ // }
47
+
48
+ // async create(
49
+ // request: AIProviderRequest<
50
+ // ChatModel,
51
+ // MessageType,
52
+ // ToolSpec,
53
+ // ResponseCreateBody['tool_choice'],
54
+ // OpenAI.Responses.ResponseTextConfig | OpenAI.Responses.ResponseTextConfig['format'],
55
+ // Partial<ResponseCreateBody>
56
+ // >
57
+ // ): Promise<AIProviderResult<MessageType, OpenAI.Responses.Response>> {
58
+ // const textConfig = request.responseFormat as
59
+ // | OpenAI.Responses.ResponseTextConfig
60
+ // | OpenAI.Responses.ResponseTextConfig['format']
61
+ // | undefined;
62
+
63
+ // const body: ResponseCreateBody = {
64
+ // model: request.model,
65
+ // input: request.messages as OpenAIResponsesInput,
66
+ // ...(request.tools ? {tools: request.tools} : {}),
67
+ // ...(request.toolChoice ? {tool_choice: request.toolChoice as ResponseCreateBody['tool_choice']} : {}),
68
+ // ...(typeof request.temperature === 'number' ? {temperature: request.temperature} : {}),
69
+ // ...(typeof request.maxOutputTokens === 'number' ? {max_output_tokens: request.maxOutputTokens} : {}),
70
+ // ...(request.reasoning ? {reasoning: request.reasoning as ResponseCreateBody['reasoning']} : {}),
71
+ // ...(request.extra ?? {}),
72
+ // stream: false,
73
+ // };
74
+
75
+ // if (textConfig) {
76
+ // if (isObjectRecord(textConfig) && ('format' in textConfig || 'verbosity' in textConfig))
77
+ // body.text = textConfig as OpenAI.Responses.ResponseTextConfig;
78
+ // else
79
+ // body.text = {format: textConfig as OpenAI.Responses.ResponseTextConfig['format']};
80
+ // }
81
+
82
+ // const response = await this.openai.responses.create(body);
83
+
84
+ // const outputItems = response.output ?? [];
85
+ // const toolCalls: AIProviderToolCall[] = [];
86
+
87
+ // for (const item of outputItems) {
88
+ // if (item.type === 'function_call') {
89
+ // const id = typeof item.call_id === 'string' ? item.call_id : '';
90
+ // const name = typeof item.name === 'string' ? item.name : '';
91
+ // const args = typeof item.arguments === 'string' ? item.arguments : '{}';
92
+ // toolCalls.push({id, type: 'function', name, arguments: args});
93
+ // }
94
+ // }
95
+
96
+ // return {
97
+ // raw: response,
98
+ // outputText: (response.output_text ?? '').trim(),
99
+ // outputMessages: outputItems as MessageType[],
100
+ // toolCalls,
101
+ // usage: response.usage ? {
102
+ // inputTokens: response.usage.input_tokens ?? undefined,
103
+ // outputTokens: response.usage.output_tokens ?? undefined,
104
+ // totalTokens: response.usage.total_tokens ?? undefined,
105
+ // } : undefined,
106
+ // };
107
+ // }
108
+ // }
@@ -0,0 +1,106 @@
1
+ // /* eslint-disable max-len */
2
+
3
+ // export type AIProviderEndpoint =
4
+ // | 'openai.responses'
5
+ // | 'openai.chat.completions';
6
+
7
+ // export type AIProviderToolCall = {
8
+ // id: string;
9
+ // type: 'function';
10
+ // name: string;
11
+ // arguments: string;
12
+ // };
13
+
14
+ // export type AIProviderUsage = {
15
+ // inputTokens?: number;
16
+ // outputTokens?: number;
17
+ // totalTokens?: number;
18
+ // };
19
+
20
+ // export type AIProviderReasoning = {
21
+ // effort?: 'low' | 'medium' | 'high';
22
+ // };
23
+
24
+ // export type EmptyObject = Record<string, never>;
25
+
26
+ // export type JsonSchema = {
27
+ // type: 'string' | 'array' | 'object' | 'number' | 'integer' | 'boolean';
28
+ // description?: string;
29
+ // items?: JsonSchema;
30
+ // properties?: Record<string, JsonSchema>;
31
+ // required?: string[];
32
+ // additionalProperties?: boolean | JsonSchema;
33
+ // patternProperties?: Record<string, JsonSchema>;
34
+ // default?: string | number | boolean | null;
35
+ // };
36
+
37
+ // export type FunctionToolSpec = {
38
+ // type: 'function';
39
+ // name: string;
40
+ // description: string;
41
+ // parameters: JsonSchema;
42
+ // strict: true;
43
+ // };
44
+
45
+ // export type BuiltinToolSpec = {
46
+ // type: 'file_search';
47
+ // vector_store_ids: string[];
48
+ // };
49
+
50
+ // export type ToolSpec = FunctionToolSpec | BuiltinToolSpec;
51
+
52
+ // export type AIProviderRequest<
53
+ // TModel,
54
+ // TInputMessage,
55
+ // TTool,
56
+ // TToolChoice = never,
57
+ // TResponseFormat = never,
58
+ // TRequestExtra = EmptyObject
59
+ // > = {
60
+ // model: TModel;
61
+ // messages: TInputMessage[];
62
+ // tools?: TTool[];
63
+ // toolChoice?: TToolChoice;
64
+ // temperature?: number;
65
+ // maxOutputTokens?: number;
66
+ // reasoning?: AIProviderReasoning;
67
+ // responseFormat?: TResponseFormat;
68
+ // extra?: TRequestExtra;
69
+ // };
70
+
71
+ // export type AIProviderResult<TMessage, TRawResponse> = {
72
+ // raw: TRawResponse;
73
+ // outputText: string;
74
+ // outputMessages: TMessage[];
75
+ // toolCalls: AIProviderToolCall[];
76
+ // usage?: AIProviderUsage;
77
+ // };
78
+
79
+ // export interface AIAPIProvider<
80
+ // TModel,
81
+ // TMessage,
82
+ // TTool,
83
+ // TRawResponse,
84
+ // TToolChoice = never,
85
+ // TResponseFormat = never,
86
+ // TRequestExtra = EmptyObject
87
+ // > {
88
+ // readonly endpoint: AIProviderEndpoint;
89
+ // create(request: AIProviderRequest<TModel, TMessage, TTool, TToolChoice, TResponseFormat, TRequestExtra>): Promise<AIProviderResult<TMessage, TRawResponse>>;
90
+ // createSystemMessage(content: string): TMessage;
91
+ // createUserMessage(content: string): TMessage;
92
+ // createToolOutputMessage(callId: string, output: string): TMessage;
93
+ // }
94
+
95
+ // export class AIProvider {
96
+ // private static provider: AIAPIProvider<any, any, any, any, any, any, any> | null = null;
97
+ // public static setProvider(provider: AIAPIProvider<any, any, any, any, any, any, any>): void {
98
+ // AIProvider.provider = provider;
99
+ // }
100
+ // public static getProvider(): AIAPIProvider<any, any, any, any, any, any, any> {
101
+ // if (!AIProvider.provider)
102
+ // throw new Error('AI Provider is not set');
103
+
104
+ // return AIProvider.provider;
105
+ // }
106
+ // }
@@ -0,0 +1,235 @@
1
+
2
+ // /** @deprecated NOT IN USE */
3
+ // class DeepWikiOpenAIClient {
4
+ // private mcpClient: Client;
5
+ // private openai: OpenAI;
6
+ // private transport: StreamableHTTPClientTransport | null = null;
7
+ // private repository: string;
8
+ // private model: string;
9
+ // private conversationHistory: OpenAI.Chat.ChatCompletionMessageParam[] = [];
10
+ // private cachedTools: OpenAI.Chat.ChatCompletionTool[] | null = null;
11
+
12
+ // private static _instance: DeepWikiOpenAIClient | null = null;
13
+ // static getInstance(config: DeepWikiClientConfig): DeepWikiOpenAIClient {
14
+ // DeepWikiOpenAIClient._instance ??= new DeepWikiOpenAIClient(config);
15
+ // return DeepWikiOpenAIClient._instance;
16
+ // }
17
+ // private constructor(config: DeepWikiClientConfig) {
18
+ // this.repository = config.repository;
19
+ // this.model = config.openaiModel || 'gpt-4o-mini';
20
+
21
+ // const apiKey = config.openaiApiKey!;
22
+ // if (!apiKey)
23
+ // throw new Error('OpenAI API key is required');
24
+
25
+
26
+ // this.openai = new OpenAI({apiKey, dangerouslyAllowBrowser: true});
27
+
28
+ // this.mcpClient = new Client(
29
+ // {
30
+ // name: 'deepwiki-openai-client',
31
+ // version: '1.0.0',
32
+ // },
33
+ // {
34
+ // capabilities: {},
35
+ // }
36
+ // );
37
+ // }
38
+
39
+ // async connect(): Promise<void> {
40
+ // if (this.transport) {
41
+ // console.log('Already connected to MCP server');
42
+ // return;
43
+ // }
44
+ // console.log('Connecting to DeepWiki MCP server...');
45
+
46
+ // // Connect to DeepWiki's free mcp endpoint
47
+ // this.transport = new StreamableHTTPClientTransport(
48
+ // new URL('https://mcp.deepwiki.com/mcp')
49
+ // );
50
+
51
+ // await this.mcpClient.connect(this.transport);
52
+
53
+ // // List available tools
54
+ // const toolsResponse = await this.mcpClient.listTools();
55
+ // console.log(
56
+ // '\n✓ Connected! Available tools:',
57
+ // toolsResponse.tools.map((tool) => tool.name).join(', ')
58
+ // );
59
+ // }
60
+
61
+ // async disconnect(): Promise<void> {
62
+ // if (this.transport) {
63
+ // await this.transport.close();
64
+ // console.log('\n✓ Disconnected from DeepWiki MCP server');
65
+ // }
66
+ // }
67
+
68
+ // private _askQuestionTool: OpenAI.Chat.Completions.ChatCompletionTool | null = null;
69
+ // async askUsingAskTool(question: string): Promise<string> {
70
+ // if (!this.transport)
71
+ // throw new Error('Not connected to MCP server. Call connect() first.');
72
+
73
+ // if (!this._askQuestionTool) {
74
+ // const tools = await this.mcpClient.listTools();
75
+ // const askTool = tools.tools.find((tool) => tool.name.includes('question'));
76
+ // if (!askTool)
77
+ // throw new Error('ask_question tool not found on MCP server.');
78
+
79
+ // this._askQuestionTool = {
80
+ // type: 'function',
81
+ // function: {
82
+ // name: askTool.name,
83
+ // description: askTool.description || '',
84
+ // parameters: askTool.inputSchema as Record<string, unknown>,
85
+ // },
86
+ // };
87
+ // }
88
+
89
+ // const q = `You are a helpful assistant with access to documentation for the ${this.repository} GitHub repository.
90
+
91
+ // VERY IMPORTANT TO REMEMER!!!: you are a UI side assistant for Datagrok platform users, so when asked about how to do something in Datagrok, try to answer with UI in mind and also the code.
92
+
93
+ // Make sure the output is nicely formatted with markdown syntax where applicable.
94
+
95
+ // Do not repeat the question in your answer, and do not include the deepwiki links!!!.
96
+
97
+ // user: ${question}
98
+ // `;
99
+ // // just call the ask tool directly
100
+ // const toolArgs = {
101
+ // repoName: this.repository,
102
+ // repository: this.repository,
103
+ // question: q,
104
+ // };
105
+
106
+ // const result = await this.mcpClient.callTool({
107
+ // name: this._askQuestionTool.function.name,
108
+ // arguments: toolArgs,
109
+ // });
110
+
111
+ // const contentArray = Array.isArray(result.content) ? result.content : [];
112
+ // const toolResult = contentArray
113
+ // .filter((item: any) => item.type === 'text')
114
+ // .map((item: any) => item.text || '')
115
+ // .join('\n');
116
+ // if (!toolResult || toolResult.length === 0)
117
+ // return 'No response generated.';
118
+
119
+ // // remove deepwiki links from the answer
120
+ // const lines = toolResult.split('\n').filter((line) => !line.includes('deepwiki.com')).join('\n');
121
+ // return lines;
122
+ // }
123
+
124
+ // async askQuestion(question: string): Promise<string> {
125
+ // if (!this.transport)
126
+ // throw new Error('Not connected to MCP server. Call connect() first.');
127
+
128
+
129
+ // console.log(`\n🤔 Question: ${question}`);
130
+
131
+ // // Get or use cached tools from MCP server
132
+ // if (!this.cachedTools) {
133
+ // const toolsResponse = await this.mcpClient.listTools();
134
+ // this.cachedTools = toolsResponse.tools
135
+ // //.filter((a) => !a.name.includes('question'))
136
+ // .map(
137
+ // (tool) => ({
138
+ // type: 'function',
139
+ // function: {
140
+ // name: tool.name,
141
+ // description: tool.description || '',
142
+ // parameters: tool.inputSchema as Record<string, unknown>,
143
+ // },
144
+ // })
145
+ // );
146
+ // }
147
+
148
+ // // System message (only sent once per conversation in history)
149
+ // const systemMessage: OpenAI.Chat.ChatCompletionMessageParam = {
150
+ // role: 'system',
151
+ // content: `You are a helpful assistant with access to documentation for the ${this.repository} GitHub repository via DeepWiki MCP tools. Use the available tools to answer questions accurately.
152
+
153
+ // VERY IMPORTANT TO REMEMER!!!: you are a UI side assistant for Datagrok platform users, so when asked about how to do something in Datagrok, try to answer with UI in mind and also the code.
154
+
155
+ // Make sure the output is nicely formatted with markdown syntax where applicable.
156
+
157
+ // If you use the ask_question tool and it returns comprehensive answer, make sure not to warp it and return as is.
158
+
159
+ // MAKE SURE TO ALWAYS USE TOOLS to access the repository information! DO NOT MAKE UP ANSWERS BASED ON YOUR TRAINING DATA!
160
+ // `,
161
+ // };
162
+
163
+ // // Add user question to conversation history
164
+ // this.conversationHistory.push({
165
+ // role: 'user',
166
+ // content: question,
167
+ // });
168
+
169
+ // // Initial call to OpenAI
170
+ // let response = await this.openai.chat.completions.create({
171
+ // model: this.model,
172
+ // messages: [systemMessage, ...this.conversationHistory],
173
+ // tools: this.cachedTools,
174
+ // tool_choice: 'auto',
175
+ // });
176
+
177
+ // let assistantMessage = response.choices[0].message;
178
+ // this.conversationHistory.push(assistantMessage);
179
+
180
+ // // Handle tool calls
181
+ // while (assistantMessage.tool_calls && assistantMessage.tool_calls.length > 0) {
182
+ // console.log(`\n🔧 Calling ${assistantMessage.tool_calls.length} tool(s)...`);
183
+
184
+ // for (const toolCall of assistantMessage.tool_calls) {
185
+ // const toolName = toolCall.function.name;
186
+ // const toolArgs = JSON.parse(toolCall.function.arguments);
187
+
188
+ // // Add repository to the arguments
189
+ // toolArgs.repository = this.repository;
190
+
191
+ // console.log(` → ${toolName}(${JSON.stringify(toolArgs)})`);
192
+
193
+ // // Call MCP tool
194
+ // const result = await this.mcpClient.callTool({
195
+ // name: toolName,
196
+ // arguments: toolArgs,
197
+ // });
198
+
199
+ // // Extract text content from result with proper type handling
200
+ // const contentArray = Array.isArray(result.content) ? result.content : [];
201
+ // const toolResult = contentArray
202
+ // .filter((item: any) => item.type === 'text')
203
+ // .map((item: any) => item.text || '')
204
+ // .join('\n');
205
+
206
+ // // Add tool result to conversation
207
+ // this.conversationHistory.push({
208
+ // role: 'tool',
209
+ // tool_call_id: toolCall.id,
210
+ // content: toolResult,
211
+ // });
212
+ // }
213
+
214
+ // // Get next response from OpenAI
215
+ // response = await this.openai.chat.completions.create({
216
+ // model: this.model,
217
+ // messages: [systemMessage, ...this.conversationHistory],
218
+ // tools: this.cachedTools,
219
+ // });
220
+
221
+ // assistantMessage = response.choices[0].message;
222
+ // this.conversationHistory.push(assistantMessage);
223
+ // }
224
+
225
+ // const finalAnswer = assistantMessage.content || 'No response generated.';
226
+ // console.log(`\n💡 Answer: ${finalAnswer}`);
227
+
228
+ // return finalAnswer;
229
+ // }
230
+
231
+ // clearHistory(): void {
232
+ // this.conversationHistory = [];
233
+ // console.log('\n✓ Conversation history cleared');
234
+ // }
235
+ // }