Python SDK#

Install packages with the CLI, load tools, and inspect installed agents, skills, knowledge packages, memory blueprints, instruction profiles, and loops from Python.

CLI and lock compatibility#

SDK 0.1.17+ requires AgentPM CLI 0.1.43+ for every Tool call, including Node and older vendored Python Tools. Install the CLI separately and check agentpm --version. Set AGENTPM to an absolute CLI executable path when it is not on PATH; it is a single executable, not a shell command.

Runtime prerequisite for containers and CI: Include CLI 0.1.43+ in the final runtime image or CI job that executes SDK Tool calls, on PATH or at the absolute path configured by AGENTPM. Installing the Python agentpm SDK does not install the CLI. A CLI available only on the host or in a discarded build stage does not satisfy this requirement. Check agentpm --version inside the actual runtime container or job before running the app's Tool-call smoke test.

The SDK reads agent.lock v2, v3 and v4 without rewriting it. Unsupported future or malformed locks fail with update/install guidance. An installed Agent can be loaded from a project containing just agent.lock and .agentpm; no app agent.json is required. Exact locked references remain exact when other versions coexist. A local author Tool root is not an installed Agent.

Calls follow app → SDK → agentpm run --machine → Tool. The SDK unwraps the CLI result and returns the Tool's original JSON data. A Tool's ok: false stays ordinary returned data; runner failures raise an exception. Interpreter, schema, target, installed-state, timeout and managed-environment checks belong to the CLI. They happen on invocation, so metadata loading itself needs no CLI or available Tool interpreter. The SDK retains bounded input/output transport and passes the requested timeout to the CLI. Ctrl-C is handled by the CLI's scoped child cleanup; SDK interruption also terminates its CLI child.

Environment precedence is ambient values, defaults for missing variables, entrypoint env, then caller env. Required variables may come from any of these layers. Managed Python strips PYTHONPATH and PYTHONHOME after layering. Use AGENTPM_PYTHON to select a compatible base interpreter before install, not to bypass the managed environment. Caller options and credential values are not printed in SDK debug output; credential values are redacted from CLI diagnostics. Tool results are returned unchanged, so Tools must not return secrets themselves.

Run agentpm install explicitly to provision dependencies. If runtime state is missing/stale, reinstall with the selected AGENTPM_PYTHON; use agentpm install --refresh to repair damaged packages. Calls never auto-install, resolve from an index, rewrite the lock or fall back to app/global Python. Older SDK versions do not become v4-compatible merely because CLI install passed.

Goal#

Install the Python SDK and use:

  • load() to call a published tool
  • load_agent() to inspect an installed agent package and its resolved packages
  • load_skill() to inspect an installed skill package and its resolved tools
  • load_knowledge() to inspect an installed knowledge package and its mode-specific metadata
  • load_memory() to inspect an installed memory blueprint package and its generated contracts
  • load_profile() to inspect an installed instruction profile package and its authored metadata
  • load_loop() to inspect an installed loop package and its authored orchestration metadata

1) Install a tool#

From your project with an agent manifest:

# declare and install a specific tool version
agentpm install @zack/summarize@0.1.3
# or: edit agent.json → tools[] then run agentpm install

This resolves and prepares the tool under: .agentpm/tools/<namespace>/<name>/<version>

You can also install a published agent package directly:

agentpm install @zack/support-agent@0.1.0

That writes:

  • the installed agent under .agentpm/agents/<namespace>/<name>/<version>
  • its resolved knowledge packages under .agentpm/knowledge/<namespace>/<name>/<version>
  • its resolved memory packages under .agentpm/memory/<namespace>/<name>/<version>
  • its resolved profile packages under .agentpm/profiles/<namespace>/<name>/<version>
  • its resolved loop package under .agentpm/loops/<namespace>/<name>/<version>
  • its resolved skills under .agentpm/skills/<namespace>/<name>/<version>
  • its resolved tools under .agentpm/tools/<namespace>/<name>/<version>

You can also install a published skill package directly:

agentpm install @zack/incident-commander@0.1.0

That writes:

  • the installed skill under .agentpm/skills/<namespace>/<name>/<version>
  • its resolved tools under .agentpm/tools/<namespace>/<name>/<version>

You can also install a published knowledge package directly:

agentpm install @zack/python-docs@0.1.0

That writes:

  • the installed knowledge package under .agentpm/knowledge/<namespace>/<name>/<version>

You can also install a published memory blueprint package directly:

agentpm install @zack/profile-memory@0.1.0

