@kontext-dev/js-sdk 0.1.1 → 0.3.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.
@@ -4,15 +4,68 @@ var ai = require('ai');
4
4
 
5
5
  // src/adapters/ai/index.ts
6
6
 
7
+ // src/errors.ts
8
+ var KontextError = class extends Error {
9
+ /** Brand field for type narrowing without instanceof */
10
+ kontextError = true;
11
+ /** Machine-readable error code, always prefixed with `kontext_` */
12
+ code;
13
+ /** HTTP status code when applicable */
14
+ statusCode;
15
+ /** Auto-generated link to error documentation */
16
+ docsUrl;
17
+ /** Server request ID for debugging / support escalation */
18
+ requestId;
19
+ /** Contextual metadata bag (integration IDs, param names, etc.) */
20
+ meta;
21
+ constructor(message, code, options) {
22
+ super(message, { cause: options?.cause });
23
+ this.name = "KontextError";
24
+ this.code = code;
25
+ this.statusCode = options?.statusCode;
26
+ this.requestId = options?.requestId;
27
+ this.meta = options?.meta ?? {};
28
+ this.docsUrl = `https://docs.kontext.dev/errors/${code}`;
29
+ Object.setPrototypeOf(this, new.target.prototype);
30
+ }
31
+ toJSON() {
32
+ return {
33
+ name: this.name,
34
+ code: this.code,
35
+ message: this.message,
36
+ statusCode: this.statusCode,
37
+ docsUrl: this.docsUrl,
38
+ requestId: this.requestId,
39
+ meta: Object.keys(this.meta).length > 0 ? this.meta : void 0
40
+ };
41
+ }
42
+ toString() {
43
+ const parts = [`[${this.code}] ${this.message}`];
44
+ if (this.docsUrl) parts.push(`Docs: ${this.docsUrl}`);
45
+ if (this.requestId) parts.push(`Request ID: ${this.requestId}`);
46
+ return parts.join("\n");
47
+ }
48
+ };
49
+ var ConfigError = class extends KontextError {
50
+ constructor(message, code, options) {
51
+ super(message, code, options);
52
+ this.name = "ConfigError";
53
+ }
54
+ };
55
+
7
56
  // src/client/tool-utils.ts
8
57
  function buildKontextSystemPrompt(toolNames, integrations) {
9
58
  if (toolNames.length === 0) return "";
10
- const searchTool = toolNames.find((n) => n.endsWith("_SEARCH_TOOLS"));
11
- const executeTool = toolNames.find((n) => n.endsWith("_EXECUTE_TOOL"));
59
+ const searchTool = toolNames.find(
60
+ (n) => n.endsWith("_SEARCH_TOOLS") || n === "SEARCH_TOOLS"
61
+ );
62
+ const executeTool = toolNames.find(
63
+ (n) => n.endsWith("_EXECUTE_TOOL") || n === "EXECUTE_TOOL"
64
+ );
12
65
  const requestCapabilityTool = toolNames.find(
13
- (n) => n.endsWith("_REQUEST_CAPABILITY")
66
+ (n) => n.endsWith("_REQUEST_CAPABILITY") || n === "REQUEST_CAPABILITY"
14
67
  );
15
- let prompt = "You are a helpful assistant with access to various tools and integrations through Kontext.\nYou can help users with tasks across their connected services (GitHub, Linear, Slack, etc.).\nWhen a user asks about their services, use the available MCP tools to help them.\nThe user has already authenticated \u2014 tools run as the user with their permissions, including access to private repositories and org resources.";
68
+ let prompt = "You are a helpful assistant with access to various tools and integrations through Kontext.\nYou can help users with tasks across their connected services (GitHub, Linear, Slack, etc.).\nWhen a user asks about their services, use the available MCP tools to help them.\nThe user has already authenticated \u2014 tools run as the user with their permissions, including access to private repositories and org resources.\nIf a Kontext tool can satisfy an integration-related request, use the Kontext tool and do not use shell or CLI commands for that request.\nUse shell or CLI only when no relevant Kontext tool exists or when the user explicitly requests local shell actions.";
16
69
  if (searchTool && executeTool) {
17
70
  prompt += `
18
71
 
@@ -36,83 +89,76 @@ You already have access to: ${connected.map((i) => i.name).join(", ")}`;
36
89
 
37
90
  The following services require user authorization: ${disconnected.map((i) => i.name).join(", ")}`;
38
91
  if (requestCapabilityTool) {
39
- const example = disconnected[0]?.name ?? "GitHub";
40
92
  prompt += `
41
93
 
42
94
  **IMPORTANT:** When the user requests an action that requires one of these services:
43
- 1. Call the \`${requestCapabilityTool}\` tool with \`capability_name\` set to the service name (e.g. "${example}")
44
- 2. The tool will return an authorization link
45
- 3. Include the link in your response so the user can click it to connect
46
- 4. After the user authorizes, the service will be available on their next message`;
95
+ 1. Call the \`${requestCapabilityTool}\` tool
96
+ 2. The tool returns a fresh integrations management link
97
+ 3. Include the link in your response so the user can connect or manage integrations
98
+ 4. Always call the tool for a fresh link and never reuse a previously returned URL`;
47
99
  } else {
48
100
  prompt += "\n\nWhen the user asks about a disconnected integration, let them know it needs to be connected first. Do not attempt to use tools from disconnected integrations without informing the user.";
49
101
  }
102
+ } else if (requestCapabilityTool && connected.length > 0) {
103
+ prompt += `
104
+
105
+ ## Integration Management
106
+
107
+ If the user asks to manage, reconnect, or verify integrations, call \`${requestCapabilityTool}\` to get a fresh integrations management link.`;
50
108
  }
51
109
  }
52
110
  return prompt;
53
111
  }
