-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcanUseTool.ts
More file actions
89 lines (77 loc) · 2.31 KB
/
canUseTool.ts
File metadata and controls
89 lines (77 loc) · 2.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import type { MessageQueue } from "utils/MessageQueue"
import type {
PermissionUpdate,
PermissionResult,
} from "@anthropic-ai/claude-agent-sdk"
export interface CanUseToolOptions {
messageQueue: MessageQueue
onToolPermissionRequest?: (toolName: string, input: any) => void
setIsProcessing?: (value: boolean) => void
}
export const createCanUseTool = (options: CanUseToolOptions) => {
const { messageQueue, onToolPermissionRequest, setIsProcessing } = options
const canUseTool = async (
toolName: string,
input: any,
options: {
signal: AbortSignal
suggestions?: PermissionUpdate[]
}
): Promise<PermissionResult> => {
if (onToolPermissionRequest) {
onToolPermissionRequest(toolName, input)
}
const userResponse = await messageQueue.waitForPermissionResponse()
const response = userResponse.toLowerCase().trim()
const CONFIRM = ["y", "yes", "allow"].includes(response)
const DENY = ["n", "no", "deny"].includes(response)
if (CONFIRM) {
const updatedPermissions: PermissionUpdate[] | undefined = (() => {
switch (true) {
// Claude Agent SDK tools can be auto-updated via suggestions from SDK
case options.suggestions && options.suggestions.length > 0: {
return options.suggestions
}
// MCP tools require custom rules, since they are not known ahead
// of time
case toolName.startsWith("mcp__"): {
return [
{
type: "addRules",
rules: [{ toolName }],
behavior: "allow",
destination: "session",
},
]
}
}
})()
return {
behavior: "allow",
updatedInput: input,
updatedPermissions,
}
}
// Keep isProcessing true so UI shows "Agent is thinking..." while it responds
if (setIsProcessing) {
setTimeout(() => {
setIsProcessing(true)
}, 50)
}
if (DENY) {
return {
behavior: "deny",
message: "User denied permission",
interrupt: true,
}
}
// If user typed anything other than yes/no, pass it as new input
// and interrupt.
return {
behavior: "deny",
message: userResponse,
interrupt: true,
}
}
return canUseTool
}