Metadata-Version: 2.5
Name: agentic-platform-sdk
Version: 0.1.0
Summary: Python SDK for the Agentic Platform Open API (/open/v1)
Project-URL: Stand-in platform, https://pypi.org/project/agentic-platform-standin/
Author: Agentic Platform contributors
License-Expression: Apache-2.0
License-File: LICENSE
Keywords: a2a,agentic-platform,llm,open-api,rag,sdk
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.11
Requires-Dist: httpx>=0.27
Requires-Dist: pydantic>=2.7
Requires-Dist: pyjwt[crypto]>=2.9
Provides-Extra: dev
Requires-Dist: datamodel-code-generator==0.96.0; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.24; extra == 'dev'
Requires-Dist: pytest>=8; extra == 'dev'
Requires-Dist: respx>=0.21; extra == 'dev'
Requires-Dist: ruff==0.17.5; extra == 'dev'
Provides-Extra: mcp
Requires-Dist: mcp<3,>=2.3; extra == 'mcp'
Provides-Extra: testing
Requires-Dist: agentic-platform-standin==0.1.0; extra == 'testing'
Requires-Dist: pyyaml>=6; extra == 'testing'
Description-Content-Type: text/markdown

# agentic-platform-sdk (Python)

The Python SDK of the Agentic Platform's open API (`/open/v1`): sync and async clients, API-key,
DPoP and token-callable auth, retries, paging, typed errors and models, and an in-memory fake for
tests. Python 3.11 or newer.

```
pip install agentic-platform-sdk
pip install 'agentic-platform-sdk[testing]'   # adds the stand-in platform (agentic-platform-standin)
```

```python
from agentic_platform_sdk import AgenticClient
from agentic_platform_sdk.auth import ApiKey

with AgenticClient("https://platform.example.com", ApiKey("agk_...")) as client:
    print(client.me.get())
```

`agentic_platform_sdk.testing` has `FakeAgenticClient` (in memory) and `run_standin()` (the stand-in
platform in a subprocess). The contract, the conformance scenarios and the call areas ship with the
platform's source repository, not with this package.

## Logging

httpx logs every request at INFO with its full URL, query string included (ids, search terms).
Unless you want that in your logs, raise its level:

```python
import logging

logging.getLogger("httpx").setLevel(logging.WARNING)
```

## Timeouts

Defaults, overridable per call (`timeout=`), per operation (`timeouts={"<operationId>": s}`) or per
area (`timeouts={"<area>": s}`), in that order; an area entry does not undo the upload and blocking
send defaults below:

| call | timeout |
|---|---|
| any area not listed | 30 s |
| `llm` | 180 s |
| `vision` | 600 s |
| a document upload (`kb.upload_document`) | 300 s |
| a blocking `agents.send` (the platform waits up to 240 s) | 250 s |
| `agents.stream` | no read timeout |

A timeout applies to each attempt. A retried call makes up to 3 attempts (`RetryConfig.tries`), so
the worst case for a blocking send that is retried is 3 x 250 s = 750 s, plus the backoff waits
(at most `RetryConfig.budget_s`, 30 s, in all). Pass a smaller `timeout=` or a `RetryConfig` with
fewer tries when a caller cannot wait that long.

## Chat events (`agentic_platform_sdk.chat`)