54
112
  function enrichToolsWithAuthAwareness(toolNames, integrations, options) {
55
- const hasDisconnected = integrations.some(
56
- (i) => !i.connected && i.connectUrl
113
+ const serverRequestCapability = toolNames.find(
114
+ (name) => name.endsWith("_REQUEST_CAPABILITY") || name === "REQUEST_CAPABILITY"
57
115
  );
58
- if (!hasDisconnected) {
59
- return {
60
- systemPrompt: buildKontextSystemPrompt(toolNames, integrations),
61
- requestCapabilityTool: null
62
- };
116
+ if (!serverRequestCapability) {
117
+ throw new ConfigError(
118
+ "REQUEST_CAPABILITY tool is required but not exposed by the MCP server. Deploy API and SDK in lockstep.",
119
+ "kontext_config_missing_request_capability_tool"
120
+ );
121
+ }
122
+ let requestCapabilityTool = null;
123
+ let effectiveToolNames = [...toolNames];
124
+ if (options?.requestCapabilityProxy) {
125
+ const prefix = options.prefix ?? toolNames.find((n) => n.endsWith("_SEARCH_TOOLS"))?.replace(/_SEARCH_TOOLS$/, "") ?? "kontext";
126
+ const toolName = `${prefix}_REQUEST_CAPABILITY`;
127
+ const tool = buildRequestCapabilityTool(
128
+ integrations,
129
+ options.requestCapabilityProxy
130
+ );
131
+ requestCapabilityTool = { name: toolName, ...tool };
132
+ effectiveToolNames = [...effectiveToolNames, toolName];
63
133
  }
64
- const prefix = toolNames.find((n) => n.endsWith("_SEARCH_TOOLS"))?.replace(/_SEARCH_TOOLS$/, "") ?? "kontext";
65
- const toolName = `${prefix}_REQUEST_CAPABILITY`;
66
- const tool = buildRequestCapabilityTool(integrations);
67
- const allToolNames = [...toolNames, toolName];
68
134
  return {
69
- systemPrompt: buildKontextSystemPrompt(allToolNames, integrations),
70
- requestCapabilityTool: { name: toolName, ...tool }
135
+ systemPrompt: buildKontextSystemPrompt(effectiveToolNames, integrations),
136
+ requestCapabilityTool
71
137
  };
72
138
  }
73
- function buildRequestCapabilityTool(capabilities) {
74
- const disconnected = capabilities.filter((c) => !c.connected && c.connectUrl);
75
- const capabilityList = disconnected.length > 0 ? disconnected.map((c) => c.name).join(", ") : "none";
139
+ function buildRequestCapabilityTool(capabilities, executeRequestCapability) {
140
+ const connected = capabilities.filter((c) => c.connected);
141
+ const disconnected = capabilities.filter((c) => !c.connected);
142
+ const connectedList = connected.length > 0 ? connected.map((c) => c.name).join(", ") : "none";
143
+ const disconnectedList = disconnected.length > 0 ? disconnected.map((c) => c.name).join(", ") : "none";
76
144
  return {
77
- description: `Request connection to a capability that is not yet connected. Currently disconnected capabilities: ${capabilityList}. Call this tool with the capability name to initiate the connection flow.`,
145
+ description: `Request a fresh integrations management link from the Kontext server. Connected integrations: ${connectedList}. Disconnected integrations: ${disconnectedList}. Always call this tool for a fresh link and never reuse an older link.`,
78
146
  parameters: {
79
147
  type: "object",
80
- properties: {
81
- capability_name: {
82
- type: "string",
83
- description: "The name of the capability to connect"
84
- }
85
- },
86
- required: ["capability_name"]
148
+ properties: {}
87
149
  },
88
- execute: async (...args) => {
89
- const input = args[0] ?? {};
90
- const name = input.capability_name ?? "";
91
- if (!name && disconnected.length === 1 && disconnected[0]) {
92
- return `${disconnected[0].name} requires authorization. Please visit the following link to connect: ${disconnected[0].connectUrl}`;
93
- }
94
- const match = disconnected.find(
95
- (c) => c.name.toLowerCase() === name.toLowerCase()
96
- );
97
- if (!match) {
98
- const isConnected = capabilities.find(
99
- (c) => c.connected && c.name.toLowerCase() === name.toLowerCase()
100
- );
101
- if (isConnected) {
102
- return `${isConnected.name} is already connected and ready to use.`;
103
- }
104
- return `Unknown capability "${name}". Available disconnected capabilities: ${capabilityList}.`;
105
- }
106
- return `${match.name} requires authorization. Please visit the following link to connect: ${match.connectUrl}`;
150
+ execute: async () => {
151
+ return executeRequestCapability();
107
152
  }
108
153
  };
109
154
  }
110
155
 
111
156
  // src/adapters/ai/index.ts
112
157
  async function toKontextTools(client, options) {
113
- const [tools, integrations] = await Promise.all([
158
+ const [tools, integrations, mcpTools] = await Promise.all([
114
159
  client.tools.list(),
115
- client.integrations.list()
160
+ client.integrations.list(),
161
+ client.mcp.listTools()
116
162
  ]);
117
163
  const coreTools = {};
118
164
  const usedNames = /* @__PURE__ */ new Set();
@@ -127,9 +173,22 @@ async function toKontextTools(client, options) {
127
173
  }
128
174
  };
129
175
  }
176
+ if (!mcpTools.some((tool) => tool.name === "REQUEST_CAPABILITY")) {
177
+ throw new ConfigError(
178
+ "REQUEST_CAPABILITY tool is missing on the MCP server. Deploy API and SDK in lockstep.",
179
+ "kontext_config_missing_request_capability_tool"
180
+ );
181
+ }
130
182
  const { systemPrompt, requestCapabilityTool } = enrichToolsWithAuthAwareness(
131
- tools.map((t) => t.name),
132
- integrations
183
+ [...tools.map((t) => t.name), "kontext_REQUEST_CAPABILITY"],
184
+ integrations,
185
+ {
186
+ prefix: "kontext",
187
+ requestCapabilityProxy: async () => {
188
+ const result = await client.mcp.callTool("REQUEST_CAPABILITY", {});
189
+ return extractText(result);
190
+ }
191
+ }
133
192
  );
134
193
  if (requestCapabilityTool) {
135
194
  coreTools[requestCapabilityTool.name] = {
@@ -137,8 +196,8 @@ async function toKontextTools(client, options) {
137
196
  parameters: ai.jsonSchema(
138
197
  requestCapabilityTool.parameters
139
198
  ),
140
- execute: async (args) => {
141
- return requestCapabilityTool.execute(args);
199
+ execute: async () => {
200
+ return requestCapabilityTool.execute();
142
201
  }
143
202
  };
144
203
  }
@@ -169,6 +228,24 @@ function buildToolName(tool, usedNames) {
169
228
  function sanitizeToolName(name) {
170
229
  return name.replace(/[^a-zA-Z0-9_-]/g, "_").replace(/_+/g, "_").replace(/^_+|_+$/g, "").slice(0, 64);
171
230
  }
231
+ function extractText(result) {
232
+ if (typeof result === "string") return result;
233
+ if (!result || typeof result !== "object") {
234
+ return String(result ?? "");
235
+ }
236
+ const content = result.content;
237
+ if (Array.isArray(content)) {
238
+ const textItem = content.find(
239
+ (item) => item.type === "text" && typeof item.text === "string"
240
+ );
241
+ if (textItem?.text) return textItem.text;
242
+ const resourceItem = content.find(
243
+ (item) => item.type === "resource" && typeof item.resource?.text === "string"
244
+ );
245
+ if (resourceItem?.resource?.text) return resourceItem.resource.text;
246
+ }
247
+ return JSON.stringify(result);
248
+ }
172
249
 
173
250
  exports.toKontextTools = toKontextTools;
174
251
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/client/tool-utils.ts","../../../src/adapters/ai/index.ts"],"names":["jsonSchema"],"mappings":";;;;;;;AAiCO,SAAS,wBAAA,CACd,WACA,YAAA,EACQ;AACR,EAAA,IAAI,SAAA,CAAU,MAAA,KAAW,CAAA,EAAG,OAAO,EAAA;AAEnC,EAAA,MAAM,UAAA,GAAa,UAAU,IAAA,CAAK,CAAC,MAAM,CAAA,CAAE,QAAA,CAAS,eAAe,CAAC,CAAA;AACpE,EAAA,MAAM,WAAA,GAAc,UAAU,IAAA,CAAK,CAAC,MAAM,CAAA,CAAE,QAAA,CAAS,eAAe,CAAC,CAAA;AACrE,EAAA,MAAM,wBAAwB,SAAA,CAAU,IAAA;AAAA,IAAK,CAAC,CAAA,KAC5C,CAAA,CAAE,QAAA,CAAS,qBAAqB;AAAA,GAClC;AAEA,EAAA,IAAI,MAAA,GACF,iaAAA;AAKF,EAAA,IAAI,cAAc,WAAA,EAAa;AAC7B,IAAA,MAAA,IACE;;AAAA;AAAA,SAAA,EACY,UAAU,CAAA;AAAA,cAAA,EACL,WAAW,CAAA;AAAA;AAAA,sFAAA,CAAA;AAAA,EAGh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,SAAS,iBAAiB,IAAA,EAAsB;AAC9C,EAAA,OAAO,IAAA,CACJ,OAAA,CAAQ,iBAAA,EAAmB,GAAG,EAC9B,OAAA,CAAQ,KAAA,EAAO,GAAG,CAAA,CAClB,QAAQ,UAAA,EAAY,EAAE,CAAA,CACtB,KAAA,CAAM,GAAG,EAAE,CAAA;AAChB","file":"index.cjs","sourcesContent":["/**\n * Shared utilities for Kontext tool handling.\n * Used by both KontextClient (core) and withKontext (Cloudflare adapter).\n */\n\nimport {\n IntegrationConnectionRequiredError,\n type ElicitationEntry,\n} from \"../errors.js\";\n\n// Re-export for backward compatibility\nexport type { ElicitationEntry } from \"../errors.js\";\n\n// ============================================================================\n// Shared types\n// ============================================================================\n\nexport interface IntegrationStatus {\n readonly id: string;\n readonly name: string;\n readonly connected: boolean;\n readonly connectUrl?: string;\n}\n\n// ============================================================================\n// System prompt\n// ============================================================================\n\n/**\n * Build an LLM system prompt based on available tool names and integration status.\n * Detects `*_SEARCH_TOOLS` / `*_EXECUTE_TOOL` suffixed names from the\n * Cloudflare Agents MCP proxy and generates appropriate guidance.\n */\nexport function buildKontextSystemPrompt(\n toolNames: readonly string[],\n integrations: readonly IntegrationStatus[],\n): string {\n if (toolNames.length === 0) return \"\";\n\n const searchTool = toolNames.find((n) => n.endsWith(\"_SEARCH_TOOLS\"));\n const executeTool = toolNames.find((n) => n.endsWith(\"_EXECUTE_TOOL\"));\n const requestCapabilityTool = toolNames.find((n) =>\n n.endsWith(\"_REQUEST_CAPABILITY\"),\n );\n\n let prompt =\n \"You are a helpful assistant with access to various tools and integrations through Kontext.\\n\" +\n \"You can help users with tasks across their connected services (GitHub, Linear, Slack, etc.).\\n\" +\n \"When a user asks about their services, use the available MCP tools to help them.\\n\" +\n \"The user has already authenticated — tools run as the user with their permissions, including access to private repositories and org resources.\";\n\n if (searchTool && executeTool) {\n prompt +=\n `\\n\\nYou have access to external integrations through Kontext MCP tools:\\n` +\n `- Call \\`${searchTool}\\` first to discover what tools/integrations are available.\\n` +\n `- Then call \\`${executeTool}\\` with the tool_id and arguments to run a specific tool.\\n` +\n `- When the user asks about \"my repos\", \"my issues\", etc., use the appropriate tool to look up their data directly. Do not ask for their username — the tools already know who they are.\\n` +\n `Always start by searching for tools when the user asks about their connected services.`;\n }\n\n // Append integration status section when there are integrations to report\n if (integrations.length > 0) {\n const connected = integrations.filter((i) => i.connected);\n const disconnected = integrations.filter((i) => !i.connected);\n\n if (disconnected.length > 0) {\n prompt += \"\\n\\n## Integration Status\";\n\n if (connected.length > 0) {\n prompt += `\\n\\nYou already have access to: ${connected.map((i) => i.name).join(\", \")}`;\n }\n\n prompt += `\\n\\nThe following services require user authorization: ${disconnected.map((i) => i.name).join(\", \")}`;\n\n if (requestCapabilityTool) {\n const example = disconnected[0]?.name ?? \"GitHub\";\n prompt +=\n `\\n\\n**IMPORTANT:** When the user requests an action that requires one of these services:` +\n `\\n1. Call the \\`${requestCapabilityTool}\\` tool with \\`capability_name\\` set to the service name (e.g. \"${example}\")` +\n `\\n2. The tool will return an authorization link` +\n `\\n3. Include the link in your response so the user can click it to connect` +\n `\\n4. After the user authorizes, the service will be available on their next message`;\n } else {\n prompt +=\n \"\\n\\nWhen the user asks about a disconnected integration, let them know it needs to be connected first. Do not attempt to use tools from disconnected integrations without informing the user.\";\n }\n }\n }\n\n return prompt;\n}\n\n// ============================================================================\n// Auth-aware toolset orchestrator\n// ============================================================================\n\nexport interface AuthAwareToolset {\n /** System prompt with integration status and REQUEST_CAPABILITY instructions. */\n readonly systemPrompt: string;\n /** REQUEST_CAPABILITY tool to inject, or null if all integrations are connected. */\n readonly requestCapabilityTool: {\n readonly name: string;\n readonly description: string;\n readonly parameters: Record<string, unknown>;\n readonly execute: (...args: unknown[]) => Promise<string>;\n } | null;\n}\n\n/**\n * Enrich a tool set with auth awareness.\n *\n * Given tool names and integration status, produces:\n * - A system prompt that tells the LLM about connected/disconnected integrations\n * - A REQUEST_CAPABILITY tool (if needed) that returns auth URLs as text\n *\n * Both `ai/` and `cloudflare/` adapters use this as their core auth layer.\n */\nexport function enrichToolsWithAuthAwareness(\n toolNames: readonly string[],\n integrations: readonly IntegrationStatus[],\n options?: { prefix?: string },\n): AuthAwareToolset {\n const hasDisconnected = integrations.some(\n (i) => !i.connected && i.connectUrl,\n );\n\n if (!hasDisconnected) {\n return {\n systemPrompt: buildKontextSystemPrompt(toolNames, integrations),\n requestCapabilityTool: null,\n };\n }\n\n // Determine prefix from existing tool names or option\n const prefix =\n options?.prefix ??\n toolNames\n .find((n) => n.endsWith(\"_SEARCH_TOOLS\"))\n ?.replace(/_SEARCH_TOOLS$/, \"\") ??\n \"kontext\";\n\n const toolName = `${prefix}_REQUEST_CAPABILITY`;\n const tool = buildRequestCapabilityTool(integrations);\n\n // Include REQUEST_CAPABILITY in tool names so the system prompt references it\n const allToolNames = [...toolNames, toolName];\n\n return {\n systemPrompt: buildKontextSystemPrompt(allToolNames, integrations),\n requestCapabilityTool: { name: toolName, ...tool },\n };\n}\n\n// ============================================================================\n// Integration status parsing\n// ============================================================================\n\n/**\n * Parse integration status from gateway tool search results.\n * Extracts connected integrations from tools and disconnected from errors.\n */\nexport function parseIntegrationStatus(\n tools: ReadonlyArray<{ server?: { id?: string; name?: string } }>,\n errors: ReadonlyArray<{ serverId: string; serverName?: string }>,\n elicitations?: ReadonlyArray<{\n url: string;\n integrationId?: string;\n integrationName?: string;\n }>,\n): IntegrationStatus[] {\n const seen = new Set<string>();\n const result: IntegrationStatus[] = [];\n\n for (const t of tools) {\n const sid = t.server?.id;\n if (sid && !seen.has(sid)) {\n seen.add(sid);\n result.push({\n id: sid,\n name: t.server?.name ?? sid,\n connected: true,\n });\n }\n }\n\n for (const e of errors) {\n if (!seen.has(e.serverId)) {\n seen.add(e.serverId);\n const elicitation = elicitations?.find(\n (el) => el.integrationId === e.serverId,\n );\n result.push({\n id: e.serverId,\n name: e.serverName ?? e.serverId,\n connected: false,\n connectUrl: elicitation?.url,\n });\n }\n }\n\n return result;\n}\n\n// ============================================================================\n// Request capability tool\n// ============================================================================\n\n/**\n * Build a tool that lets the LLM request connection of a disconnected capability.\n * Returns the connect URL as text so the LLM can present it to the user.\n * No popups — the user clicks the link in the chat to authorize.\n */\nexport function buildRequestCapabilityTool(\n capabilities: readonly IntegrationStatus[],\n): {\n description: string;\n parameters: Record<string, unknown>;\n execute: (...args: unknown[]) => Promise<string>;\n} {\n const disconnected = capabilities.filter((c) => !c.connected && c.connectUrl);\n\n const capabilityList =\n disconnected.length > 0\n ? disconnected.map((c) => c.name).join(\", \")\n : \"none\";\n\n return {\n description:\n `Request connection to a capability that is not yet connected. ` +\n `Currently disconnected capabilities: ${capabilityList}. ` +\n `Call this tool with the capability name to initiate the connection flow.`,\n parameters: {\n type: \"object\",\n properties: {\n capability_name: {\n type: \"string\",\n description: \"The name of the capability to connect\",\n },\n },\n required: [\"capability_name\"],\n },\n execute: async (...args: unknown[]): Promise<string> => {\n const input = (args[0] ?? {}) as { capability_name?: string };\n const name = input.capability_name ?? \"\";\n\n // Auto-select when called without a name and there's only one option\n if (!name && disconnected.length === 1 && disconnected[0]) {\n return (\n `${disconnected[0].name} requires authorization. ` +\n `Please visit the following link to connect: ${disconnected[0].connectUrl}`\n );\n }\n\n const match = disconnected.find(\n (c) => c.name.toLowerCase() === name.toLowerCase(),\n );\n\n if (!match) {\n const isConnected = capabilities.find(\n (c) => c.connected && c.name.toLowerCase() === name.toLowerCase(),\n );\n if (isConnected) {\n return `${isConnected.name} is already connected and ready to use.`;\n }\n return `Unknown capability \"${name}\". Available disconnected capabilities: ${capabilityList}.`;\n }\n\n return (\n `${match.name} requires authorization. ` +\n `Please visit the following link to connect: ${match.connectUrl}`\n );\n },\n };\n}\n\n/**\n * Pre-flight integration status detection.\n * Calls SEARCH_TOOLS on raw (unwrapped) tools to detect connected/disconnected\n * integrations without triggering any popups or broadcasts.\n */\nexport async function preflightIntegrationStatus(\n tools: ToolSetLike,\n): Promise<IntegrationStatus[]> {\n const searchToolKey = Object.keys(tools).find((k) =>\n k.endsWith(\"_SEARCH_TOOLS\"),\n );\n if (!searchToolKey || !tools[searchToolKey]?.execute) return [];\n\n try {\n const result = await tools[searchToolKey].execute!({ limit: 100 });\n\n // Cloudflare getAITools() returns MCP CallToolResult objects, not strings.\n // Extract JSON text from either a plain string or a CallToolResult shape.\n let json: string | undefined;\n if (typeof result === \"string\") {\n json = result;\n } else if (result && typeof result === \"object\") {\n const content = (\n result as {\n content?: Array<{\n type: string;\n resource?: { text?: string };\n text?: string;\n }>;\n }\n ).content;\n const first = content?.[0];\n json = first?.resource?.text ?? first?.text;\n }\n\n if (typeof json === \"string\") {\n const parsed = JSON.parse(json);\n if (parsed && typeof parsed === \"object\") {\n return parseIntegrationStatus(\n Array.isArray(parsed.items) ? parsed.items : [],\n Array.isArray(parsed.errors) ? parsed.errors : [],\n Array.isArray(parsed.elicitations) ? parsed.elicitations : [],\n );\n }\n }\n } catch (err: unknown) {\n // All integrations disconnected: -32042 error contains elicitations\n const elicitations = extractElicitations(err);\n if (elicitations?.length) {\n return elicitations\n .filter(\n (e): e is ElicitationEntry & { integrationId: string } =>\n !!e.integrationId,\n )\n .map((e) => ({\n id: e.integrationId,\n name: e.integrationName ?? e.integrationId,\n connected: false,\n connectUrl: e.url,\n }));\n }\n }\n\n return [];\n}\n\n// ============================================================================\n// Tool wrapping\n// ============================================================================\n\n/** A tool with an optional async execute method */\nexport interface ToolLike {\n execute?: (...args: unknown[]) => Promise<unknown>;\n [key: string]: unknown;\n}\n\n/** Record of named tools */\nexport type ToolSetLike = Record<string, ToolLike>;\n\n/**\n * Extract elicitation entries from an error thrown by the MCP SDK.\n * Handles two shapes: direct code/data and nested cause.\n */\nexport function extractElicitations(\n err: unknown,\n): ElicitationEntry[] | undefined {\n const error = err as {\n code?: number;\n data?: { elicitations?: ElicitationEntry[] };\n cause?: {\n code?: number;\n data?: { elicitations?: ElicitationEntry[] };\n };\n };\n\n // Primary: structured McpError with code -32042\n if (error?.code === -32042 && error?.data?.elicitations?.length) {\n return error.data.elicitations;\n }\n\n // Nested cause (some SDK wrappers nest the original error)\n if (\n error?.cause?.code === -32042 &&\n error?.cause?.data?.elicitations?.length\n ) {\n return error.cause.data.elicitations;\n }\n\n return undefined;\n}\n\n/**\n * Wrap tools to catch MCP error code -32042 (URL elicitation required)\n * and convert to IntegrationConnectionRequiredError.\n */\nexport function wrapToolsWithElicitation<T extends ToolSetLike>(tools: T): T {\n return Object.fromEntries(\n Object.entries(tools).map(([name, tool]) => [\n name,\n {\n ...tool,\n execute: tool.execute\n ? async (...args: unknown[]) => {\n try {\n return await tool.execute!(...args);\n } catch (err: unknown) {\n const elicitations = extractElicitations(err);\n const elicitation = elicitations?.[0];\n if (elicitation?.url) {\n const integrationId = elicitation.integrationId ?? \"unknown\";\n throw new IntegrationConnectionRequiredError(integrationId, {\n integrationName: elicitation.integrationName,\n connectUrl: elicitation.url,\n message: elicitation.message,\n });\n }\n throw err;\n }\n }\n : undefined,\n },\n ]),\n ) as T;\n}\n","/**\n * Vercel AI SDK adapter for Kontext.\n *\n * Pure format converter: maps KontextClient tools to AI SDK CoreTools.\n *\n * @example\n * ```typescript\n * import { createKontextClient } from '@kontext-dev/js-sdk';\n * import { toKontextTools } from '@kontext-dev/js-sdk/ai';\n * import { generateText } from 'ai';\n *\n * const client = createKontextClient({\n * clientId: process.env.KONTEXT_CLIENT_ID!,\n * redirectUri: 'http://localhost:3000/callback',\n * onAuthRequired: (url) => open(url.toString()),\n * });\n *\n * const { tools, systemPrompt } = await toKontextTools(client);\n * const result = await generateText({ model, system: systemPrompt, tools, prompt: '...', maxSteps: 5 });\n * ```\n *\n * @packageDocumentation\n */\n\nimport { jsonSchema, type CoreTool } from \"ai\";\nimport type {\n KontextClient,\n KontextTool,\n IntegrationInfo,\n ToolResult,\n} from \"../../client/index.js\";\nimport type { KontextOrchestrator } from \"../../client/orchestrator/index.js\";\nimport { enrichToolsWithAuthAwareness } from \"../../client/tool-utils.js\";\n\nexport interface ToKontextToolsOptions {\n formatResult?: (result: ToolResult) => unknown;\n}\n\nexport interface KontextToolsResult {\n readonly tools: Record<string, CoreTool>;\n readonly systemPrompt: string;\n readonly integrations: readonly IntegrationInfo[];\n}\n\n/**\n * Convert a KontextClient's tools into an AI SDK ToolSet with system prompt.\n *\n * Calls `client.tools.list()` and `client.integrations.list()` to discover\n * tools and integration status, then wraps each tool as an AI SDK `CoreTool`\n * whose `execute` delegates to `client.tools.execute()`.\n */\nexport async function toKontextTools(\n client: KontextClient | KontextOrchestrator,\n options?: ToKontextToolsOptions,\n): Promise<KontextToolsResult> {\n const [tools, integrations] = await Promise.all([\n client.tools.list(),\n client.integrations.list(),\n ]);\n\n const coreTools: Record<string, CoreTool> = {};\n const usedNames = new Set<string>();\n\n for (const tool of tools) {\n const name = buildToolName(tool, usedNames);\n coreTools[name] = {\n description: formatDescription(tool),\n parameters: tool.inputSchema\n ? jsonSchema(tool.inputSchema as Parameters<typeof jsonSchema>[0])\n : jsonSchema({ type: \"object\" as const, properties: {} }),\n execute: async (args: Record<string, unknown>) => {\n const r = await client.tools.execute(tool.id, args);\n return (options?.formatResult ?? defaultFormat)(r);\n },\n };\n }\n\n const { systemPrompt, requestCapabilityTool } = enrichToolsWithAuthAwareness(\n tools.map((t) => t.name),\n integrations,\n );\n\n if (requestCapabilityTool) {\n coreTools[requestCapabilityTool.name] = {\n description: requestCapabilityTool.description,\n parameters: jsonSchema(\n requestCapabilityTool.parameters as Parameters<typeof jsonSchema>[0],\n ),\n execute: async (args: Record<string, unknown>) => {\n return requestCapabilityTool.execute(args);\n },\n };\n }\n\n return { tools: coreTools, systemPrompt, integrations };\n}\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\nfunction defaultFormat(r: ToolResult): unknown {\n return r.content;\n}\n\nfunction formatDescription(tool: KontextTool): string {\n const base = tool.description ?? tool.name;\n const serverLabel = tool.server?.name ?? tool.server?.id;\n return serverLabel ? `[${serverLabel}] ${base}` : base;\n}\n\nfunction buildToolName(tool: KontextTool, usedNames: Set<string>): string {\n const rawName = tool.name || tool.id || \"tool\";\n const base = tool.server\n ? `${tool.server.name ?? tool.server.id ?? \"server\"}_${rawName}`\n : rawName;\n const sanitized = sanitizeToolName(base);\n const fallback = sanitized || `tool_${usedNames.size + 1}`;\n\n let name = fallback;\n let suffix = 1;\n while (usedNames.has(name)) {\n name = `${fallback}_${suffix}`;\n suffix += 1;\n }\n\n usedNames.add(name);\n return name;\n}\n\nfunction sanitizeToolName(name: string): string {\n return name\n .replace(/[^a-zA-Z0-9_-]/g, \"_\")\n .replace(/_+/g, \"_\")\n .replace(/^_+|_+$/g, \"\")\n .slice(0, 64);\n}\n"]}
1
+ {"version":3,"sources":["../../../src/errors.ts","../../../src/client/tool-utils.ts","../../../src/adapters/ai/index.ts"],"names":["jsonSchema"],"mappings":";;;;;;;AA8BO,IAAM,YAAA,GAAN,cAA2B,KAAA,CAAM;AAAA;AAAA,EAE7B,YAAA,GAAe,IAAA;AAAA;AAAA,EAGf,IAAA;AAAA;AAAA,EAGA,UAAA;AAAA;AAAA,EAGA,OAAA;AAAA;AAAA,EAGA,SAAA;AAAA;AAAA,EAGA,IAAA;AAAA,EAET,WAAA,CACE,OAAA,EACA,IAAA,EACA,OAAA,EAMA;AACA,IAAA,KAAA,CAAM,OAAA,EAAS,EAAE,KAAA,EAAO,OAAA,EAAS,OAAO,CAAA;AACxC,IAAA,IAAA,CAAK,IAAA,GAAO,cAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAA,CAAK,aAAa,OAAA,EAAS,UAAA;AAC3B,IAAA,IAAA,CAAK,YAAY,OAAA,EAAS,SAAA;AAC1B,IAAA,IAAA,CAAK,IAAA,GAAO,OAAA,EAAS,IAAA,IAAQ,EAAC;AAC9B,IAAA,IAAA,CAAK,OAAA,GAAU,mCAAmC,IAAI,CAAA,CAAA;AACtD,IAAA,MAAA,CAAO,cAAA,CAAe,IAAA,EAAM,GAAA,CAAA,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M,eAAe,OAAA,CAAQ,IAAA;AAAA,MAC3B,CAAC,SACC,IAAA,CAAK,IAAA,KAAS,cAAc,OAAO,IAAA,CAAK,UAAU,IAAA,KAAS;AAAA,KAC/D;AACA,IAAA,IAAI,YAAA,EAAc,QAAA,EAAU,IAAA,EAAM,OAAO,aAAa,QAAA,CAAS,IAAA;AAAA,EACjE;AAEA,EAAA,OAAO,IAAA,CAAK,UAAU,MAAM,CAAA;AAC9B","file":"index.cjs","sourcesContent":["/**\n * Typed error classes for the Kontext SDK.\n *\n * Every error has a `kontext_` prefixed code, an auto-generated docsUrl,\n * and a `kontextError` brand for type narrowing without instanceof.\n *\n * @packageDocumentation\n */\n\n// ============================================================================\n// Base\n// ============================================================================\n\n/**\n * Base error class for all Kontext SDK errors.\n *\n * @example\n * ```typescript\n * import { isKontextError } from '@kontext-dev/js-sdk';\n *\n * try {\n * await client.connect();\n * } catch (err) {\n * if (isKontextError(err)) {\n * console.log(err.code); // \"kontext_authorization_required\"\n * console.log(err.docsUrl); // \"https://docs.kontext.dev/errors/kontext_authorization_required\"\n * }\n * }\n * ```\n */\nexport class KontextError extends Error {\n /** Brand field for type narrowing without instanceof */\n readonly kontextError = true as const;\n\n /** Machine-readable error code, always prefixed with `kontext_` */\n readonly code: string;\n\n /** HTTP status code when applicable */\n readonly statusCode?: number;\n\n /** Auto-generated link to error documentation */\n readonly docsUrl: string;\n\n /** Server request ID for debugging / support escalation */\n readonly requestId?: string;\n\n /** Contextual metadata bag (integration IDs, param names, etc.) */\n readonly meta: Record<string, unknown>;\n\n constructor(\n message: string,\n code: string,\n options?: {\n statusCode?: number;\n requestId?: string;\n meta?: Record<string, unknown>;\n cause?: unknown;\n },\n ) {\n super(message, { cause: options?.cause });\n this.name = \"KontextError\";\n this.code = code;\n this.statusCode = options?.statusCode;\n this.requestId = options?.requestId;\n this.meta = options?.meta ?? {};\n this.docsUrl = `https://docs.kontext.dev/errors/${code}`;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n\n toJSON(): Record<string, unknown> {\n return {\n name: this.name,\n code: this.code,\n message: this.message,\n statusCode: this.statusCode,\n docsUrl: this.docsUrl,\n requestId: this.requestId,\n meta: Object.keys(this.meta).length > 0 ? this.meta : undefined,\n };\n }\n\n override toString(): string {\n const parts = [`[${this.code}] ${this.message}`];\n if (this.docsUrl) parts.push(`Docs: ${this.docsUrl}`);\n if (this.requestId) parts.push(`Request ID: ${this.requestId}`);\n return parts.join(\"\\n\");\n }\n}\n\n// ============================================================================\n// Type guard\n// ============================================================================\n\n/**\n * Check if an error is a KontextError without instanceof.\n * Works across package versions and bundler deduplication.\n */\nexport function isKontextError(err: unknown): err is KontextError {\n return (\n typeof err === \"object\" &&\n err !== null &&\n (err as Record<string, unknown>).kontextError === true\n );\n}\n\n// ============================================================================\n// Auth errors\n// ============================================================================\n\n/**\n * Thrown when authentication is required but no valid credentials are available.\n */\nexport class AuthorizationRequiredError extends KontextError {\n readonly authorizationUrl?: string;\n\n constructor(\n message = \"Authorization required. Complete the OAuth flow to continue.\",\n options?: {\n authorizationUrl?: string;\n requestId?: string;\n meta?: Record<string, unknown>;\n cause?: unknown;\n },\n ) {\n super(message, \"kontext_authorization_required\", {\n statusCode: 401,\n ...options,\n });\n this.name = \"AuthorizationRequiredError\";\n this.authorizationUrl = options?.authorizationUrl;\n }\n}\n\n// ============================================================================\n// OAuth errors\n// ============================================================================\n\n/**\n * Thrown when an OAuth flow fails — state validation, token exchange,\n * missing code verifier, or provider errors.\n */\nexport class OAuthError extends KontextError {\n readonly errorCode?: string;\n readonly errorDescription?: string;\n\n constructor(\n message: string,\n code: string,\n options?: {\n statusCode?: number;\n errorCode?: string;\n errorDescription?: string;\n requestId?: string;\n meta?: Record<string, unknown>;\n cause?: unknown;\n },\n ) {\n super(message, code, {\n statusCode: options?.statusCode ?? 400,\n ...options,\n });\n this.name = \"OAuthError\";\n this.errorCode = options?.errorCode;\n this.errorDescription = options?.errorDescription;\n }\n}\n\n// ============================================================================\n// Integration errors\n// ============================================================================\n\n/**\n * Thrown when an integration connection is required before a tool can be used.\n */\nexport class IntegrationConnectionRequiredError extends KontextError {\n readonly integrationId: string;\n readonly integrationName?: string;\n readonly connectUrl?: string;\n\n constructor(\n integrationId: string,\n options?: {\n integrationName?: string;\n connectUrl?: string;\n message?: string;\n requestId?: string;\n meta?: Record<string, unknown>;\n cause?: unknown;\n },\n ) {\n super(\n options?.message ??\n `Connection to integration \"${integrationId}\" is required. Visit the connect URL to authorize.`,\n \"kontext_integration_connection_required\",\n { statusCode: 403, ...options },\n );\n this.name = \"IntegrationConnectionRequiredError\";\n this.integrationId = integrationId;\n this.integrationName = options?.integrationName;\n this.connectUrl = options?.connectUrl;\n }\n}\n\n// ============================================================================\n// Config errors (NEW — replaces all plain Error config throws)\n// ============================================================================\n\n/**\n * Thrown when SDK configuration is invalid or missing.\n * These are deterministic errors caught at initialization time.\n */\nexport class ConfigError extends KontextError {\n constructor(\n message: string,\n code: string,\n options?: {\n meta?: Record<string, unknown>;\n cause?: unknown;\n },\n ) {\n super(message, code, options);\n this.name = \"ConfigError\";\n }\n}\n\n// ============================================================================\n// Network errors\n// ============================================================================\n\n/**\n * Thrown when there is a network or connection error.\n */\nexport class NetworkError extends KontextError {\n constructor(\n message = \"Network error. Check your internet connection and that the server is reachable.\",\n options?: {\n cause?: unknown;\n requestId?: string;\n meta?: Record<string, unknown>;\n },\n ) {\n super(message, \"kontext_network_error\", options);\n this.name = \"NetworkError\";\n }\n}\n\n// ============================================================================\n// HTTP response errors (differentiated by code)\n// ============================================================================\n\n/**\n * Thrown when the server returns an HTTP error.\n * Use `error.code` to distinguish between specific error types.\n */\nexport class HttpError extends KontextError {\n readonly retryAfter?: number;\n readonly validationErrors?: Array<{ field: string; message: string }>;\n\n constructor(\n message: string,\n code: string,\n options?: {\n statusCode?: number;\n retryAfter?: number;\n validationErrors?: Array<{ field: string; message: string }>;\n requestId?: string;\n meta?: Record<string, unknown>;\n cause?: unknown;\n },\n ) {\n super(message, code, {\n statusCode: options?.statusCode,\n ...options,\n });\n this.name = \"HttpError\";\n this.retryAfter = options?.retryAfter;\n this.validationErrors = options?.validationErrors;\n }\n}\n\n// ============================================================================\n// Network error detection (used by translateError)\n// ============================================================================\n\n/**\n * Safely access arbitrary properties on an error object.\n * Errors in JS frequently carry extra properties (code, statusCode, etc.)\n * that aren't part of the Error interface. This avoids `as unknown as` casts.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction errorProps(err: Error): Record<string, any> {\n return err;\n}\n\nconst NETWORK_ERROR_CODES = new Set([\n \"ECONNREFUSED\",\n \"ENOTFOUND\",\n \"ETIMEDOUT\",\n \"ECONNRESET\",\n \"ECONNABORTED\",\n \"EPIPE\",\n \"UND_ERR_CONNECT_TIMEOUT\",\n]);\n\n/**\n * Detect network errors structurally rather than by string matching.\n * Checks Node.js system error codes on the error and its cause.\n */\nexport function isNetworkError(err: Error): boolean {\n if (err.name === \"AbortError\") return true;\n\n const props = errorProps(err);\n const sysCode = props.code as string | undefined;\n if (typeof sysCode === \"string\" && NETWORK_ERROR_CODES.has(sysCode))\n return true;\n\n // fetch() throws TypeError — only classify as network error when cause\n // indicates a system-level failure\n if (err.name === \"TypeError\" && err.cause instanceof Error) {\n const causeCode = errorProps(err.cause).code;\n if (typeof causeCode === \"string\" && NETWORK_ERROR_CODES.has(causeCode))\n return true;\n }\n\n return false;\n}\n\n/**\n * Detect unauthorized errors structurally.\n * Checks status code and numeric code rather than string matching on name.\n */\nexport function isUnauthorizedError(err: Error): boolean {\n const props = errorProps(err);\n\n // Check HTTP status code (most reliable)\n if (props.statusCode === 401 || props.status === 401) return true;\n\n // Check MCP SDK UnauthorizedError by name (last resort, but needed for\n // MCP SDK errors which don't set statusCode)\n if (err.name === \"UnauthorizedError\") return true;\n if (err.message === \"Unauthorized\") return true;\n\n return false;\n}\n\n// ============================================================================\n// Elicitation types\n// ============================================================================\n\nexport interface ElicitationEntry {\n readonly url: string;\n readonly message: string;\n readonly elicitationId: string;\n readonly integrationId?: string;\n readonly integrationName?: string;\n}\n\n// ============================================================================\n// HTTP error parsing\n// ============================================================================\n\n/**\n * Parse an HTTP response into an appropriate error.\n */\nexport function parseHttpError(\n statusCode: number,\n body?: unknown,\n): KontextError {\n const message =\n typeof body === \"object\" && body !== null && \"message\" in body\n ? String((body as { message: unknown }).message)\n : `HTTP ${statusCode}`;\n\n const errorCode =\n typeof body === \"object\" && body !== null && \"code\" in body\n ? String((body as { code: unknown }).code)\n : undefined;\n\n switch (statusCode) {\n case 400:\n if (\n typeof body === \"object\" &&\n body !== null &&\n \"errors\" in body &&\n Array.isArray((body as { errors: unknown }).errors)\n ) {\n return new HttpError(message, \"kontext_validation_error\", {\n statusCode: 400,\n validationErrors: (\n body as { errors: Array<{ field: string; message: string }> }\n ).errors,\n });\n }\n return new KontextError(message, errorCode ?? \"kontext_bad_request\", {\n statusCode: 400,\n });\n\n case 401:\n return new AuthorizationRequiredError(message);\n\n case 403:\n if (errorCode === \"INTEGRATION_CONNECTION_REQUIRED\") {\n const details = body as {\n integrationId?: string;\n integrationName?: string;\n connectUrl?: string;\n };\n return new IntegrationConnectionRequiredError(\n details.integrationId ?? \"unknown\",\n {\n integrationName: details.integrationName,\n connectUrl: details.connectUrl,\n message,\n },\n );\n }\n return new HttpError(message, \"kontext_policy_denied\", {\n statusCode: 403,\n meta: { policy: (body as Record<string, unknown>)?.policy },\n });\n\n case 404:\n return new HttpError(message, \"kontext_not_found\", { statusCode: 404 });\n\n case 429: {\n const retryAfter =\n typeof body === \"object\" && body !== null && \"retryAfter\" in body\n ? Number((body as { retryAfter: unknown }).retryAfter)\n : undefined;\n return new HttpError(\n retryAfter\n ? `Rate limit exceeded. Retry after ${retryAfter} seconds.`\n : \"Rate limit exceeded. Wait and retry.\",\n \"kontext_rate_limited\",\n { statusCode: 429, retryAfter },\n );\n }\n\n default:\n if (statusCode >= 500) {\n return new HttpError(\n `Server error (HTTP ${statusCode}): ${message}`,\n \"kontext_server_error\",\n { statusCode },\n );\n }\n return new KontextError(message, errorCode ?? \"kontext_unknown_error\", {\n statusCode,\n });\n }\n}\n","/**\n * Shared utilities for Kontext tool handling.\n * Used by both KontextClient (core) and withKontext (Cloudflare adapter).\n */\n\nimport {\n ConfigError,\n IntegrationConnectionRequiredError,\n type ElicitationEntry,\n} from \"../errors.js\";\n\n// Re-export for consumers that import this type from tool-utils.\nexport type { ElicitationEntry } from \"../errors.js\";\n\n// ============================================================================\n// Shared types\n// ============================================================================\n\nexport interface IntegrationStatus {\n readonly id: string;\n readonly name: string;\n readonly connected: boolean;\n readonly connectUrl?: string;\n}\n\n// ============================================================================\n// System prompt\n// ============================================================================\n\n/**\n * Build an LLM system prompt based on available tool names and integration status.\n * Detects `*_SEARCH_TOOLS` / `*_EXECUTE_TOOL` suffixed names from the\n * Cloudflare Agents MCP proxy and generates appropriate guidance.\n */\nexport function buildKontextSystemPrompt(\n toolNames: readonly string[],\n integrations: readonly IntegrationStatus[],\n): string {\n if (toolNames.length === 0) return \"\";\n\n const searchTool = toolNames.find(\n (n) => n.endsWith(\"_SEARCH_TOOLS\") || n === \"SEARCH_TOOLS\",\n );\n const executeTool = toolNames.find(\n (n) => n.endsWith(\"_EXECUTE_TOOL\") || n === \"EXECUTE_TOOL\",\n );\n const requestCapabilityTool = toolNames.find(\n (n) => n.endsWith(\"_REQUEST_CAPABILITY\") || n === \"REQUEST_CAPABILITY\",\n );\n\n let prompt =\n \"You are a helpful assistant with access to various tools and integrations through Kontext.\\n\" +\n \"You can help users with tasks across their connected services (GitHub, Linear, Slack, etc.).\\n\" +\n \"When a user asks about their services, use the available MCP tools to help them.\\n\" +\n \"The user has already authenticated — tools run as the user with their permissions, including access to private repositories and org resources.\\n\" +\n \"If a Kontext tool can satisfy an integration-related request, use the Kontext tool and do not use shell or CLI commands for that request.\\n\" +\n \"Use shell or CLI only when no relevant Kontext tool exists or when the user explicitly requests local shell actions.\";\n\n if (searchTool && executeTool) {\n prompt +=\n `\\n\\nYou have access to external integrations through Kontext MCP tools:\\n` +\n `- Call \\`${searchTool}\\` first to discover what tools/integrations are available.\\n` +\n `- Then call \\`${executeTool}\\` with the tool_id and arguments to run a specific tool.\\n` +\n `- When the user asks about \"my repos\", \"my issues\", etc., use the appropriate tool to look up their data directly. Do not ask for their username — the tools already know who they are.\\n` +\n `Always start by searching for tools when the user asks about their connected services.`;\n }\n\n // Append integration status section when there are integrations to report\n if (integrations.length > 0) {\n const connected = integrations.filter((i) => i.connected);\n const disconnected = integrations.filter((i) => !i.connected);\n\n if (disconnected.length > 0) {\n prompt += \"\\n\\n## Integration Status\";\n\n if (connected.length > 0) {\n prompt += `\\n\\nYou already have access to: ${connected.map((i) => i.name).join(\", \")}`;\n }\n\n prompt += `\\n\\nThe following services require user authorization: ${disconnected.map((i) => i.name).join(\", \")}`;\n\n if (requestCapabilityTool) {\n prompt +=\n `\\n\\n**IMPORTANT:** When the user requests an action that requires one of these services:` +\n `\\n1. Call the \\`${requestCapabilityTool}\\` tool` +\n `\\n2. The tool returns a fresh integrations management link` +\n `\\n3. Include the link in your response so the user can connect or manage integrations` +\n `\\n4. Always call the tool for a fresh link and never reuse a previously returned URL`;\n } else {\n prompt +=\n \"\\n\\nWhen the user asks about a disconnected integration, let them know it needs to be connected first. Do not attempt to use tools from disconnected integrations without informing the user.\";\n }\n } else if (requestCapabilityTool && connected.length > 0) {\n prompt +=\n \"\\n\\n## Integration Management\" +\n `\\n\\nIf the user asks to manage, reconnect, or verify integrations, call \\`${requestCapabilityTool}\\` to get a fresh integrations management link.`;\n }\n }\n\n return prompt;\n}\n\n// ============================================================================\n// Auth-aware toolset orchestrator\n// ============================================================================\n\nexport interface AuthAwareToolset {\n /** System prompt with integration status and REQUEST_CAPABILITY instructions. */\n readonly systemPrompt: string;\n /** REQUEST_CAPABILITY tool to inject, or null if all integrations are connected. */\n readonly requestCapabilityTool: {\n readonly name: string;\n readonly description: string;\n readonly parameters: Record<string, unknown>;\n readonly execute: () => Promise<string>;\n } | null;\n}\n\n/**\n * Enrich a tool set with auth awareness.\n *\n * Given tool names and integration status, produces:\n * - A system prompt that tells the LLM about connected/disconnected integrations\n * - A REQUEST_CAPABILITY tool (if needed) that returns a fresh management URL as text\n *\n * Both `ai/` and `cloudflare/` adapters use this as their core auth layer.\n */\nexport function enrichToolsWithAuthAwareness(\n toolNames: readonly string[],\n integrations: readonly IntegrationStatus[],\n options?: {\n prefix?: string;\n requireServerRequestCapability?: boolean;\n requestCapabilityProxy?: () => Promise<string>;\n },\n): AuthAwareToolset {\n const serverRequestCapability = toolNames.find(\n (name) =>\n name.endsWith(\"_REQUEST_CAPABILITY\") || name === \"REQUEST_CAPABILITY\",\n );\n\n if (options?.requireServerRequestCapability && !serverRequestCapability) {\n throw new ConfigError(\n \"REQUEST_CAPABILITY tool is required but not exposed by the MCP server. Deploy API and SDK in lockstep.\",\n \"kontext_config_missing_request_capability_tool\",\n );\n }\n\n let requestCapabilityTool: AuthAwareToolset[\"requestCapabilityTool\"] = null;\n let effectiveToolNames = [...toolNames];\n\n if (options?.requestCapabilityProxy) {\n const prefix =\n options.prefix ??\n toolNames\n .find((n) => n.endsWith(\"_SEARCH_TOOLS\"))\n ?.replace(/_SEARCH_TOOLS$/, \"\") ??\n \"kontext\";\n const toolName = `${prefix}_REQUEST_CAPABILITY`;\n const tool = buildRequestCapabilityTool(\n integrations,\n options.requestCapabilityProxy!,\n );\n requestCapabilityTool = { name: toolName, ...tool };\n effectiveToolNames = [...effectiveToolNames, toolName];\n }\n\n return {\n systemPrompt: buildKontextSystemPrompt(effectiveToolNames, integrations),\n requestCapabilityTool,\n };\n}\n\n// ============================================================================\n// Integration status parsing\n// ============================================================================\n\n/**\n * Parse integration status from gateway tool search results.\n * Extracts connected integrations from tools and disconnected from errors.\n */\nexport function parseIntegrationStatus(\n tools: ReadonlyArray<{ server?: { id?: string; name?: string } }>,\n errors: ReadonlyArray<{ serverId: string; serverName?: string }>,\n elicitations?: ReadonlyArray<{\n url: string;\n integrationId?: string;\n integrationName?: string;\n }>,\n): IntegrationStatus[] {\n const seen = new Set<string>();\n const result: IntegrationStatus[] = [];\n\n for (const t of tools) {\n const sid = t.server?.id;\n if (sid && !seen.has(sid)) {\n seen.add(sid);\n result.push({\n id: sid,\n name: t.server?.name ?? sid,\n connected: true,\n });\n }\n }\n\n for (const e of errors) {\n if (!seen.has(e.serverId)) {\n seen.add(e.serverId);\n const elicitation = elicitations?.find(\n (el) => el.integrationId === e.serverId,\n );\n result.push({\n id: e.serverId,\n name: e.serverName ?? e.serverId,\n connected: false,\n connectUrl: elicitation?.url,\n });\n }\n }\n\n return result;\n}\n\n// ============================================================================\n// Request capability tool\n// ============================================================================\n\n/**\n * Build a tool that lets the LLM request a fresh integrations management URL.\n * Returns the URL as text so the LLM can present it to the user.\n * No popups — the user clicks the link in the chat.\n */\nexport function buildRequestCapabilityTool(\n capabilities: readonly IntegrationStatus[],\n executeRequestCapability: () => Promise<string>,\n): {\n description: string;\n parameters: Record<string, unknown>;\n execute: () => Promise<string>;\n} {\n const connected = capabilities.filter((c) => c.connected);\n const disconnected = capabilities.filter((c) => !c.connected);\n const connectedList =\n connected.length > 0 ? connected.map((c) => c.name).join(\", \") : \"none\";\n const disconnectedList =\n disconnected.length > 0\n ? disconnected.map((c) => c.name).join(\", \")\n : \"none\";\n\n return {\n description:\n \"Request a fresh integrations management link from the Kontext server. \" +\n `Connected integrations: ${connectedList}. ` +\n `Disconnected integrations: ${disconnectedList}. ` +\n \"Always call this tool for a fresh link and never reuse an older link.\",\n parameters: {\n type: \"object\",\n properties: {},\n },\n execute: async (): Promise<string> => {\n return executeRequestCapability();\n },\n };\n}\n\n/**\n * Pre-flight integration status detection.\n * Calls SEARCH_TOOLS on raw (unwrapped) tools to detect connected/disconnected\n * integrations without triggering any popups or broadcasts.\n */\nexport async function preflightIntegrationStatus(\n tools: ToolSetLike,\n): Promise<IntegrationStatus[]> {\n const searchToolKey = Object.keys(tools).find((k) =>\n k.endsWith(\"_SEARCH_TOOLS\"),\n );\n if (!searchToolKey || !tools[searchToolKey]?.execute) return [];\n\n try {\n const result = await tools[searchToolKey].execute!({ limit: 100 });\n\n // Cloudflare getAITools() returns MCP CallToolResult objects, not strings.\n // Extract JSON text from either a plain string or a CallToolResult shape.\n let json: string | undefined;\n if (typeof result === \"string\") {\n json = result;\n } else if (result && typeof result === \"object\") {\n const content = (\n result as {\n content?: Array<{\n type: string;\n resource?: { text?: string };\n text?: string;\n }>;\n }\n ).content;\n const first = content?.[0];\n json = first?.resource?.text ?? first?.text;\n }\n\n if (typeof json === \"string\") {\n const parsed = JSON.parse(json);\n if (parsed && typeof parsed === \"object\") {\n return parseIntegrationStatus(\n Array.isArray(parsed.items) ? parsed.items : [],\n Array.isArray(parsed.errors) ? parsed.errors : [],\n Array.isArray(parsed.elicitations) ? parsed.elicitations : [],\n );\n }\n }\n } catch (err: unknown) {\n // All integrations disconnected: -32042 error contains elicitations\n const elicitations = extractElicitations(err);\n if (elicitations?.length) {\n return elicitations\n .filter(\n (e): e is ElicitationEntry & { integrationId: string } =>\n !!e.integrationId,\n )\n .map((e) => ({\n id: e.integrationId,\n name: e.integrationName ?? e.integrationId,\n connected: false,\n connectUrl: e.url,\n }));\n }\n }\n\n return [];\n}\n\n// ============================================================================\n// Tool wrapping\n// ============================================================================\n\n/** A tool with an optional async execute method */\nexport interface ToolLike {\n execute?: (...args: unknown[]) => Promise<unknown>;\n [key: string]: unknown;\n}\n\n/** Record of named tools */\nexport type ToolSetLike = Record<string, ToolLike>;\n\n/**\n * Extract elicitation entries from an error thrown by the MCP SDK.\n * Handles two shapes: direct code/data and nested cause.\n */\nexport function extractElicitations(\n err: unknown,\n): ElicitationEntry[] | undefined {\n const error = err as {\n code?: number;\n data?: { elicitations?: ElicitationEntry[] };\n cause?: {\n code?: number;\n data?: { elicitations?: ElicitationEntry[] };\n };\n };\n\n // Primary: structured McpError with code -32042\n if (error?.code === -32042 && error?.data?.elicitations?.length) {\n return error.data.elicitations;\n }\n\n // Nested cause (some SDK wrappers nest the original error)\n if (\n error?.cause?.code === -32042 &&\n error?.cause?.data?.elicitations?.length\n ) {\n return error.cause.data.elicitations;\n }\n\n return undefined;\n}\n\n/**\n * Wrap tools to catch MCP error code -32042 (URL elicitation required)\n * and convert to IntegrationConnectionRequiredError.\n */\nexport function wrapToolsWithElicitation<T extends ToolSetLike>(tools: T): T {\n return Object.fromEntries(\n Object.entries(tools).map(([name, tool]) => [\n name,\n {\n ...tool,\n execute: tool.execute\n ? async (...args: unknown[]) => {\n try {\n return await tool.execute!(...args);\n } catch (err: unknown) {\n const elicitations = extractElicitations(err);\n const elicitation = elicitations?.[0];\n if (elicitation?.url) {\n const integrationId = elicitation.integrationId ?? \"unknown\";\n throw new IntegrationConnectionRequiredError(integrationId, {\n integrationName: elicitation.integrationName,\n connectUrl: elicitation.url,\n message: elicitation.message,\n });\n }\n throw err;\n }\n }\n : undefined,\n },\n ]),\n ) as T;\n}\n","/**\n * Vercel AI SDK adapter for Kontext.\n *\n * Pure format converter: maps KontextClient tools to AI SDK CoreTools.\n *\n * @example\n * ```typescript\n * import { createKontextClient } from '@kontext-dev/js-sdk';\n * import { toKontextTools } from '@kontext-dev/js-sdk/ai';\n * import { generateText } from 'ai';\n *\n * const client = createKontextClient({\n * clientId: process.env.KONTEXT_CLIENT_ID!,\n * redirectUri: 'http://localhost:3000/callback',\n * onAuthRequired: (url) => open(url.toString()),\n * });\n *\n * const { tools, systemPrompt } = await toKontextTools(client);\n * const result = await generateText({ model, system: systemPrompt, tools, prompt: '...', maxSteps: 5 });\n * ```\n *\n * @packageDocumentation\n */\n\nimport { jsonSchema, type CoreTool } from \"ai\";\nimport type {\n KontextClient,\n KontextTool,\n IntegrationInfo,\n ToolResult,\n} from \"../../client/index.js\";\nimport type { KontextOrchestrator } from \"../../client/orchestrator/index.js\";\nimport { enrichToolsWithAuthAwareness } from \"../../client/tool-utils.js\";\nimport { ConfigError } from \"../../errors.js\";\n\nexport interface ToKontextToolsOptions {\n formatResult?: (result: ToolResult) => unknown;\n}\n\nexport interface KontextToolsResult {\n readonly tools: Record<string, CoreTool>;\n readonly systemPrompt: string;\n readonly integrations: readonly IntegrationInfo[];\n}\n\n/**\n * Convert a KontextClient's tools into an AI SDK ToolSet with system prompt.\n *\n * Calls `client.tools.list()` and `client.integrations.list()` to discover\n * tools and integration status, then wraps each tool as an AI SDK `CoreTool`\n * whose `execute` delegates to `client.tools.execute()`.\n */\nexport async function toKontextTools(\n client: KontextClient | KontextOrchestrator,\n options?: ToKontextToolsOptions,\n): Promise<KontextToolsResult> {\n const [tools, integrations, mcpTools] = await Promise.all([\n client.tools.list(),\n client.integrations.list(),\n client.mcp.listTools(),\n ]);\n\n const coreTools: Record<string, CoreTool> = {};\n const usedNames = new Set<string>();\n\n for (const tool of tools) {\n const name = buildToolName(tool, usedNames);\n coreTools[name] = {\n description: formatDescription(tool),\n parameters: tool.inputSchema\n ? jsonSchema(tool.inputSchema as Parameters<typeof jsonSchema>[0])\n : jsonSchema({ type: \"object\" as const, properties: {} }),\n execute: async (args: Record<string, unknown>) => {\n const r = await client.tools.execute(tool.id, args);\n return (options?.formatResult ?? defaultFormat)(r);\n },\n };\n }\n\n if (!mcpTools.some((tool) => tool.name === \"REQUEST_CAPABILITY\")) {\n throw new ConfigError(\n \"REQUEST_CAPABILITY tool is missing on the MCP server. Deploy API and SDK in lockstep.\",\n \"kontext_config_missing_request_capability_tool\",\n );\n }\n\n const { systemPrompt, requestCapabilityTool } = enrichToolsWithAuthAwareness(\n [...tools.map((t) => t.name), \"kontext_REQUEST_CAPABILITY\"],\n integrations,\n {\n prefix: \"kontext\",\n requireServerRequestCapability: true,\n requestCapabilityProxy: async () => {\n const result = await client.mcp.callTool(\"REQUEST_CAPABILITY\", {});\n return extractText(result);\n },\n },\n );\n\n if (requestCapabilityTool) {\n coreTools[requestCapabilityTool.name] = {\n description: requestCapabilityTool.description,\n parameters: jsonSchema(\n requestCapabilityTool.parameters as Parameters<typeof jsonSchema>[0],\n ),\n execute: async () => {\n return requestCapabilityTool.execute();\n },\n };\n }\n\n return { tools: coreTools, systemPrompt, integrations };\n}\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\nfunction defaultFormat(r: ToolResult): unknown {\n return r.content;\n}\n\nfunction formatDescription(tool: KontextTool): string {\n const base = tool.description ?? tool.name;\n const serverLabel = tool.server?.name ?? tool.server?.id;\n return serverLabel ? `[${serverLabel}] ${base}` : base;\n}\n\nfunction buildToolName(tool: KontextTool, usedNames: Set<string>): string {\n const rawName = tool.name || tool.id || \"tool\";\n const base = tool.server\n ? `${tool.server.name ?? tool.server.id ?? \"server\"}_${rawName}`\n : rawName;\n const sanitized = sanitizeToolName(base);\n const fallback = sanitized || `tool_${usedNames.size + 1}`;\n\n let name = fallback;\n let suffix = 1;\n while (usedNames.has(name)) {\n name = `${fallback}_${suffix}`;\n suffix += 1;\n }\n\n usedNames.add(name);\n return name;\n}\n\nfunction sanitizeToolName(name: string): string {\n return name\n .replace(/[^a-zA-Z0-9_-]/g, \"_\")\n .replace(/_+/g, \"_\")\n .replace(/^_+|_+$/g, \"\")\n .slice(0, 64);\n}\n\nfunction extractText(result: unknown): string {\n if (typeof result === \"string\") return result;\n if (!result || typeof result !== \"object\") {\n return String(result ?? \"\");\n }\n\n const content = (\n result as {\n content?: Array<{\n type?: string;\n text?: string;\n resource?: { text?: string };\n }>;\n }\n ).content;\n if (Array.isArray(content)) {\n const textItem = content.find(\n (item) => item.type === \"text\" && typeof item.text === \"string\",\n );\n if (textItem?.text) return textItem.text;\n\n const resourceItem = content.find(\n (item) =>\n item.type === \"resource\" && typeof item.resource?.text === \"string\",\n );\n if (resourceItem?.resource?.text) return resourceItem.resource.text;\n }\n\n return JSON.stringify(result);\n}\n"]}