Skip to main content

frida-code-mode

Write TypeScript instrumentation for Frida 17, compile it into a single bundle with frida-compile, and run it on Android or iOS with attributed telemetry, live RPC queries, and same-PID hot reload with automatic rollback.

  • Frida 17 ready: bundles frida-java-bridge, frida-objc-bridge, and frida-swift-bridge once per agent, catching removed GumJS APIs at compile time.
  • Hot reload + rollback: swap hooks inside a live process without restarting the target; runtime init errors automatically restore the last working bundle.
  • Two communication paths: asynchronous send() event streams (_fcm envelope) plus synchronous generation-checked RPC queries via call_export.
  • Three ways to use: MCP server for AI agents, CLI/REPL for interactive testing, or Python SDK for security pipelines.

Live Mobile Hacking Lab demos

Both captures below were recorded against real Mobile Hacking Lab targets (Secure Notes on Android API 31 and No Escape on an iPhone X running iOS 16.7.16). Each session spawns the app, captures real hooks, queries live state with call_export, hot-reloads in the same PID, and recovers automatically when a broken hook is loaded. See the release verification matrix.

Android API 31 · Secure Notes iOS 16.7.16 · No Escape
Live MCP v1.0.0 capture on Secure Notes (Android API 31): spawn, SecretDataProvider.query hook, app_surface RPC query, decryptSecret reload, and auto-rollback Live MCP v1.0.0 capture on No Escape (iOS 16.7.16): early stat() jailbreak probe, jb_probes RPC query, stat() bypass reload, and auto-rollback

1. MCP Server (AI Agents)

Works with Claude Code, Antigravity, Cursor, and Gemini CLI over stdio (frida-code-mode-mcp). Requires Python 3.10+ and Node.js/npm.

{
  "mcpServers": {
    "frida-code-mode": {
      "command": "uvx",
      "args": ["--from", "frida-code-mode[mcp]", "frida-code-mode-mcp"]
    }
  }
}
MCP tools
Tool Purpose
use_frida Compile TypeScript (code or entry), spawn/attach, and optionally keep a session_id alive for same-PID hot reload
call_export Discover or invoke registered RPC queries (queries in runHooks) bound to the active generation
drain_session Read queued HookEvent observations after manual or automated app interaction
close_session Detach from the target and release the session (kill_process=True terminates the app)
list_sessions List open sessions with pid, generation, and agent_sha256
list_devices / ensure_server Inspect adb devices and ensure a matching frida-server on Android

Example MCP workflow

  1. Start a persistent session (keep_alive=True):
use_frida(
    package="com.mobilehackinglab.securenotes",
    description="Trace SecretDataProvider queries",
    keep_alive=True,
    code="""
    const Prov = Java.use("com.mobilehackinglab.securenotes.SecretDataProvider");
    Prov.query.implementation = function (uri: any, proj: any, sel: any, args: any, sort: any) {
      t.hit({ uri: String(uri), selection: String(sel) });
      return this.query(uri, proj, sel, args, sort);
    };
    """,
)
# -> {"ok": true, "session_id": "7fddf7a454d3", "pid": 5145, "generation": "081201fe..."}
  1. Hot-reload into the same PID (reuse session_id):
use_frida(
    session_id="7fddf7a454d3",
    description="Also trace decryptSecret",
    code="""
    const Prov = Java.use("com.mobilehackinglab.securenotes.SecretDataProvider");
    Prov.decryptSecret.implementation = function (pin: string) {
      const out = this.decryptSecret(pin);
      t.hit({ pin, unlocked: out !== null });
      return out;
    };
    """,
)
  1. Safe failure: if a reloaded script throws during initialization (such as a misspelled Java or ObjC class), use_frida returns ok: false, rolled_back: true while keeping pid alive on the last working bundle. Call drain_session to collect events after interacting with the app, then close_session.

For full TypeScript modules with RPC queries, pass entry="path/to/agent.ts" and invoke call_export(session_id, name="...", expected_generation=generation). See docs/INTEGRATING.md.


2. CLI & Live REPL

Install the CLI with uv or pip:

uv tool install "frida-code-mode"

Inline execution (exec)

