Skip to main content

A Python client for Tool Server Protocol (TSP)

Project description

pyTSPClient

A lightweight Python client for the Tool Server Protocol (TSP). It provides a simple, asynchronous way to interact with tool servers (like gtsp) via the stdio mode.

Features

  • Asynchronous IO: Built with asyncio.
  • Full Protocol Support: Methods for initialize, tool, sandbox, and shutdown.
  • Event Handling: Easy subscription to server-sent events.
  • Error Handling: Custom TSPException with error codes.
  • Logging: Captures server stderr for easier debugging.

Installation

For Users

pip install pytspclient

For Developers (Editable Mode)

If you are developing locally:

git clone https://github.com/alexazhou/TSP.git
cd TSP/client/pytspclient
pip install -e .

Quick Start

import asyncio
from pytspclient import TSPClient, TSPException

async def main():
    # command to launch the TSP server
    client = TSPClient(["./gtsp", "--mode", "stdio"])
    
    # 1. Connect (starts the subprocess)
    await client.connect()
    
    try:
        # 2. Initialize handshake
        # protocol_version is hardcoded to 0.3 internally
        init_data = await client.initialize(
            client_info={"name": "my-agent"},
            include=["read_file", "write_file"]
        )
        print(f"Connected to: {init_data.server_info.get('name')}")

        # 3. Call a tool
        try:
            result = await client.tool("read_file", {"file_path": "test.txt"})
            print(f"File content: {result['content']}")
        except TSPException as e:
            print(f"Tool failed: [{e.code}] {e.message}")

        # 4. Graceful Shutdown
        await client.shutdown()
        
    finally:
        # Ensure resources are cleaned up
        await client.disconnect()

if __name__ == "__main__":
    asyncio.run(main())

API Reference

TSPClient

__init__(command: List[str], request_timeout_sec: int = 30)

  • command: The shell command to run the TSP server.
  • request_timeout_sec: Timeout for each request.

async connect()

Spawns the TSP server process and starts the internal read loops for stdout and stderr.

async disconnect()

Forcefully terminates the process and fails all pending requests.

async initialize(...) -> TSPInitializeResult

Handshake with the server. Protocol version is internally set to 0.3. Parameters:

  • client_info: optional metadata about the client.
  • include: optional list of tools to enable.
  • exclude: optional list of tools to disable.

Returns a TSPInitializeResult object.

async tool(tool_name: str, input_params: Dict[str, Any]) -> Dict[str, Any]

Executes a specific tool on the server.

async sandbox(config: Dict[str, Any]) -> Dict[str, Any]

Configures the server's sandbox/workspace environment.

async shutdown()

Sends a shutdown request and then calls disconnect().

add_event_handler(handler: Callable[[TSPEvent], None])

Registers a callback for server-sent events.

def on_event(event: TSPEvent):
    print(f"Received event: {event.event} with data: {event.data}")

client.add_event_handler(on_event)

Data Classes

TSPInitializeResult

  • protocol_version: str
  • capabilities: Dict[str, Any]
  • server_info: Dict[str, Any]

Exceptions

TSPException

Raised when the server returns an error response.

  • code: The error code (e.g., tsp/error, tool/not_found).
  • message: Human-readable error message.

License

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pytspclient-0.2.1.tar.gz (9.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

pytspclient-0.2.1-py3-none-any.whl (10.6 kB view details)

Uploaded Python 3

File details

Details for the file pytspclient-0.2.1.tar.gz.

File metadata

  • Download URL: pytspclient-0.2.1.tar.gz
  • Upload date:
  • Size: 9.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.15

File hashes

Hashes for pytspclient-0.2.1.tar.gz
Algorithm Hash digest
SHA256 5cb0483798079e92f3fba9418c895258839e58cac9257479775cbddf131944cb
MD5 56ec8b38f234ca6fbdd67321cd86d73c
BLAKE2b-256 41efe4fc5a9d1839ec9288e9e2acf6f8f82b7b634070b9d005c55b6661c22821

See more details on using hashes here.

File details

Details for the file pytspclient-0.2.1-py3-none-any.whl.

File metadata

  • Download URL: pytspclient-0.2.1-py3-none-any.whl
  • Upload date:
  • Size: 10.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.15

File hashes

Hashes for pytspclient-0.2.1-py3-none-any.whl
Algorithm Hash digest
SHA256 644cb30bd7dad936a265d2c1722e81245a12d08e1114d90d407f9a5d833762d6
MD5 59b4587b214b3ea431fe7603af5bca25
BLAKE2b-256 851a7c50e936c2ef1239cdbf686a58deb546e9c33ce1dedc9153f69d3bc80a8d

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page