Metadata-Version: 2.5
Name: contexory-sdk
Version: 0.1.0
Summary: Resolve a Contexory agent's released context at runtime: cached, signature-verified, and safe when Contexory is unreachable.
Project-URL: Homepage, https://github.com/wedgey/contexory/tree/main/packages/sdk-python#readme
Project-URL: Repository, https://github.com/wedgey/contexory
License: MIT
License-File: LICENSE
Keywords: agent-skills,ai-agents,claude-agent-sdk,contexory,langchain,prompt-management,pydantic-ai
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: cryptography>=42
Provides-Extra: claude-agent-sdk
Requires-Dist: claude-agent-sdk>=0.1; extra == 'claude-agent-sdk'
Provides-Extra: dev
Requires-Dist: claude-agent-sdk>=0.1; extra == 'dev'
Requires-Dist: langchain>=1.0; extra == 'dev'
Requires-Dist: opentelemetry-api>=1.25; extra == 'dev'
Requires-Dist: opentelemetry-sdk>=1.25; extra == 'dev'
Requires-Dist: pydantic-ai-slim>=1.0; extra == 'dev'
Requires-Dist: pytest>=8; extra == 'dev'
Requires-Dist: ruff>=0.6; extra == 'dev'
Provides-Extra: langchain
Requires-Dist: langchain>=1.0; extra == 'langchain'
Provides-Extra: otel
Requires-Dist: opentelemetry-api>=1.25; extra == 'otel'
Requires-Dist: opentelemetry-sdk>=1.25; extra == 'otel'
Provides-Extra: pydantic-ai
Requires-Dist: pydantic-ai-slim>=1.0; extra == 'pydantic-ai'
Description-Content-Type: text/markdown

# contexory-sdk (Python)

Resolve a Contexory agent's released context at runtime: the system prompt, skills and tool
descriptions under a label such as `production`. Cached, signature-verified, and safe when Contexory is
unreachable. It is the Python twin of [`@contexory/sdk`](../sdk): same wire format, same cache layout,
same failure rules, and a shared parity suite that fails if they drift.

```bash
pip install contexory-sdk                     # resolve + apply_tools
pip install 'contexory-sdk[otel]'             # instrument()
pip install 'contexory-sdk[langchain]'        # + adapters, per framework
```

Python 3.10 or newer. The only hard dependency is `cryptography`, for Ed25519.

## resolve

```python
from contexory import Contexory

contexory = Contexory()  # CONTEXORY_API_TOKEN holds a con_rt_ runtime key
ctx = contexory.resolve("support-agent")  # label defaults to "production"

system = ctx.system
ctx.release.number  # 43
ctx.source  # "network" | "cache" | "stale-cache"
ctx.stale  # True when Contexory failed and this is the last verified release
```

`await contexory.aresolve(...)` runs the same call off the event loop.

- Every response is verified with Ed25519 against the keys at `/api/v1/signing-keys`. A bad or missing
  signature raises `ContexorySignatureError` and never falls back to the cache.
- A refusal (401, 403, 404) raises `ContexoryResolveError` with `.status`. Any other failure serves the
  last verified release and sets `ctx.stale` and `ctx.error`; with nothing cached it raises.
- Releases are cached on disk (`CONTEXORY_CACHE_DIR`, default `~/.cache/contexory/sdk`) for `ttl_ms`
  (60s), then revalidated with `If-None-Match`. The layout is byte-compatible with the TypeScript SDK's.
- Missing key: `resolve` raises immediately. The TypeScript SDK would serve a cache written under the same
  empty key; there is no such cache to serve.

## apply_tools

```python
tools = ctx.apply_tools(my_tools)  # dict keyed by name, or list of tools
tools = ctx.apply_tools(my_tools, renames={"refund": "issue_refund"})
ctx.original_tool_name("issue_refund")  # "refund"
```

Tools may be dicts, dataclasses, Pydantic models or plain objects with `name`/`description`. Hosted tools
(no `description`) pass through untouched.

## Upstream MCP descriptions

A toolset override can be pinned to the MCP server it overrides (`upstream: {server, hash}` in `tools.json`).
`apply_tools` then applies it only while the server's description still hashes to the one Contexory
accepted; otherwise the server's own text stands and the tool is listed in `held` (`ctx.held` after
`ctx.apply_tools`).

```python
from contexory import watch_mcp_tools

watch = watch_mcp_tools(
    server="zendesk",  # the name the toolset uses in upstream.server
    list_tools=lambda: {"tools": mcp.list_tools(), "ttlMs": None},  # your MCP client's tools/list
    report={"ingest_key": "con_ing_...", "agent": "support-agent", "release": ctx.release.number},
)
watch.start()  # polls on the server's ttlMs, clamped to 5s..1h (default 5min)
tools = ctx.apply_tools(my_tools, upstream_hashes=watch.latest())
```

`hash_mcp_tools`, `mcp_tools_hash`, `description_hash`, `schema_hash` and `canonical_json` are the same
hashes the server and the TypeScript SDK compute, held to `packages/shared/src/mcp-upstream/vectors.json`.
`report_upstream_hashes` posts with a write-only `con_ing_` ingest key, never a runtime key.

## instrument

```python
from opentelemetry.sdk.trace import TracerProvider
from contexory import instrument

handle = instrument(ctx)  # or instrument(43), instrument("r43")
provider = TracerProvider()
provider.add_span_processor(handle.processor)

with handle.run_with_release(44):  # per-request scope; concurrent scopes never cross
    ...
```

Stamps `gen_ai.agent.version` and the Langfuse, LangSmith and Braintrust metadata attributes on every
span. `vendors=[]` writes only `gen_ai.agent.version`; `baggage=True` carries the scope in W3C baggage.

## Adapters

| Framework | Use |
|---|---|
| LangChain / LangGraph | `create_agent(model, tools, middleware=[ContexoryMiddleware(ctx)])` from `contexory.adapters.langchain`; implements `wrap_model_call`. `apply_system=True` also swaps in the released system prompt |
| Pydantic AI | `Agent(model, prepare_tools=prepare_tools(ctx))` from `contexory.adapters.pydantic_ai`; descriptions only |
| Claude Agent SDK | `create_proxy_server(ctx, upstream_tools)` from `contexory.adapters.claude_agent_sdk` returns an in-process MCP server that re-exposes external tools with the released descriptions and forwards calls. Pass it in `mcp_servers` and disallow the originals; the model sees `mcp__contexory__<tool>` |

## Develop

```bash
cd packages/sdk-python
python -m venv .venv && . .venv/bin/activate
pip install -e '.[dev]'
ruff check . && ruff format --check . && pytest
```

`parity/fixtures.json` is generated by the TypeScript SDK (`UPDATE_PARITY=1 pnpm exec vitest run --project
sdk-python`) and replayed by `tests/test_parity.py`. Change `parity/cases.ts`, regenerate, and both suites
must pass. `pnpm test` runs the TypeScript half.

## Releasing

Releases go to PyPI as `contexory-sdk` through trusted publishing (OIDC): no token exists. The
`publish` job in `.github/workflows/sdk-python.yml` runs only for a pushed `sdk-python-v*` tag, after
the test matrix and build pass.

1. Bump `version` in `pyproject.toml` and merge it to `main`.
2. Tag that commit and push the tag. The tag must equal the version, or the job fails:

```bash
git tag sdk-python-v0.1.0 && git push origin sdk-python-v0.1.0
```

One-time setup (pending trusted publisher on PyPI, GitHub environment `pypi`):
[`docs/RELEASING.md`](../../docs/RELEASING.md#python-sdk-pypi).
