Metadata-Version: 2.5
Name: ciphyrs
Version: 8.4.0
Summary: Ciphyrs SDK: AI-agent observability and tool-call enforcement, built on OpenTelemetry
Project-URL: Homepage, https://www.ciphyrs.com
Project-URL: Documentation, https://www.ciphyrs.com/docs
Project-URL: Repository, https://github.com/praveen190/Ciphyrs
Project-URL: Changelog, https://github.com/praveen190/Ciphyrs/releases
Author-email: Ciphyrs <support@ciphyrs.com>
License-Expression: MIT
License-File: LICENSE
Keywords: ai-agents,ciphyrs,guardrails,observability,opentelemetry,pii
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: Free Threading :: 3 - Stable
Classifier: Topic :: Security
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.9
Requires-Dist: cryptography>=42.0.0
Requires-Dist: httpx>=0.25.0
Requires-Dist: opentelemetry-api>=1.20.0
Requires-Dist: opentelemetry-exporter-otlp-proto-http>=1.20.0
Requires-Dist: opentelemetry-sdk>=1.20.0
Provides-Extra: auto
Requires-Dist: openinference-instrumentation-crewai>=0.1.0; (python_version >= '3.10') and extra == 'auto'
Requires-Dist: openinference-instrumentation-langchain>=0.1.0; extra == 'auto'
Requires-Dist: openinference-instrumentation-llama-index>=1.0.0; extra == 'auto'
Requires-Dist: openinference-instrumentation-openai-agents>=0.1.0; extra == 'auto'
Requires-Dist: openinference-instrumentation-openai>=0.1.0; extra == 'auto'
Provides-Extra: mesh
Requires-Dist: ciphyrs-node>=0.1.0; ((sys_platform == 'darwin' and platform_release >= '22' and (platform_machine == 'arm64' or platform_machine == 'x86_64')) or (sys_platform == 'linux' and (platform_machine == 'x86_64' or platform_machine == 'aarch64')) or (sys_platform == 'win32' and platform_machine == 'AMD64')) and extra == 'mesh'
Provides-Extra: opentelemetry
Requires-Dist: opentelemetry-sdk>=1.20.0; extra == 'opentelemetry'
Description-Content-Type: text/markdown

# Ciphyrs — observability for AI agents

