import { McpAgent } from "agents/mcp";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";
export class MyMCP extends McpAgent<Env, Record<string, never>, Record<string, never>> {
server = new McpServer({
name: "Kanzi MCP Server",
version: "0.0.1",
});
// Store API configuration
private apiKey: string = "";
private projectId: string = "";
private integrationId: string = "";
private baseUrl = "https://api.kapa.ai";
constructor(state: DurableObjectState, env: Env) {
super(state, env);
// Initialize API configuration from environment variables
this.apiKey = env.KAPA_API_KEY || "";
this.projectId = env.KAPA_PROJECT_ID || "";
this.integrationId = env.KAPA_INTEGRATION_ID || "";
}
async init() {
// Tool for asking technical questions about Kanzi
this.server.tool(
"ask_kanzi_question",
"Ask technical questions about Kanzi",
{ query: z.string().describe("The question about Kanzi to ask") },
async ({ query }) => {
try {
const response = await fetch(`${this.baseUrl}/query/v1/projects/${this.projectId}/chat/`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-API-KEY": this.apiKey,
},
body: JSON.stringify({
integration_id: this.integrationId,
query: query,
}),
});
if (!response.ok) {
return {
content: [
{
type: "text",
text: `Error: kapa.ai API returned ${response.status} - ${response.statusText}`,
},
],
};
}
const data = (await response.json()) as { answer?: string; thread_id?: string; question_answer_id?: string };
return {
content: [
{
type: "text",
text: data.answer || "No answer received",
},
],
};
} catch (error) {
return {
content: [
{
type: "text",
text: `Error: Failed to call kapa.ai API - ${error instanceof Error ? error.message : String(error)}`,
},
],
};
}
}
);
// Search tool for retrieving documentation from Kapa
this.server.tool(
"search_kanzi_sources",
"Search for relevant Kanzi documentation",
{
query: z.string().describe("The search query to find relevant Kanzi documentation"),
},
async ({ query }) => {
try {
const response = await fetch(`${this.baseUrl}/query/v1/projects/${this.projectId}/search/`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-API-KEY": this.apiKey,
},
body: JSON.stringify({
query: query,
}),
});
if (!response.ok) {
return {
content: [
{
type: "text",
text: `Error: kapa.ai API returned ${response.status} - ${response.statusText}`,
},
],
};
}
const data = await response.json();
return {
content: [
{
type: "text",
text: JSON.stringify(data, null, 2),
},
],
};
} catch (error) {
return {
content: [
{
type: "text",
text: `Error: Failed to call kapa.ai API - ${error instanceof Error ? error.message : String(error)}`,
},
],
};
}
}
);
}
}
// Define types
interface Env {
KAPA_API_KEY?: string;
KAPA_PROJECT_ID?: string;
KAPA_INTEGRATION_ID?: string;
MCP_OBJECT: DurableObjectNamespace;
}
// Use the built-in serve method!
export default MyMCP.serve("/mcp");