@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.
- package/dist/adapters/ai/index.cjs +135 -58
- package/dist/adapters/ai/index.cjs.map +1 -1
- package/dist/adapters/ai/index.js +135 -58
- package/dist/adapters/ai/index.js.map +1 -1
- package/dist/adapters/cloudflare/index.cjs +28 -70
- package/dist/adapters/cloudflare/index.cjs.map +1 -1
- package/dist/adapters/cloudflare/index.js +28 -70
- package/dist/adapters/cloudflare/index.js.map +1 -1
- package/dist/client/index.cjs +14 -8
- package/dist/client/index.cjs.map +1 -1
- package/dist/client/index.js +14 -8
- package/dist/client/index.js.map +1 -1
- package/dist/index.cjs +15 -8
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +15 -8
- package/dist/index.js.map +1 -1
- package/dist/mcp/index.cjs +9 -7
- package/dist/mcp/index.cjs.map +1 -1
- package/dist/mcp/index.d.cts +1 -0
- package/dist/mcp/index.d.ts +1 -0
- package/dist/mcp/index.js +9 -7
- package/dist/mcp/index.js.map +1 -1
- package/dist/server/index.cjs +1 -0
- package/dist/server/index.cjs.map +1 -1
- package/dist/server/index.js +1 -0
- package/dist/server/index.js.map +1 -1
- package/package.json +1 -1
|
@@ -2,15 +2,68 @@ import { jsonSchema } from 'ai';
|
|
|
2
2
|
|
|
3
3
|
// src/adapters/ai/index.ts
|
|
4
4
|
|
|
5
|
+
// src/errors.ts
|
|
6
|
+
var KontextError = class extends Error {
|
|
7
|
+
/** Brand field for type narrowing without instanceof */
|
|
8
|
+
kontextError = true;
|
|
9
|
+
/** Machine-readable error code, always prefixed with `kontext_` */
|
|
10
|
+
code;
|
|
11
|
+
/** HTTP status code when applicable */
|
|
12
|
+
statusCode;
|
|
13
|
+
/** Auto-generated link to error documentation */
|
|
14
|
+
docsUrl;
|
|
15
|
+
/** Server request ID for debugging / support escalation */
|
|
16
|
+
requestId;
|
|
17
|
+
/** Contextual metadata bag (integration IDs, param names, etc.) */
|
|
18
|
+
meta;
|
|
19
|
+
constructor(message, code, options) {
|
|
20
|
+
super(message, { cause: options?.cause });
|
|
21
|
+
this.name = "KontextError";
|
|
22
|
+
this.code = code;
|
|
23
|
+
this.statusCode = options?.statusCode;
|
|
24
|
+
this.requestId = options?.requestId;
|
|
25
|
+
this.meta = options?.meta ?? {};
|
|
26
|
+
this.docsUrl = `https://docs.kontext.dev/errors/${code}`;
|
|
27
|
+
Object.setPrototypeOf(this, new.target.prototype);
|
|
28
|
+
}
|
|
29
|
+
toJSON() {
|
|
30
|
+
return {
|
|
31
|
+
name: this.name,
|
|
32
|
+
code: this.code,
|
|
33
|
+
message: this.message,
|
|
34
|
+
statusCode: this.statusCode,
|
|
35
|
+
docsUrl: this.docsUrl,
|
|
36
|
+
requestId: this.requestId,
|
|
37
|
+
meta: Object.keys(this.meta).length > 0 ? this.meta : void 0
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
toString() {
|
|
41
|
+
const parts = [`[${this.code}] ${this.message}`];
|
|
42
|
+
if (this.docsUrl) parts.push(`Docs: ${this.docsUrl}`);
|
|
43
|
+
if (this.requestId) parts.push(`Request ID: ${this.requestId}`);
|
|
44
|
+
return parts.join("\n");
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
var ConfigError = class extends KontextError {
|
|
48
|
+
constructor(message, code, options) {
|
|
49
|
+
super(message, code, options);
|
|
50
|
+
this.name = "ConfigError";
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
|
|
5
54
|
// src/client/tool-utils.ts
|
|
6
55
|
function buildKontextSystemPrompt(toolNames, integrations) {
|
|
7
56
|
if (toolNames.length === 0) return "";
|
|
8
|
-
const searchTool = toolNames.find(
|
|
9
|
-
|
|
57
|
+
const searchTool = toolNames.find(
|
|
58
|
+
(n) => n.endsWith("_SEARCH_TOOLS") || n === "SEARCH_TOOLS"
|
|
59
|
+
);
|
|
60
|
+
const executeTool = toolNames.find(
|
|
61
|
+
(n) => n.endsWith("_EXECUTE_TOOL") || n === "EXECUTE_TOOL"
|
|
62
|
+
);
|
|
10
63
|
const requestCapabilityTool = toolNames.find(
|
|
11
|
-
(n) => n.endsWith("_REQUEST_CAPABILITY")
|
|
64
|
+
(n) => n.endsWith("_REQUEST_CAPABILITY") || n === "REQUEST_CAPABILITY"
|
|
12
65
|
);
|
|
13
|
-
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.";
|
|
66
|
+
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.";
|
|
14
67
|
if (searchTool && executeTool) {
|
|
15
68
|
prompt += `
|
|
16
69
|
|
|
@@ -34,83 +87,76 @@ You already have access to: ${connected.map((i) => i.name).join(", ")}`;
|
|
|
34
87
|
|
|
35
88
|
The following services require user authorization: ${disconnected.map((i) => i.name).join(", ")}`;
|
|
36
89
|
if (requestCapabilityTool) {
|
|
37
|
-
const example = disconnected[0]?.name ?? "GitHub";
|
|
38
90
|
prompt += `
|
|
39
91
|
|
|
40
92
|
**IMPORTANT:** When the user requests an action that requires one of these services:
|
|
41
|
-
1. Call the \`${requestCapabilityTool}\` tool
|
|
42
|
-
2. The tool
|
|
43
|
-
3. Include the link in your response so the user can
|
|
44
|
-
4.
|
|
93
|
+
1. Call the \`${requestCapabilityTool}\` tool
|
|
94
|
+
2. The tool returns a fresh integrations management link
|
|
95
|
+
3. Include the link in your response so the user can connect or manage integrations
|
|
96
|
+
4. Always call the tool for a fresh link and never reuse a previously returned URL`;
|
|
45
97
|
} else {
|
|
46
98
|
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.";
|
|
47
99
|
}
|
|
100
|
+
} else if (requestCapabilityTool && connected.length > 0) {
|
|
101
|
+
prompt += `
|
|
102
|
+
|
|
103
|
+
## Integration Management
|
|
104
|
+
|
|
105
|
+
If the user asks to manage, reconnect, or verify integrations, call \`${requestCapabilityTool}\` to get a fresh integrations management link.`;
|
|
48
106
|
}
|
|
49
107
|
}
|
|
50
108
|
return prompt;
|
|
51
109
|
}
|
|
52
110
|
function enrichToolsWithAuthAwareness(toolNames, integrations, options) {
|
|
53
|
-
const
|
|
54
|
-
(
|
|
111
|
+
const serverRequestCapability = toolNames.find(
|
|
112
|
+
(name) => name.endsWith("_REQUEST_CAPABILITY") || name === "REQUEST_CAPABILITY"
|
|
55
113
|
);
|
|
56
|
-
if (!
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
114
|
+
if (!serverRequestCapability) {
|
|
115
|
+
throw new ConfigError(
|
|
116
|
+
"REQUEST_CAPABILITY tool is required but not exposed by the MCP server. Deploy API and SDK in lockstep.",
|
|
117
|
+
"kontext_config_missing_request_capability_tool"
|
|
118
|
+
);
|
|
119
|
+
}
|
|
120
|
+
let requestCapabilityTool = null;
|
|
121
|
+
let effectiveToolNames = [...toolNames];
|
|
122
|
+
if (options?.requestCapabilityProxy) {
|
|
123
|
+
const prefix = options.prefix ?? toolNames.find((n) => n.endsWith("_SEARCH_TOOLS"))?.replace(/_SEARCH_TOOLS$/, "") ?? "kontext";
|
|
124
|
+
const toolName = `${prefix}_REQUEST_CAPABILITY`;
|
|
125
|
+
const tool = buildRequestCapabilityTool(
|
|
126
|
+
integrations,
|
|
127
|
+
options.requestCapabilityProxy
|
|
128
|
+
);
|
|
129
|
+
requestCapabilityTool = { name: toolName, ...tool };
|
|
130
|
+
effectiveToolNames = [...effectiveToolNames, toolName];
|
|
61
131
|
}
|
|
62
|
-
const prefix = toolNames.find((n) => n.endsWith("_SEARCH_TOOLS"))?.replace(/_SEARCH_TOOLS$/, "") ?? "kontext";
|
|
63
|
-
const toolName = `${prefix}_REQUEST_CAPABILITY`;
|
|
64
|
-
const tool = buildRequestCapabilityTool(integrations);
|
|
65
|
-
const allToolNames = [...toolNames, toolName];
|
|
66
132
|
return {
|
|
67
|
-
systemPrompt: buildKontextSystemPrompt(
|
|
68
|
-
requestCapabilityTool
|
|
133
|
+
systemPrompt: buildKontextSystemPrompt(effectiveToolNames, integrations),
|
|
134
|
+
requestCapabilityTool
|
|
69
135
|
};
|
|
70
136
|
}
|
|
71
|
-
function buildRequestCapabilityTool(capabilities) {
|
|
72
|
-
const
|
|
73
|
-
const
|
|
137
|
+
function buildRequestCapabilityTool(capabilities, executeRequestCapability) {
|
|
138
|
+
const connected = capabilities.filter((c) => c.connected);
|
|
139
|
+
const disconnected = capabilities.filter((c) => !c.connected);
|
|
140
|
+
const connectedList = connected.length > 0 ? connected.map((c) => c.name).join(", ") : "none";
|
|
141
|
+
const disconnectedList = disconnected.length > 0 ? disconnected.map((c) => c.name).join(", ") : "none";
|
|
74
142
|
return {
|
|
75
|
-
description: `Request
|
|
143
|
+
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.`,
|
|
76
144
|
parameters: {
|
|
77
145
|
type: "object",
|
|
78
|
-
properties: {
|
|
79
|
-
capability_name: {
|
|
80
|
-
type: "string",
|
|
81
|
-
description: "The name of the capability to connect"
|
|
82
|
-
}
|
|
83
|
-
},
|
|
84
|
-
required: ["capability_name"]
|
|
146
|
+
properties: {}
|
|
85
147
|
},
|
|
86
|
-
execute: async (
|
|
87
|
-
|
|
88
|
-
const name = input.capability_name ?? "";
|
|
89
|
-
if (!name && disconnected.length === 1 && disconnected[0]) {
|
|
90
|
-
return `${disconnected[0].name} requires authorization. Please visit the following link to connect: ${disconnected[0].connectUrl}`;
|
|
91
|
-
}
|
|
92
|
-
const match = disconnected.find(
|
|
93
|
-
(c) => c.name.toLowerCase() === name.toLowerCase()
|
|
94
|
-
);
|
|
95
|
-
if (!match) {
|
|
96
|
-
const isConnected = capabilities.find(
|
|
97
|
-
(c) => c.connected && c.name.toLowerCase() === name.toLowerCase()
|
|
98
|
-
);
|
|
99
|
-
if (isConnected) {
|
|
100
|
-
return `${isConnected.name} is already connected and ready to use.`;
|
|
101
|
-
}
|
|
102
|
-
return `Unknown capability "${name}". Available disconnected capabilities: ${capabilityList}.`;
|
|
103
|
-
}
|
|
104
|
-
return `${match.name} requires authorization. Please visit the following link to connect: ${match.connectUrl}`;
|
|
148
|
+
execute: async () => {
|
|
149
|
+
return executeRequestCapability();
|
|
105
150
|
}
|
|
106
151
|
};
|
|
107
152
|
}
|
|
108
153
|
|
|
109
154
|
// src/adapters/ai/index.ts
|
|
110
155
|
async function toKontextTools(client, options) {
|
|
111
|
-
const [tools, integrations] = await Promise.all([
|
|
156
|
+
const [tools, integrations, mcpTools] = await Promise.all([
|
|
112
157
|
client.tools.list(),
|
|
113
|
-
client.integrations.list()
|
|
158
|
+
client.integrations.list(),
|
|
159
|
+
client.mcp.listTools()
|
|
114
160
|
]);
|
|
115
161
|
const coreTools = {};
|
|
116
162
|
const usedNames = /* @__PURE__ */ new Set();
|
|
@@ -125,9 +171,22 @@ async function toKontextTools(client, options) {
|
|
|
125
171
|
}
|
|
126
172
|
};
|
|
127
173
|
}
|
|
174
|
+
if (!mcpTools.some((tool) => tool.name === "REQUEST_CAPABILITY")) {
|
|
175
|
+
throw new ConfigError(
|
|
176
|
+
"REQUEST_CAPABILITY tool is missing on the MCP server. Deploy API and SDK in lockstep.",
|
|
177
|
+
"kontext_config_missing_request_capability_tool"
|
|
178
|
+
);
|
|
179
|
+
}
|
|
128
180
|
const { systemPrompt, requestCapabilityTool } = enrichToolsWithAuthAwareness(
|
|
129
|
-
tools.map((t) => t.name),
|
|
130
|
-
integrations
|
|
181
|
+
[...tools.map((t) => t.name), "kontext_REQUEST_CAPABILITY"],
|
|
182
|
+
integrations,
|
|
183
|
+
{
|
|
184
|
+
prefix: "kontext",
|
|
185
|
+
requestCapabilityProxy: async () => {
|
|
186
|
+
const result = await client.mcp.callTool("REQUEST_CAPABILITY", {});
|
|
187
|
+
return extractText(result);
|
|
188
|
+
}
|
|
189
|
+
}
|
|
131
190
|
);
|
|
132
191
|
if (requestCapabilityTool) {
|
|
133
192
|
coreTools[requestCapabilityTool.name] = {
|
|
@@ -135,8 +194,8 @@ async function toKontextTools(client, options) {
|
|
|
135
194
|
parameters: jsonSchema(
|
|
136
195
|
requestCapabilityTool.parameters
|
|
137
196
|
),
|
|
138
|
-
execute: async (
|
|
139
|
-
return requestCapabilityTool.execute(
|
|
197
|
+
execute: async () => {
|
|
198
|
+
return requestCapabilityTool.execute();
|
|
140
199
|
}
|
|
141
200
|
};
|
|
142
201
|
}
|
|
@@ -167,6 +226,24 @@ function buildToolName(tool, usedNames) {
|
|
|
167
226
|
function sanitizeToolName(name) {
|
|
168
227
|
return name.replace(/[^a-zA-Z0-9_-]/g, "_").replace(/_+/g, "_").replace(/^_+|_+$/g, "").slice(0, 64);
|
|
169
228
|
}
|
|
229
|
+
function extractText(result) {
|
|
230
|
+
if (typeof result === "string") return result;
|
|
231
|
+
if (!result || typeof result !== "object") {
|
|
232
|
+
return String(result ?? "");
|
|
233
|
+
}
|
|
234
|
+
const content = result.content;
|
|
235
|
+
if (Array.isArray(content)) {
|
|
236
|
+
const textItem = content.find(
|
|
237
|
+
(item) => item.type === "text" && typeof item.text === "string"
|
|
238
|
+
);
|
|
239
|
+
if (textItem?.text) return textItem.text;
|
|
240
|
+
const resourceItem = content.find(
|
|
241
|
+
(item) => item.type === "resource" && typeof item.resource?.text === "string"
|
|
242
|
+
);
|
|
243
|
+
if (resourceItem?.resource?.text) return resourceItem.resource.text;
|
|
244
|
+
}
|
|
245
|
+
return JSON.stringify(result);
|
|
246
|
+
}
|
|
170
247
|
|
|
171
248
|
export { toKontextTools };
|
|
172
249
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/client/tool-utils.ts","../../../src/adapters/ai/index.ts"],"names":[],"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,EAGhC;AAGA,EAAA,IAAI,YAAA,CAAa,SAAS,CAAA,EAAG;AAC3B,IAAA,MAAM,YAAY,YAAA,CAAa,MAAA,CAAO,CAAC,CAAA,KAAM,EAAE,SAAS,CAAA;AACxD,IAAA,MAAM,eAAe,YAAA,CAAa,MAAA,CAAO,CAAC,CAAA,KAAM,CAAC,EAAE,SAAS,CAAA;AAE5D,IAAA,IAAI,YAAA,CAAa,SAAS,CAAA,EAAG;AAC3B,MAAA,MAAA,IAAU,2BAAA;AAEV,MAAA,IAAI,SAAA,CAAU,SAAS,CAAA,EAAG;AACxB,QAAA,MAAA,IAAU;;AAAA,4B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IAAI,CAAA,CAAA,GAAK,IAAA;AACpD;AAEA,SAAS,aAAA,CAAc,MAAmB,SAAA,EAAgC;AACxE,EAAA,MAAM,OAAA,GAAU,IAAA,CAAK,IAAA,IAAQ,IAAA,CAAK,EAAA,IAAM,MAAA;AACxC,EAAA,MAAM,IAAA,GAAO,IAAA,CAAK,MAAA,GACd,CAAA,EAAG,IAAA,CAAK,MAAA,CAAO,IAAA,IAAQ,IAAA,CAAK,MAAA,CAAO,EAAA,IAAM,QAAQ,CAAA,CAAA,EAAI,OAAO,CAAA,CAAA,GAC5D,OAAA;AACJ,EAAA,MAAM,SAAA,GAAY,iBAAiB,IAAI,CAAA;AACvC,EAAA,MAAM,QAAA,GAAW,SAAA,IAAa,CAAA,KAAA,EAAQ,SAAA,CAAU,OAAO,CAAC,CAAA,CAAA;AAExD,EAAA,IAAI,IAAA,GAAO,QAAA;AACX,EAAA,IAAI,MAAA,GAAS,CAAA;AACb,EAAA,OAAO,SAAA,CAAU,GAAA,CAAI,IAAI,CAAA,EAAG;AAC1B,IAAA,IAAA,GAAO,CAAA,EAAG,QAAQ,CAAA,CAAA,EAAI,MAAM,CAAA,CAAA;AAC5B,IAAA,MAAA,IAAU,CAAA;AAAA,EACZ;AAEA,EAAA,SAAA,CAAU,IAAI,IAAI,CAAA;AAClB,EAAA,OAAO,IAAA;AACT;AAEA,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.js","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, \"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A,SAAA,CAAU,IAAI,IAAI,CAAA;AAClB,EAAA,OAAO,IAAA;AACT;AAEA,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;AAEA,SAAS,YAAY,MAAA,EAAyB;AAC5C,EAAA,IAAI,OAAO,MAAA,KAAW,QAAA,EAAU,OAAO,MAAA;AACvC,EAAA,IAAI,CAAC,MAAA,IAAU,OAAO,MAAA,KAAW,QAAA,EAAU;AACzC,IAAA,OAAO,MAAA,CAAO,UAAU,EAAE,CAAA;AAAA,EAC5B;AAEA,EAAA,MAAM,UACJ,MAAA,CAOA,OAAA;AACF,EAAA,IAAI,KAAA,CAAM,OAAA,CAAQ,OAAO,CAAA,EAAG;AAC1B,IAAA,MAAM,WAAW,OAAA,CAAQ,IAAA;AAAA,MACvB,CAAC,IAAA,KAAS,IAAA,CAAK,SAAS,MAAA,IAAU,OAAO,KAAK,IAAA,KAAS;AAAA,KACzD;AACA,IAAA,IAAI,QAAA,EAAU,IAAA,EAAM,OAAO,QAAA,CAAS,IAAA;AAEpC,IAAA,MAAM,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.js","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"]}
|
|
@@ -81,12 +81,16 @@ var ConfigError = class extends KontextError {
|
|
|
81
81
|
// src/client/tool-utils.ts
|
|
82
82
|
function buildKontextSystemPrompt(toolNames, integrations) {
|
|
83
83
|
if (toolNames.length === 0) return "";
|
|
84
|
-
const searchTool = toolNames.find(
|
|
85
|
-
|
|
84
|
+
const searchTool = toolNames.find(
|
|
85
|
+
(n) => n.endsWith("_SEARCH_TOOLS") || n === "SEARCH_TOOLS"
|
|
86
|
+
);
|
|
87
|
+
const executeTool = toolNames.find(
|
|
88
|
+
(n) => n.endsWith("_EXECUTE_TOOL") || n === "EXECUTE_TOOL"
|
|
89
|
+
);
|
|
86
90
|
const requestCapabilityTool = toolNames.find(
|
|
87
|
-
(n) => n.endsWith("_REQUEST_CAPABILITY")
|
|
91
|
+
(n) => n.endsWith("_REQUEST_CAPABILITY") || n === "REQUEST_CAPABILITY"
|
|
88
92
|
);
|
|
89
|
-
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.";
|
|
93
|
+
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.";
|
|
90
94
|
if (searchTool && executeTool) {
|
|
91
95
|
prompt += `
|
|
92
96
|
|
|
@@ -110,40 +114,26 @@ You already have access to: ${connected.map((i) => i.name).join(", ")}`;
|
|
|
110
114
|
|
|
111
115
|
The following services require user authorization: ${disconnected.map((i) => i.name).join(", ")}`;
|
|
112
116
|
if (requestCapabilityTool) {
|
|
113
|
-
const example = disconnected[0]?.name ?? "GitHub";
|
|
114
117
|
prompt += `
|
|
115
118
|
|
|
116
119
|
**IMPORTANT:** When the user requests an action that requires one of these services:
|
|
117
|
-
1. Call the \`${requestCapabilityTool}\` tool
|
|
118
|
-
2. The tool
|
|
119
|
-
3. Include the link in your response so the user can
|
|
120
|
-
4.
|
|
120
|
+
1. Call the \`${requestCapabilityTool}\` tool
|
|
121
|
+
2. The tool returns a fresh integrations management link
|
|
122
|
+
3. Include the link in your response so the user can connect or manage integrations
|
|
123
|
+
4. Always call the tool for a fresh link and never reuse a previously returned URL`;
|
|
121
124
|
} else {
|
|
122
125
|
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.";
|
|
123
126
|
}
|
|
127
|
+
} else if (requestCapabilityTool && connected.length > 0) {
|
|
128
|
+
prompt += `
|
|
129
|
+
|
|
130
|
+
## Integration Management
|
|
131
|
+
|
|
132
|
+
If the user asks to manage, reconnect, or verify integrations, call \`${requestCapabilityTool}\` to get a fresh integrations management link.`;
|
|
124
133
|
}
|
|
125
134
|
}
|
|
126
135
|
return prompt;
|
|
127
136
|
}
|
|
128
|
-
function enrichToolsWithAuthAwareness(toolNames, integrations, options) {
|
|
129
|
-
const hasDisconnected = integrations.some(
|
|
130
|
-
(i) => !i.connected && i.connectUrl
|
|
131
|
-
);
|
|
132
|
-
if (!hasDisconnected) {
|
|
133
|
-
return {
|
|
134
|
-
systemPrompt: buildKontextSystemPrompt(toolNames, integrations),
|
|
135
|
-
requestCapabilityTool: null
|
|
136
|
-
};
|
|
137
|
-
}
|
|
138
|
-
const prefix = toolNames.find((n) => n.endsWith("_SEARCH_TOOLS"))?.replace(/_SEARCH_TOOLS$/, "") ?? "kontext";
|
|
139
|
-
const toolName = `${prefix}_REQUEST_CAPABILITY`;
|
|
140
|
-
const tool = buildRequestCapabilityTool(integrations);
|
|
141
|
-
const allToolNames = [...toolNames, toolName];
|
|
142
|
-
return {
|
|
143
|
-
systemPrompt: buildKontextSystemPrompt(allToolNames, integrations),
|
|
144
|
-
requestCapabilityTool: { name: toolName, ...tool }
|
|
145
|
-
};
|
|
146
|
-
}
|
|
147
137
|
function parseIntegrationStatus(tools, errors, elicitations) {
|
|
148
138
|
const seen = /* @__PURE__ */ new Set();
|
|
149
139
|
const result = [];
|
|
@@ -174,43 +164,6 @@ function parseIntegrationStatus(tools, errors, elicitations) {
|
|
|
174
164
|
}
|
|
175
165
|
return result;
|
|
176
166
|
}
|
|
177
|
-
function buildRequestCapabilityTool(capabilities) {
|
|
178
|
-
const disconnected = capabilities.filter((c) => !c.connected && c.connectUrl);
|
|
179
|
-
const capabilityList = disconnected.length > 0 ? disconnected.map((c) => c.name).join(", ") : "none";
|
|
180
|
-
return {
|
|
181
|
-
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.`,
|
|
182
|
-
parameters: {
|
|
183
|
-
type: "object",
|
|
184
|
-
properties: {
|
|
185
|
-
capability_name: {
|
|
186
|
-
type: "string",
|
|
187
|
-
description: "The name of the capability to connect"
|
|
188
|
-
}
|
|
189
|
-
},
|
|
190
|
-
required: ["capability_name"]
|
|
191
|
-
},
|
|
192
|
-
execute: async (...args) => {
|
|
193
|
-
const input = args[0] ?? {};
|
|
194
|
-
const name = input.capability_name ?? "";
|
|
195
|
-
if (!name && disconnected.length === 1 && disconnected[0]) {
|
|
196
|
-
return `${disconnected[0].name} requires authorization. Please visit the following link to connect: ${disconnected[0].connectUrl}`;
|
|
197
|
-
}
|
|
198
|
-
const match = disconnected.find(
|
|
199
|
-
(c) => c.name.toLowerCase() === name.toLowerCase()
|
|
200
|
-
);
|
|
201
|
-
if (!match) {
|
|
202
|
-
const isConnected = capabilities.find(
|
|
203
|
-
(c) => c.connected && c.name.toLowerCase() === name.toLowerCase()
|
|
204
|
-
);
|
|
205
|
-
if (isConnected) {
|
|
206
|
-
return `${isConnected.name} is already connected and ready to use.`;
|
|
207
|
-
}
|
|
208
|
-
return `Unknown capability "${name}". Available disconnected capabilities: ${capabilityList}.`;
|
|
209
|
-
}
|
|
210
|
-
return `${match.name} requires authorization. Please visit the following link to connect: ${match.connectUrl}`;
|
|
211
|
-
}
|
|
212
|
-
};
|
|
213
|
-
}
|
|
214
167
|
async function preflightIntegrationStatus(tools) {
|
|
215
168
|
const searchToolKey = Object.keys(tools).find(
|
|
216
169
|
(k) => k.endsWith("_SEARCH_TOOLS")
|
|
@@ -558,16 +511,21 @@ function withKontext(Base) {
|
|
|
558
511
|
});
|
|
559
512
|
}
|
|
560
513
|
const mcpTools = this.mcp.getAITools();
|
|
514
|
+
const hasRequestCapabilityTool = Object.keys(mcpTools).some(
|
|
515
|
+
(name) => name.endsWith("_REQUEST_CAPABILITY") || name === "REQUEST_CAPABILITY"
|
|
516
|
+
);
|
|
517
|
+
if (!hasRequestCapabilityTool) {
|
|
518
|
+
throw new ConfigError(
|
|
519
|
+
"REQUEST_CAPABILITY tool is missing on the MCP server. Deploy API and SDK in lockstep.",
|
|
520
|
+
"kontext_config_missing_request_capability_tool"
|
|
521
|
+
);
|
|
522
|
+
}
|
|
561
523
|
this._kontextIntegrations = await preflightIntegrationStatus(mcpTools);
|
|
562
524
|
const wrapped = wrapToolsWithElicitation(mcpTools);
|
|
563
|
-
|
|
525
|
+
this._kontextSystemPrompt = buildKontextSystemPrompt(
|
|
564
526
|
Object.keys(wrapped),
|
|
565
527
|
this._kontextIntegrations
|
|
566
528
|
);
|
|
567
|
-
if (requestCapabilityTool) {
|
|
568
|
-
wrapped[requestCapabilityTool.name] = requestCapabilityTool;
|
|
569
|
-
}
|
|
570
|
-
this._kontextSystemPrompt = systemPrompt;
|
|
571
529
|
return wrapped;
|
|
572
530
|
}
|
|
573
531
|
get kontextSystemPrompt() {
|