> ## Documentation Index
> Fetch the complete documentation index at: https://docs.runlayer.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Runlayer Hooks SDK

> Hook enforcement and telemetry for TypeScript and Python agent runtimes

The Runlayer Hooks SDK wires custom agent runtimes into Runlayer's hook
enforcement and telemetry pipeline. Claude Agent SDK, Vercel Eve, and the Python
Google ADK lifecycle plugin send prompts, available reasoning summaries, tool
calls, and responses into Runlayer [Sessions](https://docs.runlayer.com/platform-sessions.md). The Vercel AI
SDK, OpenAI Agents SDK, TypeScript Google ADK, and custom-runtime tool wrappers
govern tools your process executes directly; emit lifecycle events separately
when those runtimes should also send conversation content. The SDK ships for
**TypeScript** and **Python**, with framework coverage described below.

> [!NOTE]
>
> This SDK does not replace MCP client setup. To connect an agent framework
> (Claude Agent SDK, Vercel AI SDK, OpenAI Agents SDK, Google ADK) to
> Runlayer-hosted MCP servers, see [Agent Frameworks](https://docs.runlayer.com/agent-frameworks.md). Use the
> adapters on this page for local enforcement and supported lifecycle telemetry.
> Vercel Eve and the Python ADK plugin also correlate Runlayer MCP calls with
> their conversation sessions.

## Copy prompt

Paste this into your coding agent to wire Runlayer into an existing agent project:

```text theme={null}
Read the Runlayer Hooks SDK docs at https://docs.runlayer.com/runlayer-hooks-sdk and update my agent code to integrate with Runlayer's hook enforcement and telemetry pipeline.
```

## Capabilities

* lifecycle telemetry through framework hooks or explicit event calls
* pre-tool enforcement with optional argument rewriting
* post-tool output scanning and blocking
* failed tool telemetry
* direct MCP source enforcement
* preflight session emission for ingestion checks
* transcript-bearing `Stop` events for assistant reasoning extraction
* Vercel Eve native runtime lifecycle telemetry
* Python Google ADK native lifecycle plugin (ADK 2.11+)
* framework tool wrappers for Claude Agent SDK, Vercel AI SDK, OpenAI Agents
  SDK, and Google ADK

## Getting started

**1. Install the package**

> [tab] TypeScript
>
> ```bash pnpm theme={null}
> pnpm add @runlayer/hooks-sdk@0.4.0 --save-exact
> ```
>
> ```bash npm theme={null}
> npm install @runlayer/hooks-sdk@0.4.0 --save-exact
> ```
>
> Install the agent framework package you use separately, such as
> `@anthropic-ai/claude-agent-sdk`, `ai`, `@openai/agents`, or `@google/adk`.
> Use Node.js 24.17 or newer within Node 24; Node 25 is not supported.
>
> Verified TypeScript framework versions as of 2026-07-10:
>
> | Surface | Package | Version |
> | - | - | - |
> | Claude Agent SDK hooks | `@anthropic-ai/claude-agent-sdk` | `0.3.172` |
> | Vercel Eve native hooks | `eve` | `0.19.0` |
> | OpenAI Agents SDK tools | `@openai/agents` | `0.11.6` |
> | Vercel AI SDK tools | `ai` | `6.0.200` |
> | Google ADK tools | `@google/adk` | `1.2.0` |

> [tab] Python
>
> ```bash theme={null}
> uv add runlayer-hooks-sdk
> ```
>
> For Claude Agent SDK hooks, also install:
>
> ```bash theme={null}
> uv add claude-agent-sdk==0.1.80
> ```

**2. Create credentials**

Pick the option that matches how the agent runs.

**Deployed or shared agent** — create a Runlayer
[Agent Account](https://docs.runlayer.com/platform-agent-accounts.md) and set:

```bash theme={null}
export RUNLAYER_BASE_URL="https://your-runlayer-instance.com"
export RUNLAYER_AGENT_CLIENT_ID="client_..."
export RUNLAYER_AGENT_CLIENT_SECRET="..."
```

The SDK mints an agent token with `client_credentials` and, when an OBO
subject is configured, exchanges it through RFC 8693 token exchange. It
caches and refreshes both tokens. Do not configure or pass a pre-minted
bearer token. In a shared user-facing agent, resolve the authenticated
caller and create request-scoped OBO credentials; never reuse one fixed
subject across callers.

**Deployment bound to one Runlayer user** — also add a fixed OBO subject:

```bash theme={null}
export RUNLAYER_AGENT_SUBJECT_TOKEN="user@example.com"
export RUNLAYER_AGENT_SUBJECT_TOKEN_TYPE="urn:runlayer:token-type:user-email"
```

**Local, single-user development** — a personal API key is simpler:

```bash theme={null}
export RUNLAYER_BASE_URL="https://your-runlayer-instance.com"
export RUNLAYER_API_KEY="rl_..."
```

For deployed agents, prefer an Agent Account over a shared key: it gives
each deployment its own identity and per-caller OBO attribution.

**3. Confirm the SDK session monitoring client**

Generic SDK integrations attribute events to the first-party Hooks SDK client
(`typescript-sdk` or `python-sdk`). Dedicated adapters retain their runtime
identity; the Eve adapter uses `vercel-eve`. In Runlayer, open **Settings →
Agent session monitoring → Full session scanning APIs → Hook clients** and
confirm the matching session monitoring client is enabled before testing.
Newly supported clients such as Vercel Eve are enabled by default; disable a
client explicitly if its full session content should not be collected. If
the client option is missing, ask a Runlayer admin to enable SDK session
monitoring for the workspace.

**4. Run preflight**

> [!NOTE]
>
> Vercel Eve uses its native event vocabulary. Skip this generic SDK
> preflight for Eve; finish the [Vercel Eve setup](#vercel-eve), run one
> real Eve turn, and verify that session in Runlayer instead.

Verify that Runlayer receives hook events before invoking a real model.

```typescript TypeScript theme={null}
import { RunlayerClient, sendRunlayerPreflight } from "@runlayer/hooks-sdk";

const runlayer = RunlayerClient.fromEnv({ clientVersion: "my-agent/1.0.0" });

const result = await sendRunlayerPreflight(runlayer, {
  prompt: "Runlayer ingestion preflight",
});

console.log(`Runlayer session: ${result.sessionUrl}`);
```

```python Python theme={null}
from runlayer_sdk import RunlayerClient, send_runlayer_preflight

runlayer = RunlayerClient.from_env(client_version="my-agent/1.0.0")

result = send_runlayer_preflight(runlayer, prompt="Runlayer ingestion preflight")

print(result.session_id)
```

Preflight sends a strict `SessionStart`, `UserPromptSubmit`, and `Stop`
sequence for a synthetic session. If any request fails, or if session
monitoring is not enabled for this workspace, the helper throws. TypeScript
prints a Runlayer session URL. Python prints the synthetic external session
ID but does not currently return a Runlayer session URL; open Sessions
immediately and confirm the newest **Python SDK** session appears.

## Configuration

Optional environment variables (identical across languages):

| Variable | Purpose |
| - | - |
| `RUNLAYER_AGENT_CLIENT_ID` | Agent account Client ID for `client_credentials` token exchange. |
| `RUNLAYER_AGENT_CLIENT_SECRET` | Agent account Client Secret for `client_credentials` token exchange. |
| `RUNLAYER_AGENT_SUBJECT_TOKEN` | Optional user identity for OBO agent token exchange. |
| `RUNLAYER_AGENT_SUBJECT_TOKEN_TYPE` | Token type for `RUNLAYER_AGENT_SUBJECT_TOKEN`; use `urn:runlayer:token-type:user-id`, `urn:runlayer:token-type:user-email`, or `urn:ietf:params:oauth:token-type:access_token`. |
| `RUNLAYER_HOOK_CLIENT` | Override the client name sent to Runlayer. Only use this when your deployment supports a dedicated SDK client name. |
| `RUNLAYER_HOOK_DEBUG=1` | Log non-strict hook event failures to stderr. |
| `RUNLAYER_HOOK_TIMEOUT_MS` | Request timeout for Runlayer hook calls. |
| `RUNLAYER_HOOK_MAX_TOOL_OUTPUT_BYTES` | Maximum serialized tool output sent to Runlayer. Defaults to `65536`; larger values are truncated with a marker. |
| `RUNLAYER_HOOK_ENFORCEMENT_FAILURE_MODE` | Enforcement outage behavior. Defaults to `closed`; set to `open` only if your agent should continue when Runlayer cannot be reached. |
| `RUNLAYER_ALLOW_INSECURE_TRANSPORT=1` | Allow a non-HTTPS `RUNLAYER_BASE_URL` for local development only. |
| `RUNLAYER_DIRECT_MCP_SOURCE_ENFORCEMENT_PATH` | Endpoint path for direct MCP source validation, when enabled by your deployment. |

> [!NOTE]
>
> Default request timeouts differ by SDK. TypeScript uses a single `10000` ms
> default. Python uses `30000` ms for enforcement and tool lifecycle hooks,
> `5000` ms for lifecycle event hooks, and `10000` ms for direct endpoint calls.
> Override either with `RUNLAYER_HOOK_TIMEOUT_MS`.

## Runtime safety

Runlayer enforcement is fail-closed (If Runlayer cannot be reached, the call is blocked rather than allowed through) by default. If pre-tool, post-tool, or direct
MCP source enforcement cannot reach Runlayer, the SDK treats the call as blocked.
Lifecycle telemetry is best-effort unless a helper documents strict behavior, such
as preflight and transcript `Stop` emission.

Every hook request uses a timeout, and tool output is capped before upload. Failed
tool outputs include bounded `stdout`, `stderr`, and `output` fields with
truncation metadata when available, so Runlayer can scan failure context without
the SDK uploading unbounded logs.

The SDK skips pre-tool and post-tool enforcement for Runlayer's own MCP server
names and for MCP calls that already traverse the Runlayer proxy, so first-party
traffic is not scanned twice. Third-party MCP tools remain enforced by default. For custom runtimes, use the exported `shouldEnforceTool` /
`should_enforce_tool` helper or the client's tool-enforcement option so new
adapters make the same decision consistently. The base URL must use `https://`
unless insecure transport is explicitly enabled for a trusted local endpoint.

### Block prompts with Prompt Guard

Call `beforePrompt` / `before_prompt` before your bot sends user text to the
model. It records `UserPromptSubmit`, scans the prompt with
[Prompt Guard](https://docs.runlayer.com/runlayer-toolguard.md#prompt-guard), and throws or raises
`RunlayerBlockedError` when Runlayer blocks it. Prompt checks always fail open,
regardless of the enforcement failure mode: if the scan errors or takes longer
than 6 seconds, the prompt goes through. The Claude Agent SDK hooks and the
Python Google ADK plugin call it for you. Available in Hooks SDK 0.4.0.

Runlayer only blocks a prompt when all of these hold:

* The client hooks integration is enabled for the workspace, and Prompt Guard
  is enabled and set to **Block** (the default is **Alert**, which only
  records detections).
* The workspace's AI Watch mode isn't Monitor.
* Runlayer can attribute the prompt to a workspace member. A user API key or an
  agent account works. With an organization key, set `RUNLAYER_USER_EMAIL` (or
  `userEmail` / `user_email`) to a workspace user's email; a bot's end customers
  usually aren't workspace users, so use the bot owner's or a service user's.
  If Runlayer can't attribute the prompt, it skips the scan and allows it.

If Runlayer rejects the scan request or the agent account's token request with
a 401 or 403 (a bad key, or a firewall in front of Runlayer), each client logs
one warning, because prompts aren't being scanned. Other failures allow the
prompt and log only with debug enabled. A scan request carries at most 5 MB of
prompts; past that, the system prompt is trimmed first, then the prompt. A prompt
over the workspace's scan payload budget follows that budget's action: skipped,
truncated, or blocked.

Block replies never include Runlayer's violation details. The Claude Agent SDK
hooks show `blockedPromptMessage` / `blocked_prompt_message`, and the ADK plugin
replies with `blocked_message`; both default to "Sorry, I can't help with that
request."

> [!TIP]
>
> Pass your bot's system prompt as `systemPrompt` / `system_prompt`. Prompt Guard
> scans the user prompt against it and catches more attacks with it. The Claude
> Agent SDK hooks and the ADK plugin send only the user prompt, so call
> `beforePrompt` / `before_prompt` yourself to give Prompt Guard that context.

```ts TypeScript theme={null}
try {
  await runlayer.beforePrompt({ prompt: userText, sessionId, systemPrompt });
} catch (error) {
  if (error instanceof RunlayerBlockedError) return reply("I can't help with that.");
  throw error;
}
```

```python Python theme={null}
try:
    runlayer.before_prompt(prompt=user_text, session_id=session_id, system_prompt=system_prompt)
except RunlayerBlockedError:
    return "I can't help with that."
```

## Vercel Eve

Vercel Eve exposes native runtime hooks for its durable stream lifecycle. Use
the Runlayer Eve adapter to send that lifecycle directly to
[Sessions](https://docs.runlayer.com/platform-sessions.md), without an external relay or polling process.

Install the Hooks SDK in the Eve project:

```bash theme={null}
pnpm add @runlayer/hooks-sdk@0.4.0 --save-exact
```

Create the native hook:

```typescript theme={null}
// agent/hooks/runlayer.ts
import {
  createVercelEveHook,
  RunlayerClient,
} from "@runlayer/hooks-sdk/vercel-eve";

const runlayer = RunlayerClient.fromEnv({
  client: "vercel-eve",
});

export default createVercelEveHook(runlayer, {
  mcpConnectionNames: ["runlayer"],
});
```

Set the Agent Account environment variables shown under
[Create credentials](#getting-started). For OBO attribution by Runlayer user ID,
set:

```bash theme={null}
export RUNLAYER_AGENT_SUBJECT_TOKEN="<runlayer-user-id>"
export RUNLAYER_AGENT_SUBJECT_TOKEN_TYPE="urn:runlayer:token-type:user-id"
```

The generated app-scoped connection already falls back to the Runlayer user who
generated it, so it is fixed-user OBO even when these variables are absent. Use
it unchanged only for a deployment bound to that user. For autonomous M2M,
remove the subject and subject-type arguments from its `getAccessToken` call.
For a shared user-facing agent, set `principalType: "user"`, map the
authenticated principal passed to `getToken` to a Runlayer user, and mint the
OBO token there. Eve then caches authorization per issuer and user. Do not use
one fixed subject for multiple callers.

In Runlayer's Agent Account setup guide, select **Vercel Eve** and create the
generated `agent/connections/runlayer.ts`. It combines renewable
`client_credentials`/OBO authentication with this session-aware header:

```typescript theme={null}
// agent/connections/runlayer.ts
headers: ({ session }) => ({
  "x-runlayer-session-id": session.id,
}),
```

The callback runs with the active Eve session context. One Eve `session.id`,
including all of its turns, maps to one Runlayer Session, and every Runlayer MCP
call correlates with the hook lifecycle from the first request. Do not generate a
second session identifier or replace the generated renewable authentication with
a static bearer token.

Pass every Eve MCP connection slug in `mcpConnectionNames`, including the
Runlayer connection. Runlayer uses this list to tell MCP tool calls apart from
tools your process runs locally; omitting a slug means that connection's calls
may be classified incorrectly.

Run one real Eve turn and open it in Runlayer Sessions to smoke-test this
adapter. `sendRunlayerPreflight()` emits the generic SDK lifecycle vocabulary,
not Eve's native events, so it is not the Eve verification path.

> [!WARNING]
>
> Eve treats a thrown hook as a real turn failure. The Runlayer adapter catches
> and logs lifecycle delivery failures, so Session telemetry is fail-open and a
> Runlayer outage does not fail the Eve turn. This does not make MCP enforcement
> fail-open: calls through the Runlayer proxy still use normal policies and
> scanning. The adapter observes Eve-local tools for Sessions but does not block
> them.

> [!NOTE]
>
> Built-in agent copies inherit the parent hook. Declared subagents have isolated
> hook directories, so install or re-export the Runlayer hook in each declared
> subagent that needs full child visibility. Remote subagents need the hook in
> their own deployment. The parent Session still records the child lifecycle.

## Framework adapters

Wrap the tools your runtime executes so Runlayer can enforce them. Pick your
harness — the language toggle inside each example still controls the whole page.

> [!NOTE]
>
> Claude Agent SDK, Vercel Eve, and the Python Google ADK plugin include
> lifecycle telemetry. Vercel AI SDK, OpenAI Agents SDK, TypeScript Google ADK,
> and custom-runtime wrappers cover local tools only; send lifecycle events
> separately with `emitEvent(...)` / `emit_event(...)` for those runtimes.

> [tab] Claude Agent SDK
>
> Pass Runlayer hooks into Claude Agent SDK's `query` options.
>
> ```typescript TypeScript theme={null}
> import { query } from "@anthropic-ai/claude-agent-sdk";
> import {
>   claudeAgentSdkAssistantMessageToTranscriptLine,
>   createClaudeAgentSdkHooks,
>   emitClaudeAgentSdkTranscriptStop,
>   RunlayerClient,
> } from "@runlayer/hooks-sdk/claude-agent-sdk";
>
> const runlayer = RunlayerClient.fromEnv({ clientVersion: "my-agent/1.0.0" });
>
> const transcriptLines: string[] = [];
> let sessionId: string | undefined;
>
> for await (const message of query({
>   prompt: "Inspect this workspace and summarize the active project.",
>   options: {
>     allowedTools: ["Read", "Glob", "Grep", "Bash"],
>     hooks: createClaudeAgentSdkHooks(runlayer, { includeStop: false }),
>     maxTurns: 4,
>     model: "claude-opus-4-6",
>   },
> })) {
>   if (message.type === "system" && message.subtype === "init") {
>     sessionId = message.session_id;
>   }
>   if (message.type === "assistant") {
>     transcriptLines.push(
>       claudeAgentSdkAssistantMessageToTranscriptLine(message.message),
>     );
>   }
> }
>
> if (sessionId) {
>   await emitClaudeAgentSdkTranscriptStop(runlayer, {
>     model: "claude-opus-4-6",
>     sessionId,
>     transcriptLines,
>   });
> }
> ```
>
> ```python Python theme={null}
> import anyio
> from claude_agent_sdk import AssistantMessage, ClaudeAgentOptions, SystemMessage, query
> from runlayer_sdk import RunlayerClient
> from runlayer_sdk.claude_agent_sdk import (
>     claude_agent_sdk_assistant_message_to_transcript_line,
>     create_claude_agent_sdk_hooks,
>     emit_claude_agent_sdk_transcript_stop,
> )
>
>
> async def main() -> None:
>     runlayer = RunlayerClient.from_env(client_version="my-agent/1.0.0")
>     model = "claude-opus-4-6"
>     transcript_lines: list[str] = []
>     session_id: str | None = None
>
>     options = ClaudeAgentOptions(
>         allowed_tools=["Read", "Glob", "Grep", "Bash"],
>         hooks=create_claude_agent_sdk_hooks(runlayer, include_stop=False),
>         max_turns=4,
>         model=model,
>     )
>
>     async for message in query(prompt="Inspect this workspace.", options=options):
>         if isinstance(message, SystemMessage) and message.subtype == "init":
>             session_id = message.session_id
>         if isinstance(message, AssistantMessage):
>             transcript_lines.append(
>                 claude_agent_sdk_assistant_message_to_transcript_line(message.message)
>             )
>
>     if session_id:
>         emit_claude_agent_sdk_transcript_stop(
>             runlayer, model=model, session_id=session_id, transcript_lines=transcript_lines
>         )
>
>
> anyio.run(main)
> ```
>
> Use `includeStop: false` / `include_stop=False` when you emit a
> transcript-bearing `Stop` manually. That lets Runlayer extract assistant
> `thinking` or `reasoning` blocks from the completed transcript instead of
> receiving a bare lifecycle stop.
>
> > [!NOTE]
> >
> > The TypeScript Claude adapter forwards `SessionStart` and `SessionEnd`.
> > The current Python adapter starts with `UserPromptSubmit`, then forwards
> > tool lifecycle events and `Stop`. Both group events by the Claude session
> > ID, but their lifecycle event sets are not identical.
>
> > [!NOTE]
> >
> > Each `query()` call starts a new Claude Agent SDK session with a fresh
> > `session_id`, and Runlayer records each session id as a separate
> > session. To keep a multi-prompt conversation in a single Runlayer
> > session, resume the previous session on follow-up calls (leave
> > `forkSession` / `fork_session` unset so the session id is preserved):
>
> ```typescript TypeScript theme={null}
> options: {
>   hooks: createClaudeAgentSdkHooks(runlayer, { includeStop: false }),
>   resume: sessionId, // session_id captured from the previous run's init message
> }
> ```
>
> ```python Python theme={null}
> options = ClaudeAgentOptions(
>     hooks=create_claude_agent_sdk_hooks(runlayer, include_stop=False),
>     resume=session_id,  # session_id captured from the previous run's init message
> )
> ```
>
> Emit the transcript `Stop` after each run as usual — repeated `Stop`
> events with the same session id land in the same Runlayer session.

> [tab] Vercel AI SDK
>
> Wrap a Vercel AI SDK tool set before passing it to `generateText`,
> `streamText`, or a `ToolLoopAgent`.
>
> ```typescript TypeScript theme={null}
> import { streamText, tool } from "ai";
> import {
>   RunlayerClient,
>   withRunlayerVercelAiTools,
> } from "@runlayer/hooks-sdk/vercel-ai-sdk";
>
> const runlayer = RunlayerClient.fromEnv({ clientVersion: "my-agent/1.0.0" });
>
> const tools = withRunlayerVercelAiTools(
>   {
>     getWeather: tool({
>       description: "Get weather for a city",
>       inputSchema: {
>         type: "object",
>         properties: { city: { type: "string" } },
>         required: ["city"],
>       },
>       execute: async ({ city }) => ({ forecast: `sunny in ${city}` }),
>     }),
>   },
>   { client: runlayer, sessionId: "session-id" },
> );
>
> await streamText({ model, prompt: "Check the weather in Paris", tools });
> ```
>
> ```python Python theme={null}
> from runlayer_sdk import RunlayerClient, with_runlayer_vercel_ai_tools
>
> runlayer = RunlayerClient.from_env(client_version="my-agent/1.0.0")
>
> tools = with_runlayer_vercel_ai_tools(
>     {
>         "getWeather": {
>             "description": "Get weather for a city",
>             "inputSchema": {
>                 "type": "object",
>                 "properties": {"city": {"type": "string"}},
>                 "required": ["city"],
>             },
>             "execute": lambda tool_input, execution_options=None: {
>                 "forecast": f"sunny in {tool_input['city']}",
>             },
>         },
>     },
>     {"client": runlayer, "session_id": "session-id"},
> )
> ```
>
> > [!NOTE]
> >
> > The Python adapters wrap **dict-shaped** tool definitions, not native
> > `FunctionTool` or callable objects. For native callables, call
> > `RunlayerClient.run_tool(...)` directly inside the callable.

> [tab] OpenAI Agents SDK
>
> Wrap function tool options before passing them to OpenAI Agents SDK's
> `tool(...)` helper.
>
> ```typescript TypeScript theme={null}
> import { tool } from "@openai/agents";
> import {
>   RunlayerClient,
>   withRunlayerOpenAIAgentsTool,
> } from "@runlayer/hooks-sdk/openai-agents-sdk";
>
> const runlayer = RunlayerClient.fromEnv({ clientVersion: "my-agent/1.0.0" });
>
> const lookupTicket = tool(
>   withRunlayerOpenAIAgentsTool(
>     {
>       name: "lookup_ticket",
>       description: "Look up a support ticket",
>       parameters: {
>         type: "object",
>         properties: { ticketId: { type: "string" } },
>         required: ["ticketId"],
>       },
>       execute: async ({ ticketId }) => `ticket:${ticketId}`,
>     },
>     { client: runlayer, sessionId: "session-id" },
>   ),
> );
> ```
>
> ```python Python theme={null}
> from runlayer_sdk import RunlayerClient, with_runlayer_openai_agents_tool
>
> runlayer = RunlayerClient.from_env(client_version="my-agent/1.0.0")
>
> lookup_ticket = with_runlayer_openai_agents_tool(
>     {
>         "name": "lookup_ticket",
>         "description": "Lookup a ticket",
>         "parameters": {"type": "object"},
>         "execute": lambda tool_input, context=None, details=None: {
>             "ticket_id": tool_input["ticket_id"],
>         },
>     },
>     {"client": runlayer, "session_id": "session-id"},
> )
> ```

> [tab] Google ADK
>
> Python Hooks SDK 0.3.0 adds a native lifecycle plugin; install
> `google-adk[mcp]==2.11.0` alongside the Hooks SDK. The integration supports
> ADK 2.11 through 2.x and Python 3.10+. ADK remains optional for other SDK
> customers. TypeScript continues to wrap `FunctionTool` options.
>
> ```typescript TypeScript theme={null}
> import { FunctionTool } from "@google/adk";
> import {
>   RunlayerClient,
>   withRunlayerGoogleAdkTool,
> } from "@runlayer/hooks-sdk/google-adk";
>
> const runlayer = RunlayerClient.fromEnv({ clientVersion: "my-agent/1.0.0" });
>
> const searchTickets = new FunctionTool(
>   withRunlayerGoogleAdkTool(
>     {
>       name: "search_tickets",
>       description: "Search support tickets",
>       parameters: {
>         type: "object",
>         properties: { query: { type: "string" } },
>         required: ["query"],
>       },
>       execute: async ({ query }) => ({ query }),
>     },
>     { client: runlayer, sessionId: "session-id" },
>   ),
> );
> ```
>
> ```python Python theme={null}
> from google.adk.agents import LlmAgent
> from google.adk.apps import App
> from google.adk.runners import Runner
> from google.adk.sessions import InMemorySessionService
> from runlayer_sdk import RunlayerClient, create_google_adk_plugin
>
> def search_tickets(query: str) -> dict[str, str]:
>     """Search support tickets."""
>     return {"query": query}
>
> runlayer = RunlayerClient.from_env(client_version="my-agent/1.0.0")
> plugin = create_google_adk_plugin(runlayer, model="gemini-2.5-flash")
> runner = Runner(
>     app=App(
>         name="support",
>         root_agent=LlmAgent(
>             name="assistant", model="gemini-2.5-flash", tools=[search_tickets],
>         ),
>         plugins=[plugin],
>     ),
>     session_service=InMemorySessionService(),
> )
> # Create an ADK session, then consume runner.run_async(...) normally.
> # At application shutdown: await runner.close()
> ```
>
> The Python plugin records `SessionStart` and a new user text prompt,
> tool inputs/results/errors, then completed assistant text and available ADK
> thought summaries in a transcript-bearing `Stop`. Reusing the ADK
> app/user/session identity preserves one conversation across turns; each
> invocation has isolated buffers. `Stop` ends a turn, not the conversation.
> The session ID is correlation metadata; the Runlayer client's credentials
> still determine the acting identity. Scope clients appropriately for OBO.
>
> Partial streaming events are ignored and completed event IDs deduplicated.
> Opaque thought signatures and image/audio/file contents are omitted; the
> plugin does not expose hidden reasoning or estimate token usage. Assistant
> timestamps use completion observation time, retaining the original ADK time
> as `provider_event_timestamp`. This does not change Sessions viewer layout.
>
> `max_transcript_bytes` defaults to 256 KiB per invocation. Remaining entries
> are omitted after the limit, with `transcript_truncated: true` on `Stop`.
> Tool outputs use the client's existing output limit. Buffers clear on normal
> completion/errors. ADK 2.11 skips completion/error callbacks on cancellation:
> cancelled buffers clear when ADK releases the invocation context or the
> runner closes; a final `Stop` is not guaranteed. Consume or explicitly close
> run iterators and close the runner at shutdown.
>
> Lifecycle delivery is best-effort; server `status: "ignored"` responses use
> client warnings. Use preflight to verify ingestion. Tool enforcement retains
> the client's fail-closed default and argument/output rewrites. Original
> tool/run exceptions propagate even if error reporting fails.
>
> **Runlayer MCP correlation (Python)**
>
> ```python theme={null}
> from google.adk.tools.mcp_tool import McpTool, McpToolset, StreamableHTTPConnectionParams
> from runlayer_sdk import create_google_adk_plugin, google_adk_session_headers
>
> gateway_url = "https://your-runlayer-instance.com/api/v1/proxy/YOUR_SERVER_ID/mcp"
> toolset = McpToolset(
>     connection_params=StreamableHTTPConnectionParams(
>         url=gateway_url, headers=existing_auth_headers,
>     ),
>     header_provider=google_adk_session_headers,
> )
> plugin = create_google_adk_plugin(
>     runlayer,
>     tool_url=lambda tool: gateway_url if isinstance(tool, McpTool) else None,
> )
> # Add toolset to the agent's tools and plugin to App.plugins.
> ```
>
> Keep the endpoint and authentication from your existing
> [MCP setup](https://docs.runlayer.com/agent-frameworks.md). The URL resolver above assumes all MCP tools
> use that endpoint; resolve each actual tool's URL for multiple servers.
> The client's existing URL/enforcement rules skip duplicate scanning for
> Runlayer proxy calls, while observation-only tool events remain in Sessions.
> Unknown/direct MCP URLs retain SDK enforcement.
>
> `google_adk_session_headers(context)` adds `x-runlayer-session-id`, matching
> `google_adk_session_id(context)` in SDK events so gateway audit/scanner
> records correlate with the same conversation. ADK preserves static headers;
> merge the helper's result with an existing dynamic header provider to retain
> authentication. This helper does not mint MCP tokens or alter OAuth scopes.
>
> Register one Runlayer plugin per runner, last in `App.plugins`. Earlier
> tool callbacks may transform arguments/results in place, but must return
> `None`; returning a value skips later plugins, including Runlayer. ADK runs
> agent-level `before_tool_callback` and `after_tool_callback` after plugins,
> so those callbacks must be read-only and return `None`. Move transformations
> into an earlier plugin. Do not also wrap those tools with `run_tool` or
> `with_runlayer_google_adk_tool`, which would enforce twice. The existing
> dictionary wrapper remains available unchanged.

> [tab] Custom runtime
>
> If your runtime executes tools outside a supported framework, wrap those
> calls with `runTool` / `run_tool`.
>
> ```typescript TypeScript theme={null}
> import { RunlayerClient } from "@runlayer/hooks-sdk";
>
> const runlayer = RunlayerClient.fromEnv({ clientVersion: "my-agent/1.0.0" });
>
> const output = await runlayer.runTool({
>   execute: async (toolInput) => runLocalTool(toolInput),
>   sessionId: "session-id",
>   toolInput: { command: "cat README.md" },
>   toolName: "Bash",
>   toolType: "shell",
> });
> ```
>
> ```python Python theme={null}
> from runlayer_sdk import RunlayerClient
>
> runlayer = RunlayerClient.from_env(client_version="my-agent/1.0.0")
>
> output = await runlayer.run_tool_async(
>     execute=run_local_tool_async,
>     session_id="session-id",
>     tool_input={"command": "cat README.md"},
>     tool_name="Bash",
>     tool_type="shell",
> )
> ```
>
> Runlayer can return modified arguments from the pre-tool hook; the SDK passes
> them to `execute`. If Runlayer denies the call or blocks the output, the SDK
> throws `RunlayerBlockedError`. Synchronous Python tools can use `run_tool`;
> async tools must use `run_tool_async`. Python runtimes with other dict-shaped
> tool APIs can use `run_runlayer_adapter_tool(...)` or
> `run_runlayer_adapter_tool_async(...)` for the same skip rules.

## Direct MCP source enforcement

Use direct MCP source enforcement when a custom agent can call MCP servers
without going through the Runlayer proxy.

```typescript TypeScript theme={null}
const runlayer = RunlayerClient.fromEnv({
  directMcpSourceEnforcementPath: "/api/v1/hooks/cursor",
});

await runlayer.enforceMcpSource({
  generationId: "generation-id",
  sessionId: "session-id",
  toolName: "mcp__github__list_repos",
  url: "https://tenant.runlayer.com/api/v1/proxy/server-id/mcp",
});
```

```python Python theme={null}
runlayer = RunlayerClient.from_env(
    direct_mcp_source_enforcement_path="/api/v1/hooks/cursor",
)

runlayer.enforce_mcp_source(
    generation_id="generation-id",
    session_id="session-id",
    tool_name="mcp__github__list_repos",
    url="https://tenant.runlayer.com/api/v1/proxy/server-id/mcp",
)
```

If Runlayer denies the source, the call throws `RunlayerBlockedError`.
In an async Python runtime, use `await runlayer.enforce_mcp_source_async(...)`
with the same arguments.

> [!NOTE]
>
> Direct MCP source enforcement currently uses the Cursor hook route and
> requires user API-key auth in both SDKs. Configure `RUNLAYER_API_KEY` for this
> client; Agent Account bearer auth is supported for lifecycle and tool hooks,
> but not this route.

## API reference

> [tab] TypeScript
>
> ### `RunlayerClient.fromEnv(options?)`
>
> Creates a client from `RUNLAYER_BASE_URL` plus one auth source:
> `RUNLAYER_API_KEY` or `RUNLAYER_AGENT_CLIENT_ID` / `RUNLAYER_AGENT_CLIENT_SECRET`.
> With API key auth, `RUNLAYER_USER_EMAIL` names the user attributed when the
> key is an organization key.
>
> **client** `string`
>
> Client name sent to Runlayer. Defaults to `RUNLAYER_HOOK_CLIENT` or `typescript-sdk`.
>
> **clientVersion** `string`
>
> Version string for your agent runtime; used for audit-log attribution.
>
> **enforcementFailureMode** `string` (default: closed)
>
> `closed` blocks on enforcement outages; `open` allows on outages.
>
> **timeoutMs** `number` (default: 10000)
>
> Per-request timeout in milliseconds.
>
> **toolEnforcement** `object`
>
> Tool filtering shared by generic wrappers and framework adapters.
>
> * `createClaudeAgentSdkHooks(client, options?)` — Claude Agent SDK hook map.
> * `createVercelEveHook(client, options?)` — fail-open Vercel Eve native runtime hook.
> * `sendRunlayerPreflight(client, options?)` — strict synthetic lifecycle sequence.
> * `emitClaudeAgentSdkTranscriptStop(client, options)` — strict transcript `Stop`.
> * `emitEvent(eventName, payload, transcript?, options?)` — send a lifecycle event.
> * `beforePrompt(options)` — record and scan a user prompt; throws `RunlayerBlockedError` on block.
> * `runTool(options)` — run a custom tool through pre/post enforcement.
> * `withRunlayerVercelAiTool` / `withRunlayerVercelAiTools` / `withRunlayerOpenAIAgentsTool` / `withRunlayerGoogleAdkTool` — adapter helpers.
> * `enforceMcpSource(options)` — validate a direct MCP source.

> [tab] Python
>
> ### `RunlayerClient.from_env(**options)`
>
> Creates a client from `RUNLAYER_BASE_URL` plus one auth source:
> `RUNLAYER_API_KEY` or `RUNLAYER_AGENT_CLIENT_ID` / `RUNLAYER_AGENT_CLIENT_SECRET`.
> With API key auth, `RUNLAYER_USER_EMAIL` names the user attributed when the
> key is an organization key.
>
> **client** `string`
>
> Client name sent to Runlayer. Defaults to `RUNLAYER_HOOK_CLIENT` or `python-sdk`.
>
> **client\_version** `string`
>
> Version string for your agent runtime; used for audit-log attribution.
>
> **enforcement\_failure\_mode** `string` (default: closed)
>
> `closed` blocks on enforcement outages; `open` allows on outages.
>
> **timeout\_ms** `number`
>
> Per-request timeout override. Defaults: 30000 ms enforcement/tool, 5000 ms lifecycle, 10000 ms direct.
>
> **tool\_enforcement** `object`
>
> Filter config for ignored tools, MCP server names, proxy URLs, and custom predicates.
>
> * `create_claude_agent_sdk_hooks(client, options=None, *, include_stop=None)` — Claude Agent SDK hook map.
> * `send_runlayer_preflight(client, **options)` — strict synthetic lifecycle sequence.
> * `emit_claude_agent_sdk_transcript_stop(client, **options)` — strict transcript `Stop`.
> * `RunlayerClient.emit_event(event_name, payload, transcript=None, *, strict=False)` — send a lifecycle event.
> * `RunlayerClient.before_prompt(**options)` / `before_prompt_async(**options)` — record and scan a user prompt; raises `RunlayerBlockedError` on block.
> * `RunlayerClient.run_tool(**options)` / `run_tool_async(**options)` — run a custom tool through pre/post enforcement.
> * `create_google_adk_plugin(client, *, model=None, tool_url=None, max_transcript_bytes=262144)` — native Python ADK lifecycle plugin.
> * `google_adk_session_id(context)` / `google_adk_session_headers(context)` — conversation correlation helpers.
> * `with_runlayer_vercel_ai_tool` / `with_runlayer_vercel_ai_tools` / `with_runlayer_openai_agents_tool` / `with_runlayer_google_adk_tool` — adapter helpers.
> * `run_runlayer_adapter_tool(...)` / `run_runlayer_adapter_tool_async(...)` — wrap another dict-shaped tool API.
> * `RunlayerClient.enforce_mcp_source(**options)` / `enforce_mcp_source_async(**options)` — validate a direct MCP source.

## Troubleshooting

> [accordion] Preflight says SDK session monitoring is not enabled
>
> Enable the matching SDK session monitoring client (**TypeScript SDK** or
> **Python SDK**) in **Settings → Agent session monitoring**, then rerun preflight. If you
> cannot see the client option, ask a Runlayer admin to enable SDK session
> monitoring for the workspace.

> [accordion] Preflight prints an ID, but I cannot find the session
>
> TypeScript preflight returns `sessionUrl`; open that URL first. Python
> preflight currently returns the synthetic external `session_id`, not the
> Runlayer session ID or URL. Open Sessions immediately and check the newest
> **Python SDK** session. Use the external ID to correlate the hook request in
> application logs if the session does not appear.

> [accordion] The setup script succeeds, but no tool calls are enforced
>
> Confirm you constructed the client with the same credentials used for
> preflight, and wrap local tool execution with a framework adapter or
> `runTool` / `run_tool`. Preflight only proves lifecycle ingestion; it does
> not wrap your tools by itself.

> [accordion] Events are ignored with reason actor\_unresolved
>
> The request authenticated, but Runlayer could not map it to a user. With an
> organization API key, set `RUNLAYER_USER_EMAIL` (or the `userEmail` /
> `user_email` client option) to the Runlayer user the deployment runs as.
> If that user does not exist in the workspace yet, session events are
> buffered and replayed once it is created; tool enforcement stays inactive
> until then. Otherwise use a personal API key or agent-account credentials.

> [accordion] Events are ignored with reason sessions\_disabled
>
> The applicable MDM configuration disables session reporting. Ask a
> Runlayer administrator to enable **Sessions** in that MDM configuration.
> Tool enforcement remains active while session reporting is disabled.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.