Python SDK for programmatic access to papert-code CLI
Project description
papert-code-sdk
Python SDK for programmatic access to the Papert Code CLI with streaming, control messages, permission callbacks, abort support, and MCP integration.
Installation
pip install papert-code-sdk
Requirements
- Python >= 3.8
- A
papertCLI available inPATH, or setpathToPapertExecutable - Node.js >= 18 when running JS CLI bundles
Quick Start
import asyncio
from papert_code_sdk import query
async def main():
q = query(
prompt="List top-level files in this repository",
options={"cwd": "/path/to/repo"},
)
async for message in q:
if message.type == "assistant":
print(message.message.content)
asyncio.run(main())
Query Options
The query(prompt, options=...) API supports:
sessionId/session_id(reuse session id)resume(legacy alias forsessionId)cwdmodelpermissionMode/permission_modepathToPapertExecutable/path_to_papert_executableenvskillsPath/skillsPaths/skills_pathcanUseTool/can_use_toolmcpServers/mcp_serversabortController/abort_controllerdebugmaxSessionTurns/max_session_turnscoreTools/core_toolsexcludeTools/exclude_toolsallowedTools/allowed_toolsauthType/auth_typeincludePartialMessages/include_partial_messagesagents
Tool availability note:
By default, the SDK does not disable Papert Code tools. Tools are only restricted if you explicitly set coreTools/core_tools, excludeTools/exclude_tools, or enforce custom policy in canUseTool/can_use_tool.
Query Controls
The returned Query object supports:
get_session_id()is_closed()interrupt()set_permission_mode(mode)set_model(model)supported_commands()mcp_server_status()scheduler_list(cwd=None, include_disabled=None)scheduler_status(cwd=None)scheduler_add(job, cwd=None)scheduler_update(job_id, patch, cwd=None)scheduler_remove(job_id, cwd=None)scheduler_run(job_id, mode=None, cwd=None)scheduler_runs(job_id, limit=None, cwd=None)scheduler_start(cwd=None, max_concurrent=None, queue_policy=None)scheduler_stop(cwd=None)end_input()close()
Notes:
scheduler_add(...)auto-starts scheduler processing for that workspace store.- Scheduler activity can arrive asynchronously as
systemmessages withsubtype == "scheduler_event"while a stream/query is active.
Permission Callback
import asyncio
from papert_code_sdk import query
async def can_use_tool(tool_name, tool_input, options):
if tool_name and tool_name.startswith("read_"):
return {"behavior": "allow", "updatedInput": tool_input}
return {"behavior": "deny", "message": "Denied by app policy"}
async def main():
q = query(
prompt="Create a file and then read it",
options={"canUseTool": can_use_tool},
)
async for msg in q:
print(msg.type)
asyncio.run(main())
Abort Support
import asyncio
from papert_code_sdk import AbortController, is_abort_error, query
async def main():
controller = AbortController()
q = query(
prompt="Run a long task",
options={"abortController": controller},
)
async def cancel_soon():
await asyncio.sleep(2)
controller.abort()
asyncio.create_task(cancel_soon())
try:
async for msg in q:
print(msg.type)
except Exception as exc:
if is_abort_error(exc):
print("Aborted")
else:
raise
asyncio.run(main())
Multi-turn Streaming
import asyncio
from papert_code_sdk import query, SDKUserMessage
async def prompt_stream(session_id):
yield SDKUserMessage(
type="user",
session_id=session_id,
message={"role": "user", "content": "Create hello.txt"},
parent_tool_use_id=None,
)
yield SDKUserMessage(
type="user",
session_id=session_id,
message={"role": "user", "content": "Read hello.txt"},
parent_tool_use_id=None,
)
async def main():
first = query(prompt="Start a session")
session_id = first.get_session_id()
await first.close()
q = query(
prompt=prompt_stream(session_id),
options={"permissionMode": "auto-edit"},
)
async for msg in q:
print(msg.type)
asyncio.run(main())
Agent Wrapper
from papert_code_sdk import create_papert_agent
agent = create_papert_agent(
{
"options": {
"cwd": "/path/to/repo",
"permissionMode": "auto-edit",
}
}
)
query_handle = agent.run_prompt("Summarize TODOs")
High-level Client (Reusable Sessions)
import asyncio
from papert_code_sdk import create_client
async def main():
client = create_client({"cwd": "/path/to/repo", "permissionMode": "auto-edit"})
session = client.create_session(session_id="todo-session")
first = await session.send("Create TODO.md with 3 items")
second = await session.send("Now summarize what you wrote")
print(len(first), len(second))
await client.close()
asyncio.run(main())
ClientSession helpers:
stream(prompt, options=None)-> returns a streamingQuerysend(prompt, options=None)-> collects all messages and returns a listclose()andis_closed()
Multi-agent, Skills, and .papert setup
Detailed guide with complete project layout and end-to-end sample code:
/Users/azhar/code/coding-agent/papert-code/docs/cli/sdk-python-multi-agent-skills.md
Remote Server API Client (OpenAPI generated)
The package also includes a typed remote-control client generated from the
server OpenAPI contract (/openapi.json):
from papert_code_sdk import RemoteControlApiClient
api = RemoteControlApiClient("http://127.0.0.1:41242")
session = api.create_remote_session("server-token")
catalog = api.get_webui_catalog(session["sessionId"], session["token"])
print(catalog.get("releaseChannel"))
MCP Servers
from papert_code_sdk import query
q = query(
prompt="Use tool from external MCP server",
options={
"mcpServers": {
"my-server": {
"command": "node",
"args": ["server.js"],
"env": {"PORT": "3000"},
}
}
},
)
15 Python SDK Usecases
Use the cookbook runner:
python packages/sdk-python/examples/usecases.py --usecase 01
Available usecases (01-15):
- Basic prompt
- Prompt with custom cwd
- Prompt with explicit model
- Plan mode permissions
- Allowed tools allowlist
- Excluded tools denylist
- Custom skills path
- Specific skill instruction
- PDF to PPT using
pptxskill (--pdf /abs/path/to/file.pdf) - Abort controller cancellation
canUseToolpolicy callback- Multi-turn async input stream
- Reusable client session (
send) - Reusable client session (
stream) - Runtime subagents (
--agents reviewer,writer)
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file papert_code_sdk-0.1.1.tar.gz.
File metadata
- Download URL: papert_code_sdk-0.1.1.tar.gz
- Upload date:
- Size: 25.0 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.2
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
14a69b5ab31a3429a7506e8faae83da3ff8ecac073599d955446a09d6757eeca
|
|
| MD5 |
74223dfd7a5aeebfb905f64affbffd44
|
|
| BLAKE2b-256 |
3989906144770d553ce65db42f49cf682a72ef7e5fefccf6ab79d365787e2b2a
|
File details
Details for the file papert_code_sdk-0.1.1-py3-none-any.whl.
File metadata
- Download URL: papert_code_sdk-0.1.1-py3-none-any.whl
- Upload date:
- Size: 25.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.2
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
33456300047f33d9ace2ac4699f52bee566addcf41844d7a9a68f28fb7c50b13
|
|
| MD5 |
ea216d665c3e1c48aaa75a0c415006c8
|
|
| BLAKE2b-256 |
35c1aa6f7f5a8c1a63520a3b66f481d39e7c5b27b54cb95595b329c7587c5f26
|