API Reference

This page contains the API reference for the pctx-client package.

Pctx Client

class pctx_client.Pctx(tools: list[Tool | AsyncTool] | None = None, servers: list[HttpServerConfig | StdioServerConfig] | None = None, url: str = 'http://localhost:8080', api_key: str | None = None, execute_timeout: float = 30.0)[source]

Bases: object

PCTX Client

Execute TypeScript/JavaScript code with access to both MCP tools and local Python tools.

__init__(tools: list[Tool | AsyncTool] | None = None, servers: list[HttpServerConfig | StdioServerConfig] | None = None, url: str = 'http://localhost:8080', api_key: str | None = None, execute_timeout: float = 30.0)[source]

Initialize the PCTX client.

Parameters:
  • tools – List of local Python tools to register

  • servers – List of MCP servers to register. Each server can be either: - HTTP server: {“name”: “…”, “url”: “…”, “auth”: {…}} - stdio server: {“name”: “…”, “command”: “…”, “args”: […], “env”: {…}}

  • url – PCTX server URL (default: http://localhost:8080)

  • execute_timeout – Timeout for code execution in seconds (default: 30.0)

async __aenter__()[source]

Async context manager entry.

async __aexit__(exc_type, exc_val, exc_tb)[source]

Async context manager exit.

async connect()[source]

Creates CodeMode session, register local tools, and register MCP servers.

async disconnect()[source]

Disconnect closes current code-mode session.

async list_functions() ListFunctionsOutput[source]

List all available functions organized by namespace.

This is typically the first method you should call to discover what functions are available in the current session, including both registered local tools and MCP server functions.

Returns:

An object containing function signatures organized

by namespace. The code attribute contains TypeScript code with function declarations that can be used for reference.

Return type:

ListFunctionsOutput

Raises:

SessionError – If called before establishing a session via connect().

Example

>>> async with Pctx() as pctx:
...     functions = await pctx.list_functions()
...     print(functions.code)  # TypeScript declarations
async search_functions(query: str, k: int = 10) list[ListedFunction][source]

Search available functions matching query.

This is typically the first method you should call to discover what functions are available in the current session, including both registered local tools and MCP server functions.

Parameters:
  • query – Search query string to find relevant functions.

  • k – Max number of top results to return (default: 5).

Returns:

An list of matching function signatures matching the query

Return type:

list[ListedFunction]

Raises:
  • ImportError – If bm25s is not installed.

  • SessionError – If called before establishing a session via connect().

async get_function_details(functions: list[str]) GetFunctionDetailsOutput[source]

Get detailed information about specific functions.

After discovering available functions with list_functions(), use this method to get comprehensive details about parameter types, return values, and usage for the specific functions you need.

Parameters:

functions – List of function names in ‘namespace.functionName’ format (e.g., [‘Notion.apiPostSearch’, ‘Weather.getCurrentWeather’]).

Returns:

An object containing detailed TypeScript

declarations for the requested functions. The code attribute contains the full function signatures with JSDoc comments.

Return type:

GetFunctionDetailsOutput

Raises:

SessionError – If called before establishing a session via connect().

Example

>>> async with Pctx() as pctx:
...     details = await pctx.get_function_details(['Weather.getCurrentWeather'])
...     print(details.code)  # Detailed TypeScript with parameter info
async execute_typescript(code: str, disclosure: ToolDisclosure | Literal['catalog', 'filesystem'] = ToolDisclosure.CATALOG) ExecuteTypescriptOutput[source]

Execute TypeScript code that calls namespaced functions.

This method runs TypeScript code in a secure Deno sandbox with access to all registered functions (both local tools and MCP server functions).

Parameters:

code – TypeScript code to execute. Must include an async run() function that serves as the entry point. Functions must be called with their namespace prefix (e.g., ‘Weather.getCurrentWeather()’).

Returns:

An object containing execution results with attributes:
  • result: The value returned from the run() function

  • logs: Array of console.log() outputs

  • markdown(): Method to format output as markdown

Return type:

ExecuteTypescriptOutput

Raises:
  • SessionError – If called before establishing a session via connect().

  • TimeoutError – If execution exceeds the configured timeout (default 30s).

Notes

  • Code must define an async function run() as the entry point

  • Functions MUST be called as ‘Namespace.functionName’

  • Only functions from list_functions() are available

  • No access to fetch(), fs, or other standard Node/Deno APIs

  • Variables don’t persist between execute() calls

  • Return values are already parsed objects, not JSON strings

Example

>>> async with Pctx() as pctx:
...     code = '''
...     async function run() {
...         const result = await Weather.getCurrentWeather({ city: "NYC" });
...         console.log("Temperature:", result.temp);
...         return { temperature: result.temp };
...     }
...     '''
...     output = await pctx.execute_typescript(code)
...     print(output.markdown())  # Formatted results with logs
async execute(code: str, disclosure: ToolDisclosure | Literal['catalog', 'filesystem'] = ToolDisclosure.CATALOG) ExecuteTypescriptOutput[source]

Deprecated alias for execute_typescript.

async execute_bash(command: str) ExecuteBashOutput[source]

Execute a bash command in the virtual filesystem.

The bash environment has access to the virtual filesystem populated with tool definitions, README.md, and TypeScript definition files.

Parameters:

command – Bash command to execute (e.g., “ls /”, “cat /README.md”, “grep -r ‘function’ /”)

Returns:

ExecuteBashOutput with exit code, stdout, and stderr

Raises:

SessionError – If not connected to a session

Example

>>> async with Pctx() as pctx:
...     # List files in the virtual filesystem
...     output = await pctx.execute_bash("ls /")
...     print(output.stdout)  # Shows README.md, index.d.ts, etc.
...
...     # Read the README to see available functions
...     output = await pctx.execute_bash("cat /README.md")
...     print(output.stdout)  # Shows available functions
langchain_tools(disclosure: ToolDisclosure | Literal['catalog', 'filesystem'] = ToolDisclosure.CATALOG, descriptions: dict[Literal['execute_bash', 'execute_typescript', 'get_function_details', 'list_functions', 'search_functions'], str] | None = None) list[LangchainBaseTool][source]

Expose PCTX tools as LangChain tools

Parameters:
  • disclosure – Controls which tools are exposed and how function context is provided to the model. CATALOG (default) exposes list_functions, get_function_details, and execute_typescript — the agent discovers and retrieves function signatures before executing. FS exposes execute_bash and execute_typescript — the agent browses the virtual filesystem directly.

  • descriptions – Optional custom descriptions to override defaults.

Requires the ‘langchain’ extra to be installed:

pip install pctx[langchain]

Raises:

ImportError – If langchain is not installed.

Examples

>>> tools = pctx.langchain_tools()  # default: catalog
>>> tools = pctx.langchain_tools(disclosure="filesystem")
>>> tools = pctx.langchain_tools(descriptions={"execute_typescript": "Custom"})
crewai_tools(disclosure: ToolDisclosure | Literal['catalog', 'filesystem'] = ToolDisclosure.CATALOG, descriptions: dict[Literal['execute_bash', 'execute_typescript', 'get_function_details', 'list_functions', 'search_functions'], str] | None = None) list[CrewAiBaseTool][source]

Expose PCTX tools as CrewAI tools

Parameters:
  • disclosure – Controls which tools are exposed and how function context is provided to the model. CATALOG (default) exposes list_functions, get_function_details, and execute_typescript — the agent discovers and retrieves function signatures before executing. FS exposes execute_bash and execute_typescript — the agent browses the virtual filesystem directly.

  • descriptions – Optional custom descriptions to override defaults.

Requires the ‘crewai’ extra to be installed:

pip install pctx[crewai]

Raises:

ImportError – If crewai is not installed.

Examples

>>> tools = pctx.crewai_tools()  # default: catalog
>>> tools = pctx.crewai_tools(disclosure="filesystem")
>>> tools = pctx.crewai_tools(descriptions={"execute_typescript": "Custom"})
openai_agents_tools(disclosure: ToolDisclosure | Literal['catalog', 'filesystem'] = ToolDisclosure.CATALOG, descriptions: dict[Literal['execute_bash', 'execute_typescript', 'get_function_details', 'list_functions', 'search_functions'], str] | None = None) list[FunctionTool][source]

Expose PCTX tools as OpenAI Agents SDK function tools

Parameters:
  • disclosure – Controls which tools are exposed and how function context is provided to the model. CATALOG (default) exposes list_functions, get_function_details, and execute_typescript — the agent discovers and retrieves function signatures before executing. FS exposes execute_bash and execute_typescript — the agent browses the virtual filesystem directly.

  • descriptions – Optional custom descriptions to override defaults.

Requires the ‘openai’ extra to be installed:

pip install pctx[openai]

Raises:

ImportError – If openai is not installed.

Examples

>>> tools = pctx.openai_agents_tools()  # default: catalog
>>> tools = pctx.openai_agents_tools(disclosure="filesystem")
>>> tools = pctx.openai_agents_tools(descriptions={"execute_typescript": "Custom"})
pydantic_ai_tools(disclosure: ToolDisclosure | Literal['catalog', 'filesystem'] = ToolDisclosure.CATALOG, descriptions: dict[Literal['execute_bash', 'execute_typescript', 'get_function_details', 'list_functions', 'search_functions'], str] | None = None) list[PydanticAITool][source]

Expose PCTX tools as Pydantic AI tools

Parameters:
  • disclosure – Controls which tools are exposed and how function context is provided to the model. CATALOG (default) exposes list_functions, get_function_details, and execute_typescript — the agent discovers and retrieves function signatures before executing. FS exposes execute_bash and execute_typescript — the agent browses the virtual filesystem directly.

  • descriptions – Optional custom descriptions to override defaults.

Requires the ‘pydantic-ai’ extra to be installed:

pip install pctx[pydantic-ai]

Raises:

ImportError – If pydantic-ai is not installed.

Examples

>>> tools = pctx.pydantic_ai_tools()  # default: catalog
>>> tools = pctx.pydantic_ai_tools(disclosure="filesystem")
>>> tools = pctx.pydantic_ai_tools(descriptions={"execute_typescript": "Custom"})
claude_agent_sdk_tools(disclosure: ToolDisclosure | Literal['catalog', 'filesystem'] = ToolDisclosure.CATALOG, descriptions: dict[Literal['execute_bash', 'execute_typescript', 'get_function_details', 'list_functions', 'search_functions'], str] | None = None) list[ClaudeSdkMcpTool][source]

Expose PCTX tools as Claude Agent SDK tools

Parameters:
  • disclosure – Controls which tools are exposed and how function context is provided to the model. CATALOG (default) exposes list_functions, get_function_details, and execute_typescript — the agent discovers and retrieves function signatures before executing. FS exposes execute_bash and execute_typescript — the agent browses the virtual filesystem directly.

  • descriptions – Optional custom descriptions to override defaults.

Requires the ‘claude’ extra to be installed:

pip install pctx[claude]

Raises:

ImportError – If claude is not installed.

Examples

>>> tools = pctx.claude_agent_sdk_tools()  # default: catalog
>>> tools = pctx.claude_agent_sdk_tools(disclosure="filesystem")
>>> tools = pctx.claude_agent_sdk_tools(descriptions={"execute_typescript": "Custom"})

Tool Decorator

pctx_client.tool(fn: Callable, *, name: str | None = None, namespace: str = 'tools', description: str | None = None, input_schema: type[BaseModel] | dict[str, Any] | None = None, output_schema: Any | None = None) Tool | AsyncTool[source]
pctx_client.tool(fn: None = None, *, name: str | None = None, namespace: str = 'tools', description: str | None = None, input_schema: type[BaseModel] | dict[str, Any] | None = None, output_schema: Any | None = None) Callable[[Callable], Tool | AsyncTool]

Decorator that converts a function into a Tool or AsyncTool instance.

Can be used with or without parameters: - @tool - Uses function name as tool name - @tool(name=”custom_name”) - Uses custom name for the tool - @tool(namespace=”custom”, description=”…”) - With additional options - @tool(input_schema=MyModel) or @tool(input_schema={…}) - Override

signature inference with an explicit Pydantic model or JSON Schema dict

  • @tool(output_schema={…}) or @tool(output_schema=MyModel) - Override return-annotation inference with an explicit JSON Schema dict or Python type / typing construct

Parameters:
  • fn – The function to wrap. Only set when used as a bare @tool decorator; in the parameterized form @tool(...) it is None and the function is supplied on the second call.

  • name – Optional custom tool name (default: function’s __name__).

  • namespace – The namespace the tool belongs to (default: “tools”).

  • description – Optional description override (default: uses function docstring).

  • input_schema – Optional explicit input schema. When provided, signature inference is skipped and this schema is used directly.

  • output_schema – Optional explicit output schema. When provided, return- annotation inference is skipped and this schema is used directly.

Returns:

Either a Tool/AsyncTool instance (bare form) or a decorator function that creates one (parameterized form).

Examples

>>> @tool
... def my_function(x: int) -> int:
...     '''Adds one to x'''
...     return x + 1
>>> @tool(name="custom_name", namespace="math")
... def add_two(x: int) -> int:
...     return x + 2
>>> @tool(input_schema={"type": "object", "properties": {"x": {"type": "integer"}}, "required": ["x"]})
... def from_jsonschema(**kwargs) -> int:
...     return kwargs["x"] + 1

Tool Classes

class pctx_client.Tool(*, name: str, namespace: str, description: str = '', input_schema: Annotated[type[BaseModel] | dict[str, Any] | None, SkipValidation] = None, output_schema: Annotated[Any | None, SkipValidation] = None)[source]

Bases: BaseTool, ABC

Synchronous tool base class

invoke(**kwargs: Any) Any[source]

Calls the synchronous function with the provided arguments.

Parameters:

**kwargs – Arguments to pass to the function

Returns:

The result of the function call

Raises:

ValueError – If no synchronous function is available

model_config = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

model_post_init(context: Any, /) None

This function is meant to behave like a BaseModel method to initialise private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Parameters:
  • self – The BaseModel instance.

  • context – The context.

class pctx_client.AsyncTool(*, name: str, namespace: str, description: str = '', input_schema: Annotated[type[BaseModel] | dict[str, Any] | None, SkipValidation] = None, output_schema: Annotated[Any | None, SkipValidation] = None)[source]

Bases: BaseTool, ABC

Asynchronous tool base class

async ainvoke(**kwargs: Any) Any[source]

Calls the asynchronous function with the provided arguments.

Parameters:

**kwargs – Arguments to pass to the function

Returns:

The result of the function call

Raises:

ValueError – If no synchronous function is available

model_config = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

model_post_init(context: Any, /) None

This function is meant to behave like a BaseModel method to initialise private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Parameters:
  • self – The BaseModel instance.

  • context – The context.