Skip to content

Commit f66f274

Browse files
committed
fix(agents): enforce native policy in Anthropic SDK
1 parent 29f39af commit f66f274

9 files changed

Lines changed: 382 additions & 193 deletions

File tree

‎docs/gateway/cli-backends.md‎

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -136,11 +136,16 @@ claude update
136136
The bundled `claude-cli` backend prefers Claude Code's native skill resolver. When the current skills snapshot has at least one selected skill with a materialized path, OpenClaw passes a temporary Claude Code plugin via `--plugin-dir` and omits the duplicate OpenClaw skills catalog from the appended system prompt. Without a materialized plugin skill, OpenClaw keeps the prompt catalog as a fallback. Skill env/API key overrides still apply to the child process environment for the run.
137137

138138
The Agent SDK always runs with Claude Code's default permission mode.
139-
OpenClaw's existing effective exec policy remains authoritative through SDK
140-
permission callbacks and a `PreToolUse` hook, including when user settings
141-
would otherwise preapprove a tool. Per-agent and session restrictions still
142-
override broader global policy. OpenClaw-owned MCP tools remain authorized by
143-
the Gateway rather than receiving a second Claude-native approval.
139+
OpenClaw supplies a managed ask rule so every schema-valid executable call
140+
reaches the SDK permission callback, even when user settings would otherwise
141+
preapprove it. The callback runs OpenClaw's canonical `before_tool_call`
142+
policy before native exec policy and approval. Per-agent and session
143+
restrictions still override broader global policy. OpenClaw-owned MCP tools
144+
already execute canonical policy inside the Gateway, so the adapter allows
145+
those exact `mcp__openclaw__*` calls without a duplicate approval; other MCP
146+
tools remain host-permission controlled. Claude Code rejects schema-invalid
147+
tool input before any permission callback, so policy parity applies to
148+
schema-valid executable calls.
144149

145150
When the effective exec ask setting is `on-miss` or `always`, OpenClaw relays
146151
native or extension tool requests as interactive approvals to the session's

‎docs/providers/anthropic.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,8 @@ OpenClaw release:
107107
OpenClaw detects the existing Claude CLI login. Normal agent turns use
108108
the official Agent SDK with the installed, authenticated Claude Code
109109
executable, including native-tool turns whose approvals remain under
110-
OpenClaw control. Imported native OAuth profiles reuse the verified
110+
OpenClaw control. Schema-valid native calls pass through OpenClaw's
111+
canonical tool policy before native approval. Imported native OAuth profiles reuse the verified
111112
Claude Code login; explicitly selected API-key or token credentials
112113
still use protected file-descriptor forwarding. Isolated side-question
113114
completions and paired-node execution retain the supervised CLI path.

‎extensions/anthropic/agent-sdk.runtime.permissions.test.ts‎

Lines changed: 50 additions & 69 deletions
Original file line numberDiff line numberDiff line change
@@ -75,26 +75,6 @@ function sdkNativeTool(options: Record<string, unknown>): SdkNativeToolCallback
7575
return options.canUseTool as SdkNativeToolCallback;
7676
}
7777