`client.agents.stream(agent_id, text, chat_events=True)` activates the platform's chat-events extension and yields typed
events (`TextDelta`, `ThinkingDelta`, `ToolCall`, `ToolResult`, `Approval`, `Sources`, `Plan`, `SubAgent`, `Status`),
ending with `Done(task)`; an event type this SDK does not know arrives as `Unknown`, never an error. `app_context={...}`
(at most 4096 bytes of compact JSON) is handed to the app's tools. A dropped stream is resumed with
`client.agents.subscribe`'s mechanism (`after_seq` = the last `seq` seen) up to 3 times, each event reaching you once;
past that, or when the platform's event log is gone (`a2a.events_unavailable`), `Done` carries the task as `GetTask`
sees it, which may still be running: check `done.task.state`. `resume=False` raises the drop instead. A text event with
`append=False` replaces the answer so far. `approvals.decide(request_id, "approve")` answers an `Approval` event; a
late decision (the run's 210 s cap, `a2a.task_timeout`) is `Conflict` `approval.request_not_pending`.

## App tool endpoints (`agentic_platform_sdk.tools`)

A platform agent can call an app's own tools, as the user whose task is running, at the app's registered MCP endpoint.
Every request carries a short-lived HS256 token signed with the app's `ats_` secret. The helper checks it and hands
the handler who is calling:

```python
from agentic_platform_sdk.tools import CallbackAuth, InMemoryReplayStore, current_caller, ref

# in front of an ASGI app that serves MCP over STATELESS Streamable HTTP; pass both secrets (a list of `ats_`
# strings, never a bare string) while one is being rotated
guarded = CallbackAuth(
    mcp_asgi_app,
    audience="my-app-slug",
    secrets=lambda: [CURRENT, PREVIOUS],
    replay=InMemoryReplayStore(),
)  # several replicas: an AsyncReplayStore on Redis (SET NX EXAT)


async def start_job(spec: str):
    caller = current_caller.get()  # ToolCaller: user_sub, sub_iss, workspace_id, task_id, ...
    user = my_users.by_subject(
        caller.sub_iss, caller.user_sub
    )  # your own user; run your normal access checks
    job_id = queue.enqueue(user, spec)
    return {
        "ref": ref("my-app.job", job_id)
    }  # return at once; the UI fetches the job through your API
```

- **Never take a user or workspace id from the tool's arguments.** The caller is the token's `sub`; arguments are the
  model's input.
- A refused request (bad signature, expired, wrong audience, wrong tool, changed app context, a replayed token, a
  `sync` token on `tools/call`) is HTTP 401 with no detail; `on_refused(code)` receives the `callback.*` code for your log.
- **Stateless mode only.** `current_caller` is a context variable, right only while the tool handler runs in the
  HTTP request's own task. A stateless Streamable HTTP server does that; a stateful one (it sets `Mcp-Session-Id`)
  runs handlers in a session task made by the first request, so a later call would see that request's caller (none,
  or another user's). Never put `CallbackAuth` in front of a stateful server, and never run a handler in a
  background task that reads `current_caller` (copy the `ToolCaller` out first).
- Only `initialize`, `notifications/initialized`, `tools/list` and `ping` are served on a `sync` token; any other
  method, a body that does not parse as a JSON-RPC object (or array of objects), a batch holding a `tools/call`,
  and a WebSocket are refused. `secrets` must be a list of `ats_` secrets (a bare string or a short secret raises at
  construction); `iss` is informational (the app checks `aud`).
- A replay store is called on the event loop: `InMemoryReplayStore` (one process) is fine; a network store must
  implement `AsyncReplayStore` (`async def seen_or_add(jti, until)`, awaited), so it never blocks the loop. It
  remembers each jti until `exp` + the 30 s leeway.
- Token claims, the app-context hash (RFC 8785) and the codes: `sdk/spec/README.md`, "App tool callback".

### The MCP server on the official SDK (`[mcp]` extra)

`AgenticToolServer` is the whole thing in one class: the official `mcp` SDK (`pip install 'agentic-platform-sdk[mcp]'`,
`mcp>=2.3,<3`; it is an optional extra, never a core dependency) in stateless Streamable HTTP with JSON replies, behind
`CallbackAuth`. A `caller: ToolCaller` parameter is filled from the verified token and is not in the tool's input schema:

```python
from agentic_platform_sdk.tools import ToolCaller, ToolResult, ref
from agentic_platform_sdk.tools.mcp import (
    AgenticToolServer,
)  # imports `mcp`; raises ImportError without the extra

server = AgenticToolServer("my-app-slug", secrets=lambda: [CURRENT, PREVIOUS])


@server.tool(description="Start a part-generation job")
async def start_job(spec: str, caller: ToolCaller) -> ToolResult:
    user = my_users.by_subject(caller.sub_iss, caller.user_sub)
    return ToolResult(
        "started", ref=ref("my-app.job", queue.enqueue(user, spec))
    )  # `ref` -> structuredContent.ref


app = server.asgi_app()  # uvicorn.run(app): endpoint http://host:port/mcp
```

- `stateless=False` is refused (see "Stateless mode only" above). Register every tool before calling `asgi_app()`.
- To mount it in another app (FastAPI `app.mount("/tools", server.asgi_app())`), give the host app
  `lifespan=server.lifespan`: the MCP session manager then runs once for the process. Served on its own, `asgi_app()`
  runs it itself. With no lifespan at all (a bare `TestClient(app)` without `with`, a host that does not forward
  lifespan) each request runs its own short-lived manager: correct, a little slower. `server.lifespan()` may be nested
  (an inner entry is only counted) and entered again once every earlier entry has exited. The first entry owns the
  manager: if overlapping entries exit out of order, the others finish on per-request managers (correct, slower). The
  no-lifespan mode is safe across threads.
- **Input schemas and arguments.** `tools/list` shows each tool's schema without pydantic's `title` keys and with
  `additionalProperties: false`. `@server.tool(input_schema={...})` shows your own object schema instead (the handler is
  still what runs, behind the same `caller` injection and token check; its signature still validates the types).
  **The schema must match the handler**, checked at registration (a `TypeError`, so a mismatch never ships): every
  required handler parameter (no default; not the injected `caller`) must be in `properties` and in `required`; the
  schema may not declare a property the handler does not accept, unless the handler takes `**kwargs`; and it may not
  declare the injected `caller`. An optional handler parameter may be left out of the schema.
  Arguments are checked on the raw call before the handler runs: an **undeclared argument** (anything outside the
  schema's `properties`, `caller` and ids included) is refused; `@server.tool(validate=fn)` runs `fn(arguments)` (sync
  or async, must not block) on a copy of the raw arguments (the verified caller is `current_caller.get()` inside it) and refuses with your own text (`raise InvalidArguments("...")`,
  optionally `code="my.code"`) or by returning a `ToolResult`; a type or missing-field failure answers
  `tool.invalid_arguments: <tool>: invalid or missing argument(s): <names>` (names only, never values or library text).
  Every refusal is a normal result with `isError: true`, which the platform shows the model as the app's own text
  (`app_tool.tool_error`). With `additionalProperties: true` in your schema nothing undeclared is refused, but a handler
  only receives its declared parameters.
- **Unknown tool** answers HTTP 200 with `isError: true` and `tool.unknown: no tool named '<name>'`, not a JSON-RPC
  error: the platform's client maps a JSON-RPC `error` to `app_tool.unavailable` (the app is treated as down and the model
  sees none of your text) and an `isError` result to `app_tool.tool_error` with your text. (The MCP spec says -32602 here;
  this server chooses what the platform can use.)
