How can my app ask for approval before Claude Code runs a shell command?

June 14, 2025

In June 2025 I wanted to build something with Claude Code. Using the SDK looked like the quickest way to get its coding tools into an app of my own. I remember thinking the SDK had just come out, per the reddit post.1 The comments discussed scripting the command-line interface and reading its JSON output. That interface was already on Hacker News on May 19. The Python package was newer. Anthropic uploaded claude-code-sdk 0.0.10 on June 12, two days before I looked at it.2

The question I got stuck on was what would happen when Claude wanted to run a command. I asked DeepSeek about permissions and got an answer about API keys. An API key lets the app reach the model. I wanted the person using my app to see the command and decide whether to run it. I asked again that evening.3

when execute command it needs permission from user, how to handle this programmatically using sdk

Where does the approval request go in the June 2025 SDK?

Suppose I ask the agent to run the project's tests. It proposes using its shell tool, Bash, with the command npm test. I want my app to show that exact command and wait for a decision before it runs. Printing the agent's streamed JSON output would give me a transcript. Where do I send the user's answer? The examples I had open covered file processing, scripts, streamed JSON, and CLI options.4

In Python SDK 0.0.10, query() started the Claude Code CLI as a child process. The wrapper configured two separate things. It requested stream-json for output, and it translated the Python option permission_prompt_tool_name into the CLI flag --permission-prompt-tool. The CLI described it as an “MCP tool to use for permission prompts (only works with --print)”. The Python wrapper already supplied --print when it launched the child process.56

A working approval tool for one command

Here is how I would wire up that June interface for a Linux desktop. Use a Python 3.10+ virtual environment, an authenticated Claude Code CLI 1.0.24 on your path, and Zenity for the confirmation window. Install the Python dependencies together. The Pydantic pins keep this older MCP release compatible with its validation library.67

python -m pip install claude-code-sdk==0.0.10 mcp==1.9.3 pydantic==2.11.5 pydantic-settings==2.9.1

Save the two Python files below beside each other.

First, save the approval tool as review.py. Model Context Protocol (MCP) lets the CLI call a named tool in another process. Here the tool receives the name Bash and the full proposed input, such as {"command": "npm test"}. It shows what it received. Zenity returns exit code zero when the user clicks Run once. Clicking Decline or closing the window produces a denial.

import json
import subprocess

from mcp.server.fastmcp import FastMCP

server = FastMCP("review")


@server.tool()
def approve(tool_name: str, input: dict) -> str:
    """Ask the user whether Claude Code may run this particular command."""
    decision = {"behavior": "deny", "message": "User declined the command."}
    if tool_name != "Bash":
        return json.dumps({"behavior": "deny", "message": "This dialog reviews Bash only."})

    try:
        dialog = subprocess.run([
            "zenity", "--question", "--no-markup", "--default-cancel",
            "--title=Allow Claude Code to use Bash?",
            "--ok-label=Run once", "--cancel-label=Decline",
            "--text", json.dumps(input, indent=2),
        ])
    except OSError:
        return json.dumps({"behavior": "deny", "message": "Approval dialog unavailable."})

    if dialog.returncode == 0:
        decision = {"behavior": "allow", "updatedInput": input}
    return json.dumps(decision)


if __name__ == "__main__":
    server.run(transport="stdio")

Then register that tool from the app in app.py. Pass the desktop session variables to the child process so it can open the dialog while its standard input and output carry MCP messages. The server name review and the function name approve form the CLI tool name mcp__review__approve. Leaving Bash off the allowlist lets commands reach the dialog when the existing permission rules call for a decision.568

import asyncio
import os
import sys
from pathlib import Path

from claude_code_sdk import ClaudeCodeOptions, query


async def main():
    server_file = Path(__file__).with_name("review.py").resolve()
    display_vars = ("DISPLAY", "XAUTHORITY", "WAYLAND_DISPLAY", "XDG_RUNTIME_DIR",
                    "DBUS_SESSION_BUS_ADDRESS")
    review_server = {
        "command": sys.executable,
        "args": [str(server_file)],
        "env": {key: os.environ[key] for key in display_vars if key in os.environ},
    }
    options = ClaudeCodeOptions(
        mcp_servers={"review": review_server},
        permission_prompt_tool_name="mcp__review__approve",
    )
    async for message in query(prompt="Run npm test in this project.", options=options):
        print(message)


if __name__ == "__main__":
    asyncio.run(main())

Run python app.py from the project's directory. When the command requires approval, the CLI waits for the MCP reply while the user reads the dialog. FastMCP puts the string returned by approve into a text block, and CLI 1.0.24 reads the decision as JSON from that block. On Run once, Claude Code receives the reviewed input and runs the command. On Decline, it receives the reason and skips that call. The dialog never launches npm test itself.67

Did the Claude Coder extension use that permission API?

I had looked at Anthropic’s editor integration and project memory guides.9 I opened Kodu's Claude Coder Marketplace listing because it offered just the interaction I had in mind.10 I wanted to see whether it used the Claude Code SDK and how it connected the permission prompt to a button in VS Code.

In the April source for Claude Coder 2.3.13, the extension calls Claude as a model and implements command execution itself. Its manifest matches the Marketplace extension I opened. Two model connections in the source explain why the name “Claude SDK” can be confusing here.10

