(_onFinish: unknown, options?: OnChatMessageOptions)
| 44 | @callable() |
| 45 | async removeServer(serverId: string) { |
| 46 | await this.removeMcpServer(serverId); |
| 47 | } |
| 48 | |
| 49 | async onChatMessage(_onFinish: unknown, options?: OnChatMessageOptions) { |
| 50 | const mcpTools = this.mcp.getAITools(); |
| 51 | const workersai = createWorkersAI({ binding: this.env.AI }); |
| 52 | |
| 53 | const result = streamText({ |
| 54 | model: workersai("@cf/moonshotai/kimi-k2.7-code", { |
| 55 | sessionAffinity: this.sessionAffinity |
| 56 | }), |
| 57 | system: `You are a helpful assistant that can understand images. You can check the weather, get the user's timezone, run calculations, and schedule tasks. When users share images, describe what you see and answer questions about them. |
| 58 | |
| 59 | ${getSchedulePrompt({ date: new Date() })} |
| 60 | |
| 61 | If the user asks to schedule a task, use the schedule tool to schedule the task.`, |
| 62 | // Prune old tool calls and reasoning to save tokens on long conversations |
| 63 | messages: pruneMessages({ |
| 64 | messages: await convertToModelMessages(this.messages), |
| 65 | toolCalls: "before-last-2-messages", |
| 66 | reasoning: "before-last-message" |
| 67 | }), |
| 68 | tools: { |
| 69 | // MCP tools from connected servers |
| 70 | ...mcpTools, |
| 71 | |
| 72 | // Server-side tool: runs automatically on the server |
| 73 | getWeather: tool({ |
| 74 | description: "Get the current weather for a city", |
| 75 | inputSchema: z.object({ |
| 76 | city: z.string().describe("City name") |
| 77 | }), |
| 78 | execute: async ({ city }) => { |
| 79 | // Replace with a real weather API in production |
| 80 | const conditions = ["sunny", "cloudy", "rainy", "snowy"]; |
| 81 | const temp = Math.floor(Math.random() * 30) + 5; |
| 82 | return { |
| 83 | city, |
| 84 | temperature: temp, |
| 85 | condition: |
| 86 | conditions[Math.floor(Math.random() * conditions.length)], |
| 87 | unit: "celsius" |
| 88 | }; |
| 89 | } |
| 90 | }), |
| 91 | |
| 92 | // Client-side tool: no execute function — the browser handles it |
| 93 | getUserTimezone: tool({ |
| 94 | description: |
| 95 | "Get the user's timezone from their browser. Use this when you need to know the user's local time.", |
| 96 | inputSchema: z.object({}) |
| 97 | }), |
| 98 | |
| 99 | // Approval tool: requires user confirmation before executing |
| 100 | calculate: tool({ |
| 101 | description: |
| 102 | "Perform a math calculation with two numbers. Requires user approval for large numbers.", |
| 103 | inputSchema: z.object({ |
nothing calls this directly
no outgoing calls
no test coverage detected