Run a TypeScript snippet without scaffolding a project. Java, t (Telemetry), and config are pre-wired for snippets:

frida-code-mode devices
frida-code-mode server --serial emulator-5554

frida-code-mode exec \
  --package com.mobilehackinglab.securenotes \
  --serial emulator-5554 \
  --duration 6 \
  -c 'const p = Module.findGlobalExportByName("openat");
      if (p) Interceptor.attach(p, {
        onEnter(args) { t.hit({ path: args[1].readUtf8String() }); }
      });'

Events print to stdout as NDJSON (run and exec exit 1 if the agent reports an error):

{"kind": "hook_installed", "hook": "inline", "source": "inline", "seq": 0, "agent_ts": 1796356792.9, "host_ts": 1796356792.5, "data": {}}
{"kind": "hook_hit", "hook": "inline", "source": "inline", "seq": 1, "agent_ts": 1796356793.1, "host_ts": 1796356792.7, "data": {"path": "/data/user/0/com.mobilehackinglab.securenotes/shared_prefs"}}

Scaffold a project and hot-reload (init + repl)

frida-code-mode init ./my-hooks --install
frida-code-mode repl src/index.ts \
  --project ./my-hooks \
  --package com.mobilehackinglab.securenotes \
  --serial emulator-5554

Saving changes under src/ recompiles and reloads the bundle into the running process. If a reload fails at compile time or throws during startup, the REPL restores the previous working bundle.

iOS and remote transports

# iOS over USB
frida-code-mode run src/ios_probe.ts --platform ios --package com.mobilehackinglab.No-Escape

# iOS or jailbroken device over SSH port forwarding
frida-code-mode run src/ios_probe.ts --platform ios --package com.mobilehackinglab.No-Escape \
  --transport ssh --host 192.168.1.50 --ssh-user mobile

# Remote frida-server over TCP (e.g. adb forward tcp:27042 tcp:27042)
frida-code-mode run src/index.ts --package com.mobilehackinglab.securenotes \
  --transport remote --host 127.0.0.1 --remote-port 27042 --no-server

3. Writing TypeScript Hooks & Using the Python SDK

Install the library with pip install frida-code-mode.

TypeScript hook + live RPC query (agent.ts)

import Java from "frida-java-bridge";
import { defineHook, runHooks } from "./runtime.js";

let hits = 0;

const queryHook = defineHook("provider-trace", (t) => {
  const Prov = Java.use("com.mobilehackinglab.securenotes.SecretDataProvider");
  Prov.query.implementation = function (uri: any, proj: any, sel: any, args: any, sort: any) {
    hits += 1;
    t.hit({ uri: String(uri), selection: String(sel) });
    return this.query(uri, proj, sel, args, sort);
  };
  t.installed({ target: "SecretDataProvider.query" });
});

runHooks([queryHook], {
  java: Java as any,
  queries: {
    stats: {
      description: "Return total observed provider queries",
      handler: () => ({ ok: true, value: { hits } }),
    },
  },
});
  • Pass { early: true } to defineHook(id, fn, { early: true }) for native-only Interceptor/Module hooks that must arm while a spawned process is still paused before resume().
  • Pass objc: ObjC as any (from frida-objc-bridge) on iOS so deferred hooks schedule onto the main queue safely under spawn.

Python SDK (CodeModeRunner & CodeModeSession)

from pathlib import Path
from frida_code_mode import (
    CodeModeRunner,
    Platform,
    RunConfig,
    TargetConfig,
    TransportConfig,
    TransportKind,
)

runner = CodeModeRunner(agent_project_dir=Path("agent"))
agent = runner.compile("agent.ts", "build/agent.js")

result = runner.run(
    RunConfig(
        target=TargetConfig(platform=Platform.ANDROID, package="com.mobilehackinglab.securenotes"),
        transport=TransportConfig(kind=TransportKind.USB, serial="emulator-5554"),
        duration=8.0,
    ),
    agent,
)

for event in result.hits():
    print(event.hook, event.data)

For long-lived sessions with call_export() and hot-reload, or wrapping an existing frida.core.Device, see docs/INTEGRATING.md.