Connection selected in the extensionHow the request leaves VS Code
Anthropic directlyKodu calls createAnthropic({apiKey}).languageModel(modelId) from Vercel's @ai-sdk/anthropic adapter and uses streamText from the ai package to send the messages and read the response.11
Kodu's serviceKodu uses message types from Anthropic's general-purpose @anthropic-ai/sdk package to describe the request in TypeScript. The network call itself is axios.post(getKoduInferenceUrl(), …), which returns a stream. The extension source shows this first hop to Kodu's service.12

Neither path calls the Claude Code SDK to approve or execute commands. The extension parses tool tags from the model's streamed text. When it recognizes an execute_command request, its own runner asks for approval and waits. Here is the path for a command that requires a click.131415

sequenceDiagram
    actor User
    participant K as Claude Coder in VS Code
    participant M as Selected model service
    participant T as VS Code terminal
    K->>M: Send task and conversation
    M-->>K: Stream a request to run npm test
    K->>User: Allow npm test?
    alt Run once
        User->>K: Approve
        K->>T: Run npm test
        T-->>K: Command output
        K->>M: Include the result in the next turn
    else Decline
        User->>K: Reject
        K->>M: Report rejection or user feedback
    end

The line I was looking for turned out to be the runner's check for yesButtonTapped. On approval it reaches terminalManager.runCommand. On rejection it returns early, carrying any written feedback into the conversation. If I built my app on Claude Code SDK instead, the same two buttons would answer the MCP request in review.py, and Claude Code would own the terminal operation.1513

What would I use in the later Claude Agent SDK?

The later Python package, claude-agent-sdk, exposes a can_use_tool callback on ClaudeAgentOptions. For a shell call that reaches the callback, the proposed command is in input_data["command"]. An app can show it, await the user's choice, then return PermissionResultAllow(updated_input=input_data) or PermissionResultDeny(message="User declined to run the tests."). Anthropic's Python example shows how to wire the callback into a streaming session.16

In August I explored what it takes to build a tool executor of my own. What appealed to me about the SDK in June was how much less I would have to build. My app could ask for consent. Claude Code could run the approved command, collect the output, and bring it back into the conversation.

References

Footnotes

  1. coding_workflow. (n.d.). Comment on the Claude Code SDK discussion. Reddit, r/ClaudeAI. See the comment on CLI and JSON output. Also see sync. (2025, May 19). Claude Code SDK. Hacker News. ↩

  2. Anthropic. (2025, June 12). Claude Code SDK 0.0.10 [Python distribution]. PyPI. Release files and upload dates. ↩

  3. Cai, B. (2025, June 14). Handling Permissions in Claude SDK Guide [Private DeepSeek conversation]. Second user message, 18:48 Shanghai time. ↩

  4. Anthropic. (n.d.). Agent SDK overview. Claude Code Docs. Saved section links for processing files, script integration, streaming JSON output, and available CLI options. These fragments come from the former SDK guide and may open the top of the revised overview. See also the CLI reference. ↩

  5. Anthropic. (2025, June 12). Claude Code SDK for Python (commit 54bff2e). GitHub. Python SDK repository. See the query interface, public options, and construction of the CLI command. ↩ ↩2

  6. Anthropic. (2025, June 14). Claude Code 1.0.24 [CLI distribution]. npm. Claude Code repository and versioned package, cli.js, option text for --permission-prompt-tool and the parser for the first MCP text block. ↩ ↩2 ↩3 ↩4

  7. Model Context Protocol. (2025). MCP Python SDK 1.9.3. PyPI. Tools and direct execution. ↩ ↩2

  8. Anthropic. (n.d.). Security and Settings. Claude Code Docs. The saved links point to tools available to Claude and permission settings. The June implementation is pinned in the CLI and Python sources above. ↩

  9. Anthropic. (n.d.). Use Claude Code in VS Code and How Claude remembers your project. Claude Code Docs. Editor integration and project memory. ↩

  10. Kodu AI. (2025, April 30). Claude Coder (commit 60c1a71). GitHub. Visual Studio Marketplace listing, extension manifest and project's link to the Marketplace listing. ↩ ↩2

  11. Kodu AI. (2025, April 30). Custom API handler. GitHub. Anthropic model construction and streaming the selected model. ↩

  12. Kodu AI. (2025, April 30). Kodu API handler. GitHub. Selecting the handler and typed request body and HTTP call. ↩

  13. Kodu AI. (2025, April 30). Task executor. GitHub. Parsing tool requests in the stream and collecting tool results for the conversation. ↩ ↩2

  14. Kodu AI. (2025, April 30). AskManager. GitHub. Receiving a response and creating a pending request. ↩

  15. Kodu AI. (2025, April 30). Execute command tool. GitHub. Approval, rejection, and terminal execution. ↩ ↩2

  16. Anthropic. (n.d.). Handle approvals and user input. Claude Code Docs. Tool approval example, Python tab. ↩

© 2025 borui. All rights reserved. This content may be freely reproduced, displayed, modified, or distributed with proper attribution to borui and a link to the article: borui (2025-06-14). How can my app ask for approval before Claude Code runs a shell command?. https://caiborui.com/blog/2025-06-14-en-claude-code-sdk-command-approval

@misc{borui2025-ae7b7195,
  author = {borui},
  title = {{How can my app ask for approval before Claude Code runs a shell command?}},
  year = {2025},
  publisher = {borui's blog},
  url = {https://caiborui.com/blog/2025-06-14-en-claude-code-sdk-command-approval}
}