- **One request per POST**: a JSON-RPC batch answers 400 `-32600 "one request per POST"` (a batch holding a `tools/call`
  is refused earlier by `CallbackAuth`, empty 401). **Only POST**: `GET` / `DELETE` / any other method answer 405
  `Allow: POST` once the token verified (stateless, JSON replies: no event stream, no session to end).
- **`initialize`** advertises `{"tools": {"listChanged": false}}` only (prompts, resources, subscriptions and
  completions are not served). `protocolVersion`: the client's is echoed when the official SDK supports it (the
  platform's client sends `2025-06-18` and gets it back), else the SDK's latest is answered and the client decides.
- `max_concurrency=N` (on `AgenticToolServer`, or per tool on `@server.tool`) caps how many plain (non-async) handlers run
  at once; unset, anyio's default thread limiter (40) applies. Use one event loop per server when a cap is set (anyio's limiter is not safe to share between loops).
- The `caller` parameter may be written `ToolCaller`, `ToolCaller | None`, `Optional[ToolCaller]`, `Annotated[...]` of
  those, or be a bare `caller`; it is always filled from the verified token. Any other annotation that mentions
  `ToolCaller` (`list[ToolCaller]`, `ToolCaller | str`), or a parameter named `caller` that is not annotated exactly so,
  is a `TypeError` at `@server.tool()`; a registered schema that would build a `ToolCaller` from the arguments is refused too.
- A plain (non-async) handler runs in a worker thread, so a blocking call does not stall other callers.
- The official server object is private (`server._mcp`). Registering a tool on it, or serving its
  `streamable_http_app()`, bypasses both the `caller` injection and the token check; use `@server.tool()` and `asgi_app()` only.
- DNS-rebinding host checks are off by default: every request (every method, GET included) already needs an HS256 call
  or sync token for your audience, valid for 120 s and single-use (`jti`), which a rebinding page cannot mint; the official
  default accepts only `localhost`, which would refuse the platform's calls to your host name. `allowed_hosts=[...]` turns
  them on. With it set, a request that carries an `Origin` header is refused (`allowed_origins=[]`: fine for the
  platform's server-side client, not for a browser test tool), and the host check runs after the token check, so a
  refused host has already used up its token's `jti`.
- `examples/app_tool_sample` is a runnable sample (`python -m app_tool_sample` from `examples/`, with
  `SAMPLE_APP_TOOL_SECRET`): `start_job` returns a ref at once, `get_job`, `list_items`, per-user access.