Why Frida 17 Needs Compiled Hooks

  1. Runtime bridges are separate packages: Java, ObjC, and Swift are no longer globals in GumJS. Uncompiled scripts throw ReferenceError: Java is not defined unless they import the bridge and bundle with frida-compile.
  2. Removed APIs are caught before runtime: Module.findExportByName(null, name) was removed in Frida 17 in favor of Module.findGlobalExportByName(name). Type-checking against @types/frida-gum catches breaking changes before touching the device.
  3. One bundle prevents the two-bridge collision: loading two separately compiled frida-java-bridge bundles into one process silently drops Java hooks (0 events). runHooks([...], { java }) composes hooks into a single bundle so the bridge is imported once.

Events vs. Live Queries

  • Telemetry (send() / _fcm envelope): every Telemetry call (t.installed, t.hit, t.error, t.log, t.custom) emits a monotonic _fcm envelope so the observed app cannot spoof hook attribution:
{
  "_fcm": { "v": 1, "kind": "hook_hit", "hook": "provider-trace", "seq": 2, "ts": 1796356792942 },
  "uri": "content://com.mobilehackinglab.securenotes.secretprovider",
  "selection": "pin=1234"
}
  • Live RPC queries (call_export): synchronous bounded JSON calls (2s timeout, 8 KiB args, 64 KiB result) tagged with an opaque generation ID so stale calls after a reload or rollback fail explicitly instead of silently reading the wrong script.

See docs/CONTRACT.md for the full v1 wire contract and error taxonomy.


Architecture & Docs

frida_code_mode/
  workspace.py       Embedded TS template, managed cache, inline snippet wrapper
  compiler.py        frida-compile wrapper with sha256 verification
  events.py          _fcm envelope parser -> typed HookEvent
  config.py          RunConfig / TargetConfig / TransportConfig
  transport/         USB, remote TCP, SSH forward, and iproxy transports
  android/           Injectable adb wrapper + frida-server provisioning & recovery
  session.py         spawn/attach -> load -> stream -> reload -> call_export -> detach
  runner.py          One-shot orchestration with cooperative budget & retention caps
  repl.py            File watcher -> recompile -> hot-reload with rollback
  cli.py             devices / server / init / compile / run / exec / repl
  mcp.py             Stateful MCP server (use_frida / call_export / drain_session / close_session)

Development

python3 -m venv .venv && .venv/bin/pip install -e ".[dev]"
(cd agent && npm install)

.venv/bin/ruff check .
.venv/bin/pytest
(cd agent && npm run typecheck && npm test && npm run build)

License

MIT

Metadata

Release files for frida-code-mode 1.0.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for frida-code-mode 1.0.0
File Size Uploaded Provenance Actions
frida_code_mode-1.0.0.tar.gz 98.8 kB With provenance Details for frida_code_mode-1.0.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for frida-code-mode 1.0.0
File Interpreter ABI Platform Actions
frida_code_mode-1.0.0-py3-none-any.whl Python 3 none any Details for frida_code_mode-1.0.0-py3-none-any.whl

Total release size: 170.3 kB

Release files / frida_code_mode-1.0.0.tar.gz

Download URL frida_code_mode-1.0.0.tar.gz
Size 98.8 kB
Tags Source
SHA-256 checksum
How to use checksums
87bc06effdd6ba2573c5f44b9dd4118a29182a1be86dc9b70ab6ad0aded484f4
BLAKE2b-256 checksum
How to use checksums
dcf676f32376f01c58cc8b79d25b837966d12f307a2e23ebce0720dadaab361f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 4, 2026.

Transparency log

Release files / frida_code_mode-1.0.0-py3-none-any.whl

Download URL frida_code_mode-1.0.0-py3-none-any.whl
Size 71.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
2da7bd60b47bf127df57caf1fa4415e2c1822794110faf112c35fa7171423864
BLAKE2b-256 checksum
How to use checksums
fed08857606b0858fdebeb01d128d6d28e0064957ae0ed514dd295d561afa113
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 4, 2026.

Transparency log

Security for frida-code-mode 1.0.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for frida_code_mode-1.0.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 4, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

1.0.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page