Skip to main content
Glama
cbxss
by cbxss

spawn_and_attach

Force stop an Android app, launch it fresh, and attach Frida for reliable hooking. Avoids timeouts common with connect(spawn=True).

Instructions

Force stop app, launch fresh, and attach Frida. The reliable alternative to connect(spawn=True) which often times out.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
packageYesApp package name (e.g., 'com.bestbuy.android')
device_idNoDevice ID (optional)
wait_msNoTime to wait for app to start in ms (default: 3000)

Implementation Reference

  • The handler function that implements the spawn_and_attach tool logic. It force-stops the app, launches fresh, and attaches Frida by delegating to connect() with spawn=True.
    def spawn_and_attach(
        package: str,
        device_id: str | None = None,
        wait_ms: int = 5000,
    ) -> dict:
        """Force stop app, launch fresh, and attach Frida."""
        return connect(package, device_id, spawn=True, timeout_ms=wait_ms)
  • The Tool definition with inputSchema for spawn_and_attach, declaring 'package' (required string), 'device_id' (optional string), and 'wait_ms' (optional integer).
    Tool(
        name="spawn_and_attach",
        description="Force stop app, launch fresh, and attach Frida. The reliable alternative to connect(spawn=True) which often times out.",
        inputSchema={
            "type": "object",
            "properties": {
                "package": {"type": "string", "description": "App package name (e.g., 'com.bestbuy.android')"},
                "device_id": {"type": "string", "description": "Device ID (optional)"},
                "wait_ms": {"type": "integer", "description": "Time to wait for app to start in ms (default: 3000)"},
            },
            "required": ["package"],
        },
    ),
  • The dispatch/registration point in server.py that routes 'spawn_and_attach' calls to device.spawn_and_attach().
    elif name == "spawn_and_attach":
        return device.spawn_and_attach(
            arguments["package"],
            arguments.get("device_id"),
            arguments.get("wait_ms", 3000),
        )
  • The connect() function that spawn_and_attach delegates to. It handles force-stopping the app, launching via monkey, waiting for PID, attaching Frida, and loading the agent.
    def connect(
        target: str,
        device_id: str | None = None,
        spawn: bool = False,
        timeout_ms: int = 15000,
    ) -> dict:
        """Connect to an app by name/bundle ID or PID."""
        # Disconnect existing active session
        active = registry.get_active()
        if active:
            registry.remove(active.id)
    
        # Get device
        if device_id:
            device = frida.get_device(device_id)
        else:
            device = frida.get_usb_device(timeout=10)
    
        # Ensure SELinux is permissive
        selinux_status = ensure_selinux_permissive(device_id)
    
        # Determine if target is PID or name
        pid = None
        spawn_method = None
        try:
            pid = int(target)
            frida_session = device.attach(pid)
            target_name = target
        except ValueError:
            if spawn:
                # Force stop the app
                adb_shell(["am", "force-stop", target], device_id)
    
                # Wait for process to die
                for _ in range(10):
                    time_module.sleep(0.2)
                    if not adb_shell(["pidof", target], device_id):
                        break
    
                time_module.sleep(0.3)
    
                # Launch via monkey
                adb_shell([
                    "monkey", "-p", target,
                    "-c", "android.intent.category.LAUNCHER", "1"
                ], device_id)
    
                # Wait for PID
                pid = wait_for_pid(target, device_id, timeout_ms)
                frida_session = device.attach(pid)
                spawn_method = "adb_launch"
            else:
                frida_session = device.attach(target)
            target_name = target
    
        # Load agent
        agent_source = get_agent_source()
        script = frida_session.create_script(agent_source)
    
        actual_pid = pid
        if actual_pid is None:
            try:
                actual_pid = frida_session._impl.pid
            except Exception:
                actual_pid = 0
    
        script.load()
        api = script.exports_sync
    
        # Register session
        fs = registry.create(
            device=device,
            session=frida_session,
            api=api,
            target=target_name,
            pid=actual_pid,
        )
    
        # Message handler
        def on_message(message, data):
            if message["type"] == "send":
                payload = message['payload']
                display = str(payload)[:200] + '...' if len(str(payload)) > 200 else str(payload)
                print(f"[FRIDA] {display}", file=sys.stderr)
                if isinstance(payload, str) and payload.startswith('['):
                    fs.add_message("agent", payload)
            elif message["type"] == "error":
                print(f"[ERROR] {message.get('stack', message)}", file=sys.stderr)
    
        script.on("message", on_message)
    
        result = {
            "status": "connected",
            "session_id": fs.id,
            "device": device.name,
            "target": target_name,
            "pid": actual_pid,
            "selinux": selinux_status,
        }
        if spawn_method:
            result["spawn_method"] = spawn_method
        return result
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations provided. Description discloses core behavior (force stop, launch, attach) but omits details like side effects of force stopping, whether Frida session ID is returned, or required prerequisites (e.g., Frida server running). With zero annotation coverage, more transparency would improve this score.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Two sentences, no wasted words. Front-loaded with the action and immediately provides comparison for usage context.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Does not explain return value (e.g., session handle), error scenarios, or prerequisites. For a tool combining multiple operations (force stop, launch, attach), this leaves the agent uncertain about expected outcomes and failure modes.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Input schema has 100% coverage with clear descriptions for each parameter. The tool description adds no additional meaning beyond what the schema provides, so baseline 3 is appropriate.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

Clearly states the action: force stop app, launch fresh, and attach Frida. Distinguishes from sibling 'connect' by positioning as a reliable alternative.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Explicitly names 'connect(spawn=True)' as an alternative and suggests using this tool when that times out. Does not mention other alternatives like 'launch_app' or 'stop_app'.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/cbxss/frida-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server