That writes:

  • the installed memory package under .agentpm/memory/<namespace>/<name>/<version>

You can also install a published profile package directly:

agentpm install @zack/support-style@0.1.0

That writes:

  • the installed profile package under .agentpm/profiles/<namespace>/<name>/<version>

You can also install a published loop package directly:

agentpm install @zack/incident-response-loop@1.0.0

That writes:

  • the installed loop package under .agentpm/loops/<namespace>/<name>/<version>

2) Install the Python SDK#

uv pip install agentpm
# or: pip install agentpm

3) The load() function (core API)#

load() resolves the tool and returns a callable bound to a managed subprocess.

Basic usage#

from agentpm import load
 
summarize = load("@zack/summarize@0.1.3")
result = summarize({ "text": "Cats are elegant, enigmatic creatures." })
print(result)

Type signature (overloads)#

from typing import Callable, TypedDict, Literal
 
ToolFunc = Callable[[JsonValue], JsonValue]
 
class LoadedWithMeta(TypedDict):
    func: ToolFunc
    meta: ToolMeta
 
def load(
    spec: str,
    with_meta: bool = False,
    timeout: float | None = None,
    tool_dir_override: str | None = None,
    env: dict[str, str] | None = None,
) -> ToolFunc | LoadedWithMeta: ...

Arguments#

  • spec: str — tool spec like @namespace/name@0.1.3
  • with_meta: bool = False — include manifest metadata in the return value
  • timeout: float | None = None — per-call hard cap in seconds (default: 120.0)
  • tool_dir_override: str | None = None — custom tool root (tests/local layouts)
  • env: dict[str, str] | None = None — merged into the subprocess environment

Example with environment and timeout#

from agentpm import load
import os
 
capitalize = load(
    "@zack/capitalize@0.1.11",
    timeout=30.0,
    env={ "OPENAI_API_KEY": os.environ["OPENAI_API_KEY"] },
)
 
out = capitalize({
    "text": "Cats are some of the most amazing creatures—loving, curious, and a little wild at heart.",
    "doKeywords": True,
    "doSentiment": True,
    "doSummary": True,
    "maxSummaryChars": 200,
})
print(out)

4) Loading with metadata#

Ask load() for manifest data you can hand to your agent runtime (for tool descriptions, IO schemas, etc.).

from agentpm import load
 
loaded = load("@zack/capitalize@0.1.11", with_meta=True)
func = loaded["func"]
meta = loaded["meta"]
 
out2 = func({ "text": "hi" })

meta fields:

# meta: ToolMeta
# {
#   "name": str,
#   "version": str,
#   "description": str | None,
#   "inputs": JsonValue | None,   # JSON Schema (Draft 2020-12)
#   "outputs": JsonValue | None,  # JSON Schema (Draft 2020-12)
#   "runtime": { "type": "node|python", "version": "…" } | None
# }

Using meta to configure an agent tool (example)#

from agentpm import load
import json
 
tools = [
    load("@zack/capitalize@0.1.11", with_meta=True),
    load("@zack/summarize@0.1.3", with_meta=True),
]
 
agent_tools = []
for t in tools:
    func, meta = t["func"], t["meta"]
    agent_tools.append({
        "name": meta["name"],
        "description": meta.get("description") or "AgentPM tool",
        # helpful: concatenate description + IO shapes for better tool selection
        "longDescription": f'{meta.get("description","")}\n\n'
                           f'Inputs: {json.dumps(meta.get("inputs"))}\n'
                           f'Outputs: {json.dumps(meta.get("outputs"))}',
        "call": func,  # the callable your agent runtime will invoke
    })
 
# register agent_tools with your agent runtime’s tool loader

5) Loading an installed agent package#

Use load_agent() when you want metadata for a registry-installed agent package plus the concrete package refs it resolved to at install time.

from agentpm import load, load_agent, load_skill
 
agent = load_agent("@zack/support-agent@0.1.0")
first_skill = agent["resolvedSkills"][0]
skill = load_skill(f'{first_skill["name"]}@{first_skill["version"]}')
first_tool = skill["resolvedTools"][0]
tool = load(f'{first_tool["name"]}@{first_tool["version"]}')

What load_agent() returns:

  • the installed agent manifest
  • the installed agent root path
  • resolvedKnowledge, which are the exact knowledge package refs represented in agent.lock
  • resolvedMemory, which are the exact memory package refs represented in agent.lock
  • resolvedProfiles, which are the exact profile package refs represented in agent.lock
  • resolvedLoop, which is the exact singular loop ref represented in agent.lock
  • reserved refs (knowledge, memory, profiles) from the lockfile metadata path
  • resolvedTools, which are the exact tool package refs represented in agent.lock
  • resolvedSkills, which are the exact skill package refs represented in agent.lock