[![PyPI](https://img.shields.io/pypi/v/ciphyrs)](https://pypi.org/project/ciphyrs/)
[![Python](https://img.shields.io/pypi/pyversions/ciphyrs)](https://pypi.org/project/ciphyrs/)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)

See every agent, tool call and model call your application makes, as one
connected graph. Built on OpenTelemetry, so the spans are standard OTLP and
sit beside whatever tracing you already have — and your model calls stay
yours, made directly against your provider.

## Install

```bash
pip install ciphyrs
```

One command. OpenTelemetry and `httpx` come with it. **Python 3.9 through
3.14**, including the free-threaded 3.14 build (PEP 703). There, and on any
Python started with `-X thread_inherit_context=1`, threads inherit their
starter's context, so a thread pool's worker would keep the context of the
turn that created it; `init()` therefore makes every `ThreadPoolExecutor`
task and `Thread` run in the context that submitted or started it
(`propagate_threads`, on by default on those interpreters only).
`init(propagate_threads=False)` is honoured, with a warning: an `@tool` on a
shared pool could then run in another turn and receive its values.

No framework-specific integration to install. `@agent` and `@tool` wrap
plain **functions**, so they work with any agent framework, or none.

For traces from LangChain, LangGraph, CrewAI and the OpenAI Agents SDK, install
the extra: `pip install "ciphyrs[auto]"`. On those frameworks (and Google ADK)
`init()` alone is enough to monitor; see [Using a framework](#using-a-framework).

## Monitor your agents

```python
import ciphyrs

ciphyrs.init(api_key="cyp_live_...", project="customer-support")

@ciphyrs.tool
def issue_refund(order: str, amount: float) -> dict:
    return payments.refund(order, amount)   # traced, and checked against policy

@ciphyrs.agent("BillingAgent", role="worker")
def billing(question: str) -> str:
    answer = my_model.generate(question)      # your model call, unchanged
    issue_refund(order="A-1041", amount=12.0)
    return answer

@ciphyrs.agent("RouterAgent", role="router")
def router(message: str) -> str:
    return billing(message)      # called INSIDE router -> a RouterAgent→BillingAgent edge

with ciphyrs.session("conv-7f3a"):            # ties one conversation together
    router("I was charged twice for order A-1041")

ciphyrs.shutdown()                            # flush; short-lived scripts only
```

That is the whole integration. Nesting **is** the topology: because `billing`
was called inside `router`, the dashboard draws the edge. Both agents appear
in the fleet at start-up — decorators register themselves, before any traffic.

| | |
|---|---|
| `init()` | Configures an OTLP exporter to Ciphyrs, or attaches to a `TracerProvider` you already have and leaves your exporters alone. Falls back to `CIPHYRS_API_KEY`, `CIPHYRS_PROJECT`, `CIPHYRS_BASE_URL`. |
| `@agent` | One span per call, named for the agent. Everything it calls nests underneath. |
| `@tool` | One span per tool call, with arguments and result. Also checked against policy before it runs — `enforce` inherits `init(enforce=True)`, so a `block` verdict raises `ToolBlocked` and the function never executes. Pass `enforce=False` to trace only. |
| `session()` | Tags every span inside with `session.id`. |
| `init(agents=...)` | Declares the roster and the designed peer graph at boot, so the fleet is complete before the first request. Starts a heartbeat (default 60 s) so idle and dead are distinguishable. LangGraph, CrewAI, OpenAI Agents SDK and Google ADK objects need not be passed: see [Topology](#topology). |

Async is automatic — declare the function `async def` and the decorators
install async wrappers. Every platform call they make runs off your event
loop.

### See the inputs and outputs

On by default. Pass `capture_io=False` to an individual `@agent` or `@tool`
whose arguments must not be recorded; its spans still carry timing, nesting
and errors.

### Agents in separate processes

Already on. Outgoing HTTP requests carry the trace context, so an agent that
calls another service shows up as one connected graph rather than two
disconnected fleets. `init(propagate=False)` turns it off. Every host gets only
the opaque trace context; the agent and project *names* go only to private
hosts, the Ciphyrs hosts, and any you list with
`ciphyrs.propagation.peer_hosts([...])` — never to a model provider or other
public site.

### Topology

Automatic for **LangGraph, CrewAI, the OpenAI Agents SDK and Google ADK**.
After `init()`, the SDK notices these objects being built and declares their
designed topology — agents, roles, tool names and peer edges — before the
first request, with no code change:

| Framework | Read when | Edges from |
|---|---|---|
| LangGraph | a `StateGraph` (or `MessageGraph`) is compiled | the compiled graph's edges |
| CrewAI | a `Crew` is constructed | task order |
| OpenAI Agents SDK | an `Agent` is constructed | `handoffs` |
| Google ADK | an agent is constructed | `sub_agents` |

It works whether the framework is imported before or after `init()`, never
imports a framework itself, and never raises into the framework's code. Every
object built within about a second is read in one pass and merged by name
into one roster per process — sub-agents built before their parent, several
graphs, graphs rebuilt in tests — and a declaration is sent only when that
roster changes. Only names, roles, tool names and edges are read: never
prompts, instructions, descriptions or state. An object built *before*
`init()` is read on its first run instead: a compiled graph's `invoke` /
`ainvoke` / `stream` / `astream`, `Crew.kickoff` / `kickoff_async`, the
Agents SDK's `Runner.run` / `run_sync` / `run_streamed`, ADK's `Runner.run` /
`run_async`. Each object is read once; `ciphyrs.flush()` and `shutdown()`
declare anything still pending.

What you declare yourself wins: names, roles and peers from
`@ciphyrs.agent(..., role=, peers=)`, `init(agents=...)` or `announce()` are
never overwritten, and discovered edges are added to them. An agent that only
discovery found is declared with `source: "discovered"` and labelled
"auto-mapped" in the dashboard.

`init(auto_topology=False)` or `CIPHYRS_AUTO_TOPOLOGY=0` turns discovery off;
`ciphyrs.selfcheck()["auto_topology"]` lists the hooked frameworks and the
number of agents discovered; `shutdown()` restores the frameworks' original
methods.

#### Inferred connections for hand-written agents

Hand-written orchestration has no framework object to read, so the SDK reads
the code instead. At `init()` — and again, debounced, whenever an
`@ciphyrs.agent` is decorated after it — each agent function's compiled code
is inspected for references to *other* `@ciphyrs.agent` functions:

```python
@ciphyrs.agent("RouterAgent")
def router(q):
    return fraud(q) if "fraud" in q else billing(q)   # RouterAgent → FraudAgent, BillingAgent
```

Nothing is executed and nothing is imported. Caught: direct calls in any
branch; `module.agent()` and `Class.agent()`; an agent captured in a closure;
calls inside nested functions, lambdas and comprehensions; `self.other()` on
the agent's own class (and its bases); a module-level dispatch table — a dict,
list, tuple or set of at most 200 items holding agents, e.g.
`ROUTES = {"b": billing}; ROUTES[k](q)`. Not caught: anything decided at run
time — `getattr(mod, name)`, `globals()[name]`, a name built from a string, an
agent passed in as an argument, a call made through a plain helper function —
and tables nested more than one level deep. Those edges appear when traffic
crosses them.

Inferred edges are sent as each agent's `inferred_peers` (agent names only,
never source or constants), not as `peers`, and a name you already gave in
`peers=` is not repeated. The dashboard draws them dashed until traffic
confirms them. `init(infer_topology=False)` or `CIPHYRS_INFER_TOPOLOGY=0`
turns it off; `ciphyrs.selfcheck()["infer_topology"]` counts the agents
inspected and the edges inferred, and lists any agent that could not be
inspected (a C or Cython function, for one) with the reason.

### Model and framework internals

Spans *inside* a framework or provider — retriever calls, per-node detail —
come from that framework's own OpenTelemetry instrumentation, not from
Ciphyrs. `init()` finds the agent frameworks installed in the process
(CrewAI, LangGraph, LangChain, the OpenAI Agents SDK, Google ADK, LlamaIndex,
AutoGen, the OpenAI client) and activates the matching OpenInference
instrumentor when it is installed; `pip install "ciphyrs[auto]"` installs
them (AutoGen's goes beside AutoGen), a missing one is named once in the log,
and `init(auto_instrument=False)` turns this off. Their spans travel through
the exporter `init()` already installed and nest inside your agent spans.
(Ciphyrs does sit on the model request itself, to mask and guard it: see the
model-call shield below.)

### Is it actually on?

```python
state = ciphyrs.selfcheck()
if state["problems"]:
    log.error("Ciphyrs is not live in this process: %s", state["problems"])
```

Reports what is genuinely running and names each problem in words. Makes no
network call, so it is safe in a readiness probe.

## Using a framework

**Monitoring needs only `init()`, no decorators**, for LangGraph, CrewAI, the
OpenAI Agents SDK and Google ADK: the agent map is read from the framework's
own objects (see [Topology](#topology)), traces come from its instrumentation
(`pip install "ciphyrs[auto]"`; ADK traces itself), and model calls are masked
and guarded by the model-call shield. **Decorators are for enforcing policy on
tools**: checking a call before it runs, approvals, blocking. Plain LangChain,
without LangGraph, has no graph to read: put `@ciphyrs.agent` on the function
that runs the agent, or list it with `init(agents=[...])`.

| Framework | Agent map | Tool policy |
|---|---|---|
| LangGraph, CrewAI, OpenAI Agents SDK, Google ADK | automatic | `@ciphyrs.tool` on risky tools |
| LangChain v1 `create_agent` | automatic | `ciphyrs.langchain_middleware()` for every tool, or `@ciphyrs.tool` |
| LangChain (no LangGraph) | `@ciphyrs.agent` or `init(agents=...)` | `@ciphyrs.tool` on risky tools |

**Which tools to wrap.** Only the ones that can do damage: payments and
refunds, deletes, outbound messages, data exports. Read-only tools can stay
plain.

**The rule.** The framework's decorator outside, `@ciphyrs.tool` directly on
the function. (The reverse order also works since 8.4: `@ciphyrs.tool` applied
to a framework's tool object governs it in place.) A tool is checked as the
enclosing `@ciphyrs.agent`, or `@ciphyrs.tool(agent="Billing")`, else as
`init()`'s service name (by default the project).

**What the model reads on a block.** Each framework reacts to a tool exception
in its own way, so decide it. `@ciphyrs.tool(on_block=callable)` turns a
`ToolBlocked` into the tool's return value: the function still does not run
and the span records the block (not available on generator tools). The
framework's own error hooks work too, as shown below.

### LangChain

```python
import ciphyrs
from langchain_core.tools import tool

ciphyrs.init(project="support")              # the API key comes from CIPHYRS_API_KEY

@tool                                        # the framework's decorator OUTSIDE
@ciphyrs.tool(on_block=lambda e: f"Blocked by policy: {e.reason}")   # ours directly on the function
def refund(order_id: str, amount: float, count: int = 1) -> str:
    """Refund an order."""
    return payments.refund(order_id, amount, count)

@tool                                        # read-only: stays a plain tool
def order_status(order_id: str) -> str:
    """Look up an order's status."""
    return orders.status(order_id)

# Plain LangChain has no graph for init() to read: name the agent yourself
# (or list it with init(agents=[...])).
@ciphyrs.agent("SupportAgent", role="worker")
def support(question: str) -> str:
    return chain.invoke({"question": question})   # your chain or agent, unchanged
```

- Without `on_block`, `tool.invoke` raises `ToolBlocked` (`str(e)` is
  `[block] <reason>`); LangChain's `handle_tool_error` catches only
  `ToolException`. With it, the `ToolMessage` reads `Blocked by policy: <reason>`.
- Class-based tools:

```python
import ciphyrs
from langchain_core.tools import BaseTool, StructuredTool

def search(query: str) -> str:
    """Search the knowledge base."""
    return kb.search(query)

async def asearch(query: str) -> str:
    """Search the knowledge base."""
    return await kb.asearch(query)

# A StructuredTool with a sync and an async path: govern the object it built ...
search_tool = ciphyrs.govern(StructuredTool.from_function(func=search, coroutine=asearch))

# ... or wrap each callable, naming the async one so both are checked as "search".
search_tool = StructuredTool.from_function(
    func=ciphyrs.tool(search), coroutine=ciphyrs.tool("search")(asearch), name="search")

class Weather(BaseTool):
    name: str = "weather"
    description: str = "Current weather for a city."

    def _run(self, city: str) -> str:
        return forecast(city)

weather = ciphyrs.govern(Weather())          # or put @ciphyrs.tool("weather") on _run
```

### LangGraph

```python
import ciphyrs
from langchain_core.tools import tool
from langgraph.prebuilt import ToolNode, create_react_agent

ciphyrs.init(project="support")

@tool
@ciphyrs.tool
def refund(order_id: str, amount: float) -> str:
    """Refund an order."""
    return payments.refund(order_id, amount)

def on_block(e: ciphyrs.ToolBlocked) -> str:   # typed: handles ONLY ToolBlocked
    return f"Blocked by policy: {e.reason}"

agent = create_react_agent(model, ToolNode([refund], handle_tool_errors=on_block))
```

- Default `ToolNode`: `ToolBlocked` propagates out of `graph.invoke` and the
  run ends. With the typed handler the model reads
  `ToolMessage("Blocked by policy: <reason>", status="error")`;
  `handle_tool_errors=True` gives `Error: ToolBlocked('[block] <reason>')` and
  ` Please fix your mistakes.`; `@ciphyrs.tool(on_block=...)` needs no
  `ToolNode` configuration.
- The agent map uses the graph's node names (`agent`, `tools`), not the
  agent's `name=`.
- Injected parameters stay out of the schema and the check:

```python
from typing import Annotated

import ciphyrs
from langchain_core.tools import InjectedToolCallId, tool
from langgraph.prebuilt import InjectedState

@tool
@ciphyrs.tool
def lookup(query: str,
           state: Annotated[dict, InjectedState],
           tool_call_id: Annotated[str, InjectedToolCallId]) -> str:
    """Look something up."""
    # Only `query` is in the schema and the policy check; state and
    # tool_call_id arrive as LangGraph's own objects.
    return kb.search(query, turns=len(state["messages"]))
```

### LangChain v1 `create_agent`

Decorated tools work as they are. Or let one middleware put **every** tool the
agent calls behind the gate, prebuilt and third-party tools included:

```python
import ciphyrs
from langchain.agents import create_agent

ciphyrs.init(project="support")

agent = create_agent(model, tools=[refund, search, weather],
                     middleware=[ciphyrs.langchain_middleware(agent="Billing")])
```

- `ciphyrs.langchain_middleware(on_block=None, **tool_options)` takes the
  options of `@ciphyrs.tool` and applies it to a copy of each tool on first
  use. Your tool objects are not changed, and the same tool called outside the
  agent is not gated. The gate sees the parsed arguments with defaults, never
  the injected ones. A tool that is already `@ciphyrs.tool`-decorated is not
  checked twice.
- With the middleware, a block becomes
  `ToolMessage("Blocked by policy: <reason>", status="error")` and the run
  continues. `on_block` returns other content (sync or `async`), a
  `ToolMessage` or `Command`, or `None` to re-raise.
- Without it, a block in a decorated tool ends the run: `agent.invoke` raises
  `ToolBlocked` (`create_agent` handles only argument errors). Use
  `@ciphyrs.tool(on_block=...)`, or LangChain's `ToolErrorMiddleware`:

```python
from langchain.agents.middleware import ToolErrorMiddleware

def on_error(exc, request):
    if isinstance(exc, ciphyrs.ToolBlocked):
        return f"Blocked by policy: {exc.reason}"
    return None   # anything else is re-raised

agent = create_agent(model, tools=[refund], middleware=[ToolErrorMiddleware(on_error)])
```

- `InjectedState`, `InjectedToolCallId` and `runtime: ToolRuntime[Ctx]`
  (with `context_schema=` and `invoke(..., context=...)`) are passed through.
  A plain `Annotated[..., InjectedToolArg]` is not filled by `create_agent`
  itself, with or without Ciphyrs.
- The agent map uses the graph's node names (`model`, `tools`). With
  `ciphyrs[auto]` the tool-check is in the agent's trace, under LangChain's
  span for that tool call.
- The middleware needs `langchain>=1`; without it, building the middleware
  raises `ImportError`.

### CrewAI

```python
import ciphyrs
from crewai import Agent
from crewai.tools import tool
from crewai.tools.tool_failure import ToolFailure

ciphyrs.init(project="support")

@tool("refund")
@ciphyrs.tool(on_block=lambda e: ToolFailure(message=f"Blocked by policy: {e.reason}", code="ToolBlocked"))
def refund(order_id: str, amount: float) -> str:
    """Refund an order."""
    return payments.refund(order_id, amount)

billing = Agent(role="Billing", goal="Resolve refund requests", backstory="...",
                tools=[refund], llm=llm)
```

- Use `on_block` with CrewAI. Without it, CrewAI's text (ReAct) loop retries a
  tool that raised: one refused call became six tool checks, and six approval
  prompts, in testing. With it the call is checked once and the model reads
  `Blocked by policy: <reason> (code: ToolBlocked)`. On a CrewAI without
  `ToolFailure`, return a string from `on_block`.
- A `BaseTool` subclass: `ciphyrs.govern(Weather())`, or
  `@ciphyrs.tool("weather")` on `_run`.

### OpenAI Agents SDK

```python
from dataclasses import dataclass

import ciphyrs
from agents import Agent, RunContextWrapper, function_tool

ciphyrs.init(project="support")

@dataclass
class MyCtx:
    user_id: str

@function_tool
@ciphyrs.tool
def refund(ctx: RunContextWrapper[MyCtx], order_id: str, amount: float) -> str:
    """Refund an order."""
    return payments.refund(order_id, amount, requested_by=ctx.context.user_id)

billing = Agent(name="Billing", instructions="Handle refund requests.", tools=[refund])
```

- On a block the model receives the tool output `An error occurred while
  running the tool. Please try again. Error: [block] <reason>` and the run
  continues; `@function_tool(failure_error_function=None)` raises
  `ToolBlocked` instead, and `on_block` replaces the text.
- `ctx: RunContextWrapper` stays out of the schema and the check; writes to
  `ctx.context` persist.
- Strict mode is the framework's, and rejects `dict[str, ...]` parameters
  with or without Ciphyrs: pass `strict_mode=False`.

```python
import ciphyrs
from agents import function_tool

@function_tool(strict_mode=False)            # dict[str, ...] parameters: the framework's strict schema rejects them
@ciphyrs.tool
def tag_order(order_id: str, labels: dict[str, str]) -> str:
    """Attach labels to an order."""
    return orders.tag(order_id, labels)
```

### Google ADK

```python
import ciphyrs
from google.adk.agents import LlmAgent
from google.adk.tools import ToolContext

ciphyrs.init(project="support")

@ciphyrs.tool
def refund(order_id: str, amount: float, tool_context: ToolContext) -> dict:
    """Refund an order."""
    tool_context.state["last_refund"] = order_id
    return {"status": payments.refund(order_id, amount)}

def on_tool_error(tool, args, tool_context, error):
    if isinstance(error, ciphyrs.ToolBlocked):
        return {"error": f"Blocked by policy: {error.reason}"}
    return None

agent = LlmAgent(name="Billing", model="gemini-2.5-flash", tools=[refund],
                 on_tool_error_callback=on_tool_error)
```

- ADK has no tool decorator: put `@ciphyrs.tool` on the function and pass it
  in `tools=[...]`. Without the callback, `runner.run_async` raises
  `ToolBlocked` and the run ends; `@ciphyrs.tool(on_block=lambda e: {"error": ...})`
  is the alternative to the callback.
- `tool_context`, typed or untyped, stays out of the declaration and the
  check; `tool_context.state` writes persist. (An untyped `tool_context`
  counts as ADK's only while Google ADK is loaded, and is left out of a call
  only when ADK passes its ToolContext; anywhere else it is an ordinary
  argument the gate rules on.)
- `protect_tool(client, agent="Billing")` also works inside `FunctionTool(...)`
  and under LangChain's `@tool`.

### Everywhere

- Framework-injected parameters (ADK `tool_context`, Agents
  `RunContextWrapper` / `ToolContext`, LangChain `RunnableConfig`,
  `InjectedToolArg`, `InjectedToolCallId`, `InjectedState`, `ToolRuntime`,
  callback managers) are left out of the schema and the policy check and
  passed through as the real object. A policy rule therefore cannot match an
  injected value. They are recognised by the RESOLVED type, so an
  application's own class that happens to be called `ToolContext` is an
  argument like any other.
- A tool governed after the framework built it (`govern(tool)`,
  `ciphyrs.tool(function_tool)`) runs on the arguments the gate decided: a
  `redact_args` verdict and restored placeholders reach the body, as they do
  for the documented decorator order.
- With `pii="mask"`, only JSON-shaped arguments (str, bytes, dicts, lists,
  tuples, sets, pydantic models, dataclasses) are restored for the tool body;
  any other object (an audit log, a client) is passed as the caller's own
  object, so the tool's writes to it are seen by the caller.
- `async def` tools work in every framework.
- Approvals work in every framework: the tool call waits for the decision, and
  a denial is a `ToolBlocked` with action `denied`, handled like a block. An
  approval the gateway answers with the agent quarantined (or with a block
  decision) is a `ToolBlocked` with action `block`, even when its status says
  approved.
- With `ciphyrs[auto]`, every tool-check carries the trace and span of the
  tool's span, which sits in the agent's trace in every framework above (for
  the OpenAI Agents SDK, with its tracing on). LangChain never makes its spans
  current, so the SDK parents the tool span on LangChain's own span for that
  tool call.
- Tested with ciphyrs 8.4.0 and langchain 1.4.5, langchain-core 1.6.10,
  langgraph 1.2.15, crewai 1.15.28, openai-agents 0.20.0, google-adk 2.12.0.

More, with what the model reads in each case:
[Using Ciphyrs with your framework](https://www.ciphyrs.com/docs#framework-guide).

## Beyond tracing

The platform also enforces policy on agent messages, masks PII, and can
quarantine a misbehaving agent from the dashboard. **Tool checks, message
checks and PII masking are all on by default** once `init()` has an API key,
which means text leaves your process to be evaluated. The documentation says
what each one sends and how to turn it off (`enforce=`, `guard_input=`,
`guard_output=`, `pii=`).

**Every one of them fails closed by default** (since 6.0): if Ciphyrs cannot
give an answer, the input is refused (`InputBlocked`), the reply is refused
(`OutputBlocked`), the tool does not run (`ToolBlocked`) and text that could
not be masked does not reach the model (`PIIProtectionError`). An enforced
`@tool` with no API key is refused too. Each stage can be opened per
application -- `guard_fail_closed={"input": False}`, `pii_fail_closed=False`,
`@tool(fail_closed=False)`, `@protect_tool(..., fail_closed=False)` -- and is
logged once when it is. An opened stage proceeds only during a genuine outage
(no connection, a 5xx without a verdict). A gateway refusal (a
`fail_closed: true` body, at any status) is a block under both postures, and a
timeout, a 429 or any other 4xx is refused as well. Tool arguments too large
to send whole (over 8,000 characters in one value or 64,000 in all) reach the
gate clipped, flagged `args_clipped` with the `args_sha256` of the full
arguments, and the call is refused unless the gateway acknowledges the clip,
under every posture (since 7.3: `fail_closed=False` covers an unreachable
gateway, not a check that saw only part of the arguments).

**Model calls are masked and guarded wherever they are made** (since 7.0).
`init()` patches `httpx` (sync and async) and `requests` — what the OpenAI,
Anthropic, Mistral, Cohere and Google GenAI Python SDKs use — so a POST, PUT or
PATCH (or any request with a body) to a model provider (OpenAI and its EU / US
data-residency hosts, Azure OpenAI / AI Foundry / Azure AI inference, Anthropic,
Gemini / Vertex AI, Bedrock (including FIPS endpoints) through an httpx client
such as `AnthropicBedrock`, Mistral and Codestral, Cohere, Groq, Together, DeepSeek, xAI, OpenRouter, Fireworks,
Perplexity) has every string at a prompt position
(message content, system prompts, tool-call arguments and tool outputs,
embeddings input) masked in one batch before it leaves the process, whether or
not the call is inside `@agent`. That is what covers a framework that owns the
loop — LangGraph, CrewAI, the OpenAI Agents SDK. Outside an `@agent` turn, and
inside a `@tool` body (whose arguments hold real values), the shield also runs
the input guard before the request is sent and the output guard on the reply,
and restores the real values in the reply, tool-call arguments included; a
streamed reply is restored as it arrives and, with the output guard on,
released only once the guard has ruled on it. Inside an `@agent` turn the
agent does the guarding and restoring, and the shield masks only what is
still raw, in the turn's vault session. Embeddings requests are masked too, so
their vectors are computed over the placeholder text.

What the shield does not cover: clients that use neither httpx nor `requests`
— `boto3` / botocore for Bedrock, `aiohttp`, gRPC clients — whose calls need an
`@agent` boundary; images, audio and files inside a request, which are sent as
they are (only text is masked); and audio or other binary replies (images,
audio, video, fonts, octet-stream, PDF, archives, office documents), which are
returned without a guard. A text-like reply that is not JSON or `text/*` (xml,
yaml, a `charset` parameter) is guarded and restored as text; a reply of any
other type is refused under the closed output posture (400) rather than
returned unguarded. A request body that is not JSON (a file upload, a
form, a transcription) and a request for a stream that is not server-sent
events (Bedrock's event stream, NDJSON) are refused rather than sent unmasked,
and so is a body (or a reply that needs restoring) over 64 MiB.
A refusal comes back as an HTTP response, not an exception, so the provider's
SDK raises its own error and does not retry it: 400 when the body cannot be
masked, 403 when a guard blocked the prompt or the reply, 503 when Ciphyrs
could not mask or guard under the closed posture (the SDK retries that one),
each with an `x-ciphyrs-shield` header and a body saying "Blocked by
Ciphyrs". Add a self-hosted model or an internal LLM gateway with
`init(shield_hosts=[...])` or `CIPHYRS_SHIELD_HOSTS`; exempt an endpoint with
`init(shield_exclude=["api.openai.com/v1/files"])` or `CIPHYRS_SHIELD_EXCLUDE`
(its bodies are then sent unmasked, logged once); `init(shield=False)` turns
the shield off, which is logged and reported by `selfcheck()` as a problem
while masking is on. The shield is on whenever `init()` has an API key and
`pii` is not `"off"`.

**Log forwarding is off by default** (since 6.0). `init(capture_logging=True)`
sends every record your application logs at `log_level` or above (INFO by
default, through Python's `logging`, from any logger) to Ciphyrs, shown on the
trace. Credentials are redacted locally before a line leaves the process; the
SDK does not run log lines through the masking service, and the Ciphyrs
gateway masks forwarded lines on ingest before they are stored.

Spans carry `enduser.id` as `sha256:<hex>` of the id you pass to
`ciphyrs.session(..., end_user=)` (raw only with `pii_capture_raw=True`). The
PII vault session id is written only on the spans exported to Ciphyrs, not on
the span your own exporters see: within its workspace it works like a bearer
reference to the turn's real values. `init(export_session_id=True)` writes it
on the span itself.

Governed tools present a verified agent identity: a short-lived token is
minted for the agent's name on its first governed call and refreshed before
it expires. No fleet declaration is needed. If the gateway refuses the token,
the log says why and how to fix it, and the project's identity mode decides
whether the tool runs. If the gateway cannot be reached, the tool is refused
unless it was opened with `fail_closed=False`.

`@agent` closes each turn's PII vault session when the turn ends. For a
session nothing else will close (one you masked into with `CiphyrsClient`,
or a turn run without `@agent`), call `ciphyrs.close_session(session_id)`,
or `await ciphyrs.aclose_session(...)` from async code. Closing twice is
safe, and the call never raises. It returns a `SessionCloseResult`, truthy
only when the gateway confirmed the close; `retained_hours` is set when your
workspace keeps a review copy. `CiphyrsClient.protect()` closes its session on
every path unless you pass `purge=False`, and reports `session_closed`.

## Mesh: agents on other machines, as tools

The Ciphyrs mesh connects agents across processes, machines and networks. On
each machine a small daemon, `ciphyrs-node`, holds the machine's identity,
enforces the policy offline and relays calls to other nodes, end-to-end
encrypted. The SDK talks only to the node on this machine. The normative
description, shared by every Ciphyrs SDK, is SPEC §20 (`packages/clients/SPEC.md`).

### Turning it on: the `mesh` option

```python
ciphyrs.init(project="payments", mesh=True)               # start a node if none runs
client = ciphyrs.CiphyrsClient(api_key=key, mesh="auto")  # the default
```

| `mesh` | What the SDK does |
|---|---|
| `"auto"` (default) | Uses a node that is already running: `node_url` / `CIPHYRS_NODE_URL`, else the node home's `endpoint.json` -- which must name a `peer_id` and a `gate_token` -- when `GET /health?nonce=…`, sent with **no** credential, answers within 1 s with that `peer_id`, the HMAC proof of that gate token over the nonce, and THIS client's gateway as its `control_plane` (a node naming none is not used); the gate token is presented only after that, unless you set `node_token`. The pid in the file is only a hint: a node in another PID namespace is found by its proof. Nothing found: the mesh is off, silently. Tools are **not** published unless you pass `mesh_publish=True`. |
| `True` | The same, and when no node runs it **starts one** (only with an API key; the node enrols with it). It writes `<home>/sdk-node.yaml` atomically and only if absent (`listen: "127.0.0.1:0"`; yours is never overwritten), runs `ciphyrs-node run -config <abs> -home <abs> -sdk-managed -log <home>/node.log` directly (no shell), detached, with only an allowlisted environment (PATH, HOME, temp and locale variables, proxies, certificates, `XDG_*`, plus `CIPHYRS_API_KEY` / `CIPHYRS_PROJECT` -- never your other secrets), and waits up to 20 s; it outlives your process and exits after 10 idle minutes. `init()` returns at once (the start runs on a background thread), a mesh call or `mesh.ready()` waits for it, and a script that exits right away waits only until the node has been spawned (a few seconds at most). If another process started a node first, that one is used. An SDK-written `sdk-node.yaml` that names another gateway is not started from (`config_gateway_mismatch`). Tools are published by default. |
| `False` | No discovery, no start, no publishing. |

`CIPHYRS_MESH=auto|true|false` sets the default; an explicit argument wins.
The node home is `CIPHYRS_NODE_HOME`, else `%LOCALAPPDATA%\ciphyrs-node` on
Windows, else `$XDG_STATE_HOME/ciphyrs-node`, else
`~/.local/state/ciphyrs-node`. It must be a real directory you own that group
and others cannot write, else nothing in it is trusted (`unsafe_home`). Before
`mesh=True` starts a node, an existing `sdk-node.yaml` must also be a `0600`
regular file of yours (`unsafe_config`) and `node.log` not a symbolic link
(`unsafe_home`); discovery never reads the config.

A node that cannot be found or started never raises and never turns anything
else off. While the mesh is off, every mesh call (`list_tools`, `call_tool`,
`request`) raises `MeshNodeUnavailable` naming the reason; there is no
fallback address (pass `node_url` for a node you run yourself).

```python
client.mesh.available        # bool (resolves on first use: <= 1 s, <= 20 s while mesh=True starts one)
client.mesh.reason           # None, or a code (below)
client.mesh.status()         # the node's status, or {"available": False, "reason", "message", "home", ...}
await aclient.mesh.ready()   # the async client resolves on a worker thread
ciphyrs.selfcheck()["mesh"]  # the same, plus what is published and the replay-window counters
```

### Installing the node

`mesh=True` looks for the binary in this order: `CIPHYRS_NODE_BIN` (an
absolute path), the optional `ciphyrs-node` package installed next to this
SDK, then `ciphyrs-node` in an absolute `PATH` entry.

```bash
pip install "ciphyrs[mesh]"    # the prebuilt node for macOS 13+ (arm64, x86_64), Linux (x86_64, aarch64), Windows (AMD64)
```

On other platforms the extra installs nothing and `mesh.status()` says what
the package reported; build the node or download a release and point
`CIPHYRS_NODE_BIN` at it. `pip install ciphyrs` alone never installs a binary.

### Publishing your tools

Under `mesh=True`, and under `"auto"` with `mesh_publish=True`, every
function you wrap with `@ciphyrs.tool` or `protect_tool` is published while
a node is available — nothing else to write (one info line says so the first
time). An explicit `mesh=False` or `mesh_publish=False` on `init()` or on
ANY client stops all publishing in the process, including through clients
you built yourself:

```python
@ciphyrs.tool(agent="billing")
def refund(payment_id: str, amount: int) -> str:
    """Refund a payment."""
    return stripe.Refund.create(payment_intent=payment_id, amount=amount).id

@ciphyrs.protect_tool(client, agent="billing")
async def lookup_invoice(invoice_id: str) -> dict: ...
```

The SDK runs one local MCP server per process (`127.0.0.1:<random>/mcp`,
authenticated from the headers before any body is read, strict HTTP framing,
capped headers, bodies and connections),
registers each agent and then one `mcp` service per agent with the node,
renews the registration every 20 s and removes it on `client.close()`,
`ciphyrs.shutdown()` or exit (an expired lease removes it anyway). Each
agent's service has its own bearer, so one agent's service can never list or
run another agent's tools. Other agents see the tool as `<service>__<tool>`,
where the service is the agent name as the node normalises it: trimmed and
lower-cased, every character outside `[a-z0-9.]` turned into `-` (a run of
them into one), each `.`-separated label trimmed of `-` and cut to 63
characters, empty labels dropped. So agent `billing` publishes
`billing__refund`, `BillingAgent` publishes `billingagent__refund` and
`Billing Agent` publishes `billing-agent__refund`; `mesh.request` normalises a
service name the same way. A `@tool` with no `agent=`
belongs to `init(service_name=...)`. Clients and decorators in one process
that name the same agent share one registration.

A remote call runs through **the same pipeline as a local one** — tool check,
masking, approvals, spans — as the owning agent (async tools: see below). The span carries `ciphyrs.mesh.caller_peer` and
`ciphyrs.mesh.caller_agent` (the calling node and agent the node verified). A
tool that raises gives the caller only `tool <name> failed (error id <8
hex>)`; the exception is logged in your process under that id. Only the
pipeline's own refusal of the call -- a policy block, an approval denied or
timed out -- is returned as the refusal; a gateway outage while deciding is
the generic text too.

Not published: generator tools, methods taking `self` / `cls`, and functions
defined inside another function (per-request closures) unless the decorator
says `mesh_publish=True`; `@tool(mesh_publish=False)` keeps one tool local. The
registry holds tools weakly, and a second, different function under a name
an agent already publishes is refused with a warning (the first is kept).
Registrations are grouped per node, gateway, API key and agent, so clients
with different keys never share a tool list. Async tools run on your
application's event loop (the one `init()` or an async mesh call ran on) so
their loop-bound clients and locks work, else on a private loop, and are
cancelled after 120 s. The process is fork-safe (gunicorn `--preload`,
multiprocessing): a worker never withdraws its parent's registrations and
publishes the tools it registers itself. A node of another tenant than this
client's (once known) gets nothing (`node_tenant_mismatch`).

A client that CALLS through a node the SDK found or started registers its
agent with that node on first use (no tools, no service, renewed with the
leases, withdrawn on close) -- whether or not publishing is on, and never over
the tool list this process publishes for that agent -- so the node accepts it
as the caller. Nothing is registered on a node given by `node_url`. A service name another node already publishes (`service_name_taken`)
and a node that cannot reach this process (502) are one warning each and are
retried at every renewal. Publishing needs the node's gate token (a node the
SDK starts has one) and never keeps your process alive.

### Calling other agents' tools

```python
client = ciphyrs.CiphyrsClient(api_key=key, default_agent="support-bot")
client.mesh.list_tools()                                               # [{"name": "billing__refund", ...}]
client.mesh.call_tool_text("billing", "refund", {"payment_id": "pi_1", "amount": 500})
```

A refusal by policy is `ToolBlocked` (with `.tool`); a node that does not
answer, or no node, is `MeshNodeUnavailable`. The async client is the same
with `await`.

### HTTP and A2A services: `mesh.request`

```python
r = client.mesh.request("GET", "inventory", "/v1/items", params={"sku": 42})       # an httpx.Response
task = client.mesh.request("POST", "planner", "tasks/send", type="a2a", json=msg)
r = await aclient.mesh.request("GET", "inventory", "/v1/items")
```

The node resolves the service by name (404 `service_unknown`, 409
`service_ambiguous`) and applies the same policy as a tool call. You get the
response whatever its status; the agent header and the gate token are the
SDK's, no redirect is followed and the body is capped at 16 MiB. `path` stays
on the service: a `.` / `..` segment (`%2e` included), a backslash or an
encoded slash is `INVALID_ARGUMENT`.

### Queues: `wrap_message` / `unwrap_message` (any broker)

A message on a queue has no node in the middle, so the producer asks the
gateway for a **message token** bound to the sender, the receiver, the exact
bytes and a lifetime (the same edge policy as a call), and the consumer
verifies it offline before acting.

```python
# producer
body, headers = client.mesh.wrap_message({"order_id": 17}, to="fulfilment", mask=True)
# consumer
msg = client.mesh.unwrap_message(body, headers, agent="fulfilment")
msg.json()        # {"order_id": 17}; msg.from_agent, msg.message_id, msg.masked, msg.traceparent, msg.tokens_withheld, msg.withheld_labels
```

`payload` is bytes, a string, or anything JSON-serialisable. `from_agent`
defaults to `default_agent`, the current `@agent`, or `init(service_name=)`;
agent names follow the gateway rule (2-64 characters of letters, digits,
space, `_ . / -`, starting with a letter or digit).

```python
# Kafka (confluent-kafka): headers come back as a list of (name, bytes); unwrap_message reads them as they are.
producer.produce("orders", value=body, headers=list(headers.items()))
msg = client.mesh.unwrap_message(m.value(), m.headers(), agent="fulfilment")

# SQS (boto3): message attributes in, MessageAttributes out (MessageAttributeNames=["All"]).
sqs.send_message(QueueUrl=url, MessageBody=base64.b64encode(body).decode(),
                 MessageAttributes={k: {"DataType": "String", "StringValue": v} for k, v in headers.items()})
attrs = {k: v["StringValue"] for k, v in m["MessageAttributes"].items()}
msg = client.mesh.unwrap_message(base64.b64decode(m["Body"]), attrs, agent="fulfilment")

# RabbitMQ (pika)
ch.basic_publish("", "orders", body, pika.BasicProperties(headers=headers))
def on_message(ch, method, props, payload):
    msg = client.mesh.unwrap_message(payload, props.headers, agent="fulfilment")

# Google Pub/Sub
publisher.publish(topic, body, **headers)
def callback(m):
    msg = client.mesh.unwrap_message(m.data, dict(m.attributes), agent="fulfilment")

# NATS (nats-py; headers need a server with headers support, otherwise use embed mode)
await nc.publish("orders", body, headers=headers)
async def handler(m):
    msg = await aclient.mesh.unwrap_message(m.data, m.headers, agent="fulfilment")
```

**Embed mode** for channels with no headers (a Redis list, a webhook, a file
drop): `wrap_message(payload, to=..., embed=True)` returns `headers == {}`
and a body that is a small JSON envelope
(`{"ciphyrs_envelope":1,"token":…,"traceparent":…,"masked":…,"body_b64":…}`);
`unwrap_message` detects it when the headers carry no token.

Both ends prove who they are, as for a call-token mint: the SDK presents the
delegated token it holds for the sending (or consuming) agent, minting one on
first use, or your key is bound to that agent. Unproven is `MESH_REFUSED`
with `reason` `caller_unverified` (on wrap, and on an online unwrap) and a
message saying how to give the client an agent identity. A `429` on either
route is `RATE_LIMIT` (`CiphyrsRateLimitError`).

What `unwrap_message` checks, in order: the signature against the gateway's
published keys, `token_use` `mesh_message`, `aud` `mesh-message`, expiry, the
sender's project (`prj`) being present, the **tenant** (`tenant_id=`, else the tenant this client's own `wrap_message`
tokens carry; with neither, it proceeds and warns once — pass `tenant_id` or
`online=True`), that the token names **this** consumer, that the SHA-256 of
the received bytes is the one in the token, and that the message id was not
already accepted in this process. A masked payload is restored before the online check, so a failed restore
spends nothing and a redelivery can succeed. `online=True` then spends the id
at the gateway, which also checks project, quarantine and revocation (offline
verification cannot) and refuses a replay across consumer replicas — use it
at high message volume: the in-process window holds 100,000 unexpired ids,
and while an id it had to forget would still be valid, offline-only unwrap
is refused (`replay_window_exhausted`). Whether to restore is decided by the token's
signed `msk` claim, never by the `ciphyrs-masked` header; a partial restore
reports how many placeholders stayed masked (`tokens_withheld`, an int) and
their labels (`withheld_labels`). Any failure raises `MessageRefused` (code
`MESSAGE_REFUSED`) with a `reason` from SPEC 20.7.5 (`no_token`,
`bad_envelope`, `invalid_token`, `wrong_token_use`, `wrong_audience`,
`expired`, `tenant_mismatch`, `wrong_consumer`, `payload_mismatch`,
`replayed`, `replay_window_exhausted`, `restore_failed`; online also
`environment_mismatch`, `project_mismatch`, `quarantined`, `revoked`,
`refused_online`; when the check could not run `verify_unavailable`,
`replay_check_unavailable`, `verify_lookup_unavailable`,
`identity_lookup_unavailable`) and never the payload.
`mask=True` masks the payload at the gateway first (the vault session is
derived from the message id and kept for `ttl_seconds`, default 86400; the
token never outlives what your workspace keeps; under 60 s it is
`MESH_REFUSED` `vault_ttl_too_short`) and the consumer restores it. A mask
answer that is fail-closed / fail-open, has no masked text or names another
vault session is `BAD_RESPONSE`. A gateway refusal at wrap time
(`edge_not_granted`, `callee_unknown`, `duplicate_message_id`, …) is
`MESH_REFUSED` with that `reason`.

### Shared stores: provenance tags

```python
db.insert({**row, **ciphyrs.provenance_tag()})   # ciphyrs_agent, ciphyrs_trace_id, ciphyrs_span_id, ciphyrs_at
ciphyrs.record_provenance(db.get(row_id))         # a ciphyrs.provenance.read event on the current span
```

Tags are **unsigned**: they attribute a record to the agent and trace that
wrote it. They are not a security control — anyone who can write the store
can write a tag.

### The gate token

A node with `gate_token` set requires `Authorization: Bearer <token>` on every
call but `/health`, and its local admin API (publishing) always requires it.
The SDK presents, in order: `node_token`, `CIPHYRS_NODE_TOKEN`, the
`gate_token` of the discovered `endpoint.json`. It is never logged or put in
an error.

### Troubleshooting

`client.mesh.reason` / `client.mesh.status()["reason"]` when the mesh is off
(the codes of SPEC 20.4.5; a `MeshNodeUnavailable` message begins with the
code, `"<code>: <words>"`):
`not_found` (no running node in the home, or an `endpoint.json` without a
`peer_id` or `gate_token`: start one or use `mesh=True`),
`unhealthy` (endpoint.json names a node that does not answer `/health`),
`endpoint_mismatch` (it answers with another `peer_id` or cannot prove the
gate token), `node_gateway_mismatch` (a node of another gateway, or naming none),
`config_gateway_mismatch`, `unsafe_home` / `unsafe_config`, `no_api_key`,
`no_binary` (`pip install "ciphyrs[mesh]"` or set `CIPHYRS_NODE_BIN`),
`start_failed` / `start_timeout` (read `<home>/node.log`), `disabled`
(`mesh=False`); `message` says it in words. `ciphyrs.selfcheck()["mesh"]`
lists what is published (`published`, `server`, `last_error`, `reason`:
`publish_off` / `vetoed`, `errors` per agent: `service_name_taken`,
`agent_name_taken`, `target_is_gate`, `too_many_registrations`,
`no_gate_token`, `node_tenant_mismatch`) and the replay window (`messages`).
A publishing veto lasts for the life of the process. On the
async client, `mesh.available` / `reason` / `node_url` only report the last
resolution; `await mesh.ready()` resolves without blocking the loop. A node
that exits and comes back on another port is found again: an idempotent call
(`list_tools`, `status`, a `GET`) is retried once, a tool call is not.

- [Documentation](https://www.ciphyrs.com/docs)
- [Website](https://www.ciphyrs.com)
- [Dashboard](https://www.ciphyrs.com/dashboard)

_Third-party names are trademarks of their respective owners; no affiliation or endorsement is implied._