78-
type SdkPreToolUseCallback = (
79-
input: {
80-
hook_event_name: "PreToolUse";
81-
tool_name: string;
82-
tool_input: unknown;
83-
tool_use_id: string;
84-
},
85-
toolUseId: string | undefined,
86-
options: { signal: AbortSignal },
87-
) => Promise<unknown>;
88-
89-
function sdkPreToolUse(options: Record<string, unknown>): SdkPreToolUseCallback {
90-
const hooks = options.hooks as { PreToolUse?: Array<{ hooks?: SdkPreToolUseCallback[] }> };
91-
const callback = hooks.PreToolUse?.[0]?.hooks?.[0];
92-
if (!callback) {
93-
throw new Error("Claude Agent SDK did not register its native permission hook.");
94-
}
95-
return callback;
96-
}
97-
9878
afterEach(() => {
9979
queryMock.mockReset();
10080
vi.restoreAllMocks();
@@ -144,74 +124,75 @@ describe("Anthropic Agent SDK native permission bridge", () => {
144124
expect(requestUserInput).toHaveBeenCalledOnce();
145125
});
146126

147-
it("enforces native tool policy before user settings can shadow the permission callback", async () => {
127+
it("forces schema-valid calls through the sole permission callback", async () => {
148128
const requestToolPermission = vi.fn(async () => ({
149129
behavior: "deny" as const,
150130
message: "The session policy denied native execution.",
151131
}));
152132
let nativeDecision: unknown;
153-
let gatewayDecision: unknown;
154-
let malformedDecision: unknown;
133+
let openClawMcpDecision: unknown;
134+
let externalMcpDecision: unknown;
155135
useSdkMessages([SUCCESS_RESULT], async (options) => {
156-
const hook = sdkPreToolUse(options);
136+
const canUseTool = sdkNativeTool(options);
157137
const signal = new AbortController().signal;
158138

159-
nativeDecision = await hook(
160-
{
161-
hook_event_name: "PreToolUse",
162-
tool_name: "Bash",
163-
tool_input: { command: "cat private.txt" },
164-
tool_use_id: "native-tool-shadowed",
165-
},
166-
"native-tool-shadowed",
167-
{ signal },
139+
nativeDecision = await canUseTool(
140+
"Bash",
141+
{ command: "cat private.txt" },
142+
{ signal, toolUseID: "native-tool" },
168143
);
169-
gatewayDecision = await hook(
170-
{
171-
hook_event_name: "PreToolUse",
172-
tool_name: "mcp__openclaw__message",
173-
tool_input: { action: "send" },
174-
tool_use_id: "gateway-tool-owned",
175-
},
176-
"gateway-tool-owned",
177-
{ signal },
144+
openClawMcpDecision = await canUseTool(
145+
"mcp__openclaw__message",
146+
{ action: "send" },
147+
{ signal, toolUseID: "gateway-tool-owned" },
178148
);
179-
malformedDecision = await hook(
180-
{
181-
hook_event_name: "PreToolUse",
182-
tool_name: "Bash",
183-
tool_input: "not-an-object",
184-
tool_use_id: "malformed-native-tool",
185-
},
186-
"malformed-native-tool",
187-
{ signal },
149+
externalMcpDecision = await canUseTool(
150+
"mcp__external__search",
151+
{ query: "policy" },
152+
{ signal, toolUseID: "external-mcp" },
188153
);
189154
});
190155

191156
await collect(createContext({ requestToolPermission }));
192157

158+
expect(sdkOptions().managedSettings).toEqual({ permissions: { ask: ["*"] } });
159+
expect(sdkOptions()).not.toHaveProperty("hooks");
160+
expect(sdkOptions()).not.toHaveProperty("allowedTools");
193161
expect(nativeDecision).toEqual({
194-
hookSpecificOutput: {
195-
hookEventName: "PreToolUse",
196-
permissionDecision: "deny",
197-
permissionDecisionReason: "The session policy denied native execution.",
198-
},
162+
behavior: "deny",
163+
message: "The session policy denied native execution.",
199164
});
200-
expect(gatewayDecision).toEqual({ continue: true });
201-
expect(malformedDecision).toEqual({
202-
hookSpecificOutput: {
203-
hookEventName: "PreToolUse",
204-
permissionDecision: "deny",
205-
permissionDecisionReason: "OpenClaw rejected malformed native tool input.",
206-
},
165+
expect(openClawMcpDecision).toEqual({
166+
behavior: "allow",
167+
updatedInput: { action: "send" },
207168
});
208-
expect(requestToolPermission).toHaveBeenCalledOnce();
209-
expect(requestToolPermission).toHaveBeenCalledWith({
210-
toolName: "Bash",
211-
toolInput: { command: "cat private.txt" },
212-
toolCallId: "native-tool-shadowed",
213-
abortSignal: expect.any(AbortSignal),
169+
expect(externalMcpDecision).toEqual({
170+
behavior: "deny",
171+
message: "The session policy denied native execution.",
214172
});
173+
expect(requestToolPermission).toHaveBeenCalledTimes(2);
174+
expect(requestToolPermission).toHaveBeenNthCalledWith(
175+
1,
176+
expect.objectContaining({ toolName: "Bash" }),
177+
);
178+
expect(requestToolPermission).toHaveBeenNthCalledWith(
179+
2,
180+
expect.objectContaining({ toolName: "mcp__external__search" }),
181+
);
182+
});
183+
184+
it("keeps schema validation SDK-owned before any permission callback", async () => {
185+
useSdkMessages();
186+
187+
await collect(createContext());
188+
189+
expect(sdkOptions()).toEqual(
190+
expect.objectContaining({
191+
managedSettings: { permissions: { ask: ["*"] } },
192+
canUseTool: expect.any(Function),
193+
}),
194+
);
195+
expect(sdkOptions()).not.toHaveProperty("hooks");
215196
});
216197

217198
it("keeps bypass-shaped backend arguments behind the host permission callback", async () => {

‎extensions/anthropic/agent-sdk.runtime.test.ts‎

Lines changed: 9 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -116,28 +116,6 @@ function sdkNativeTool(options: Record<string, unknown>): SdkNativeToolCallback
116116
return callback;
117117
}
118118

119-
type SdkPreToolUseCallback = (
120-
input: {
121-
hook_event_name: "PreToolUse";
122-
tool_name: string;
123-
tool_input: unknown;
124-
tool_use_id: string;
125-
},
126-
toolUseId: string | undefined,
127-
options: { signal: AbortSignal },
128-
) => Promise<unknown>;
129-
130-
function sdkPreToolUse(options: Record<string, unknown>): SdkPreToolUseCallback {
131-
const hooks = options.hooks as {
132-
PreToolUse?: Array<{ hooks?: SdkPreToolUseCallback[] }>;
133-
};
134-
const callback = hooks.PreToolUse?.[0]?.hooks?.[0];
135-
if (!callback) {
136-
throw new Error("Claude Agent SDK did not register its native permission hook.");
137-
}
138-
return callback;
139-
}
140-
141119
function createLiveCapability(
142120
fingerprint = "matching-session-policy",
143121
state: { current?: CliBackendLiveSessionHandle } = {},
@@ -374,20 +352,9 @@ describe("Anthropic Agent SDK runtime ownership", () => {
374352
}
375353
const requestToolPermission = vi.fn(async () => decision);
376354
const input = { command: "cat /tmp/openclaw-proof-private.txt" };
377-
let hookDecision: unknown;
378355
let callbackDecision: unknown;
379356
useSdkMessages([SUCCESS_RESULT], async (options) => {
380357
const signal = new AbortController().signal;
381-
hookDecision = await sdkPreToolUse(options)(
382-
{
383-
hook_event_name: "PreToolUse",
384-
tool_name: "Bash",
385-
tool_input: input,
386-
tool_use_id: "restricted-native-bash",
387-
},
388-
undefined,
389-
{ signal },
390-
);
391358
callbackDecision = await sdkNativeTool(options)("Bash", input, {
392359
signal,
393360
toolUseID: "restricted-native-bash",
@@ -405,29 +372,22 @@ describe("Anthropic Agent SDK runtime ownership", () => {
405372
expect(sdkOptions()).toEqual(
406373
expect.objectContaining({
407374
tools: ["Bash"],
408-
allowedTools: ["mcp__openclaw__message"],
375+
managedSettings: { permissions: { ask: ["*"] } },
409376
settingSources: [],
410377
permissionMode: "default",
411378
}),
412379
);
380+
expect(sdkOptions()).not.toHaveProperty("hooks");
381+
expect(sdkOptions()).not.toHaveProperty("allowedTools");
413382
if (credential) {
414383
expect(sdkOptions().spawnClaudeCodeProcess).toEqual(expect.any(Function));
415384
expect(sdkOptions().env).toEqual(
416385
expect.objectContaining({ CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR: "3" }),
417386
);
418387
expect(JSON.stringify(sdkOptions().env)).not.toContain(credential.token);
419388
}
420-
expect(hookDecision).toEqual({
421-
hookSpecificOutput: {
422-
hookEventName: "PreToolUse",
423-
permissionDecision: decision.behavior,
424-
...(decision.behavior === "allow"
425-
? { updatedInput: decision.updatedInput }
426-
: { permissionDecisionReason: decision.message }),
427-
},
428-
});
429389
expect(callbackDecision).toEqual(decision);
430-
expect(requestToolPermission).toHaveBeenCalledTimes(2);
390+
expect(requestToolPermission).toHaveBeenCalledOnce();
431391
expect(requestToolPermission).toHaveBeenCalledWith(
432392
expect.objectContaining({
433393
toolName: "Bash",
@@ -783,13 +743,13 @@ describe("Anthropic Agent SDK runtime ownership", () => {
783743
expect(sdkOptions()).toEqual(
784744
expect.objectContaining({
785745
tools: [],
786-
allowedTools: ["mcp__openclaw__message"],
746+
managedSettings: { permissions: { ask: ["*"] } },
787747
disallowedTools: ["Bash", "Edit", "Write"],
788748
settingSources: [],
789749
strictMcpConfig: true,
790750
}),
791751
);
792-
expect(sdkOptions().allowedTools).not.toContain("Bash");
752+
expect(sdkOptions()).not.toHaveProperty("allowedTools");
793753
expect(sdkOptions()).not.toHaveProperty("mcpServers");
794754
expect(sdkOptions().extraArgs).toEqual(
795755
expect.objectContaining({ "mcp-config": "/tmp/openclaw-restricted-mcp.json" }),
@@ -845,7 +805,7 @@ describe("Anthropic Agent SDK runtime ownership", () => {
845805
expect(queryMock).not.toHaveBeenCalled();
846806
});
847807

848-
it("expands wildcard MCP grants into only the exact tools admitted by OpenClaw", async () => {
808+
it("does not project argv allow rules into SDK auto-approval", async () => {
849809
useSdkMessages();
850810

851811
await collect(
@@ -861,12 +821,10 @@ describe("Anthropic Agent SDK runtime ownership", () => {
861821
expect(sdkOptions()).toEqual(
862822
expect.objectContaining({
863823
tools: [],
864-
allowedTools: ["mcp__openclaw__message", "mcp__openclaw__memory_search"],
824+
managedSettings: { permissions: { ask: ["*"] } },
865825
}),
866826
);
867-
expect(sdkOptions().allowedTools).not.toContain("mcp__openclaw__*");
868-
expect(sdkOptions().allowedTools).not.toContain("Bash");
869-
expect(sdkOptions().allowedTools).not.toContain("Edit");
827+
expect(sdkOptions()).not.toHaveProperty("allowedTools");
870828
});
871829

872830
it.each([429, 529])(

0 commit comments

Comments
 (0)