Compatibility note:

  • resolvedKnowledge is populated from the modern first-class root.knowledge entries in agent.lock.
  • reserved.knowledge is legacy pass-through metadata from older lockfile shapes. For current installs, treat resolvedKnowledge as authoritative and expect reserved.knowledge to usually be empty.
  • If your workspace still has an older lockfile shape where Knowledge refs only exist under reserved.knowledge, rerun agentpm install to rewrite the lockfile.
  • resolvedLoop is populated from the modern first-class root.loop entry in agent.lock.
  • resolvedProfiles is populated from the modern first-class root.profiles entries in agent.lock.
  • reserved.profiles is legacy pass-through metadata from older lockfile shapes. For current installs, treat resolvedProfiles as authoritative and expect reserved.profiles to usually be empty.
  • manifest["loop"] and manifest["bindings"] preserve the authored declarative metadata from the installed agent.json.

What it does not do:

  • it does not execute the agent package
  • it does not orchestrate the tools for you
  • it does not load the local project ./agent.json

That makes load_agent() the Python mirror of the Node SDK’s loadAgent():

  • inspect an installed agent package
  • get the exact resolved package refs
  • choose which skills and tools to load into your runtime

6) Loading an installed skill package#

Use load_skill() when you want metadata for a registry-installed skill package plus the concrete tool refs it resolved to at install time.

from agentpm import load_skill
 
skill = load_skill("@zack/incident-commander@0.1.0")
 
print(skill["entrypointPath"])
print(skill["entrypointContent"])
print(skill["references"])
print(skill["scripts"])
print(skill["resolvedTools"])

load_skill() returns an inspectable Skill object. Skills are not runnable SDK objects by themselves.

7) Loading an installed knowledge package#

Use load_knowledge() when you want metadata for a registry-installed Knowledge package plus the canonical package-relative paths it declares.

from agentpm import load_knowledge
 
knowledge = load_knowledge("@zack/python-docs@0.1.0")
 
print(knowledge["knowledge"]["mode"])
print(knowledge["documentPaths"])
print(knowledge["chunksPath"])
print(knowledge["sourcesPath"])
print(knowledge["vectorsPath"])
print(knowledge["indexPaths"])

load_knowledge() returns an inspectable knowledge object. Knowledge packages are not runnable SDK objects by themselves.

8) Loading an installed memory blueprint package#

Use load_memory() when you want authored memory blueprint metadata, parsed build metadata, the persisted contract index, and on-demand access to resolved contracts.

from agentpm import load_memory, load_memory_contract
 
memory = load_memory("@zack/profile-memory@0.1.0")
contract = load_memory_contract(
    memory,
    space="profile",
    record_type="user_preference",
)
 
print(memory["memory"]["spaces"])
print(memory["build"])
print(memory["contractIndex"])
print(memory["contracts"])
print(contract)

load_memory() returns an inspectable memory object. Memory packages are not runnable SDK objects by themselves and do not provide live record CRUD behavior.

9) Loading an installed instruction profile package#

Use load_profile() when you want authored Instruction Profile metadata from an installed registry package.

from agentpm import load_profile
 
profile = load_profile("@zack/support-style@0.1.0")
 
print(profile["profile"]["identity"]["role"])
print(profile["profile"]["objectives"])
print(profile["profile"]["communication"])

load_profile() returns an inspectable profile object containing:

  • the installed profile manifest
  • the installed package root path
  • parsed authored profile metadata

It does not compile prompts, interpret README content as instructions, enforce constraints, or execute runtime behavior.

10) Loading an installed loop package#

Use load_loop() when you want authored Loop metadata from an installed registry package.

from agentpm import load_loop
 
loop = load_loop("@zack/incident-response-loop@1.0.0")
 
print(loop["loop"]["entry_phase"])
print(loop["loop"]["phases"])
print(loop["loop"]["transitions"])
print(loop["loop"]["error_policy"])

load_loop() returns an inspectable Loop object containing:

  • the installed loop manifest
  • the installed package root path
  • parsed authored loop metadata

It does not execute the graph, choose a model, resolve Agent phase bindings, validate Memory selectors against installed blueprints, start MCP, or read consumer_context.file. Use HarnessClient when you want the SDK to host agentpm harness --machine.

load() stays tool-only#

from agentpm import load
 
load("@zack/incident-commander@0.1.0")
# raises: use load_skill("@zack/incident-commander@0.1.0") instead
 
load("@zack/python-docs@0.1.0")
# raises: use load_knowledge("@zack/python-docs@0.1.0") instead
 
load("@zack/profile-memory@0.1.0")
# raises: use load_memory("@zack/profile-memory@0.1.0") instead
 
load("@zack/support-style@0.1.0")
# raises: use load_profile("@zack/support-style@0.1.0") instead
 
load("@zack/incident-response-loop@1.0.0")
# raises: use load_loop("@zack/incident-response-loop@1.0.0") instead

11) Execution contract (how tools must behave)#

For a tool to work with the SDK, it must follow this process protocol:

  • STDIN: SDK sends the input to the CLI, which writes JSON to the Tool subprocess stdin.
  • STDOUT: Tool writes exactly one JSON object (tool outputs) to stdout (typically the last line).
  • STDERR: Any logs/diagnostics go to stderr.
  • Exit code: 0 on success; non-zero indicates failure.

(The full rationale and Node example are on the Node SDK page; the contract is identical here.)

12) Loading and invocation checks#

load() discovers installed metadata, preserves the selected exact version, and checks required environment variables. It returns the same callable shape as before. It does not start a Tool or provision an environment.

When you invoke the callable, the SDK requires CLI 0.1.43+ and delegates to agentpm run --machine. The CLI checks the entrypoint interpreter family, runtime version, input/output schemas, installed target state and managed Python environment. Runtime failures raise SDK exceptions; Python timeout failures raise TimeoutError, and Node failures reject the Promise. A Tool returning ok: false remains normal Tool data.

13) CLI-owned execution#

The CLI launches the selected installed payload in tool_root / entrypoint.cwd (default .). Caller env overrides entrypoint env; defaults fill missing values. It owns timeout, output limits and child cleanup. The SDK bridge keeps the historical 10 MB Tool-output budget and support for a JSON object after legacy stdout logs, while waiting for a completed CLI result. Write logs to stderr in new Tools. A Tool must finish before the timeout, even if it already printed JSON.

Dependency-bearing Python runs in the CLI-provisioned environment with ambient PYTHONPATH/PYTHONHOME removed. Legacy vendored Python and Node Tools also use the CLI; the SDK no longer adds its own interpreter flags, temporary HOME, resource limits or separate subprocess policy. Put any required Node runtime flags explicitly in entrypoint.args.

14) Troubleshooting#

  • Interpreter not found
    • Ensure node/python is on PATH. Use the CLI diagnostic to repair interpreter selection; SDK errors do not dump PATH.
  • Timeouts
    • Increase timeout (seconds) in load() or set entrypoint.timeout_ms (SDK uses the per-call value).
  • Non-JSON output
    • Make sure only one valid JSON object is written to stdout; logs go to stderr. The CLI diagnostic points to its failure logs; the SDK forwards redacted stderr.
  • Runtime mismatch
    • Align runtime.type (node/python) with entrypoint.command.
  • Local testing / custom layouts
    • Use toolDirOverride in Node or tool_dir_override in Python to select an installed-tools base directory.
  • Modern package loading requires a current agent.lock
    • load_agent() and load_skill() read modern lockfile shapes. If the lockfile is missing or too old, rerun agentpm install.
  • Agent installed on disk but not in the lockfile
    • load_agent() uses the installed agent directory and the agent.lock root entry together. If the lockfile is missing the agent root, reinstall it.
  • Skill installed on disk but not in the lockfile
    • load_skill() uses the installed skill directory and the agent.lock root entry together. If the lockfile is missing the skill root, reinstall it.

15) Best practices#

  • Define strong IO schemas so agents construct correct arguments.
  • Keep logs off stdout; stdout is reserved for the final JSON.
  • Set sensible timeouts (entrypoint.timeout_ms) and document required env vars in your tool README/manifest descriptions.

Release and migration reference#

Keep SDK 0.1.17+ and CLI 0.1.43+ installed together. Upgrade this SDK with its language package manager; update AgentPM packages using agentpm install. A newer CLI alone does not make an older SDK understand v4 managed Tool state.

See Python dependency migration and release integrity for the legacy/new-format boundary, portable lock state, target selection and actual signature/attestation verification. The maintained examples include no-model smoke entrypoints that invoke the installed Python Tool through each SDK.