Skip to main content

Open Context Protocol — Python client SDK

Project description

ocp-client

Python async client SDK for the Open Context Protocol (OCP) — a vendor-neutral protocol for sharing retrievable context, persistent state, and invalidation events across AI agents, models, and frameworks.

Install

pip install ocp-client

Quick start

import asyncio
from ocp_client import OCPClient

async def main():
    async with OCPClient.stdio(["ocp-server"]) as client:
        # Register and index a workspace
        ws = await client.workspace_register("file:///path/to/your/repo")
        await client.workspace_index(ws.workspace_id)

        # Semantic search
        results = await client.context_search(ws.workspace_id, "authentication middleware")
        for chunk, score in zip(results.chunks, results.scores):
            print(f"[{score:.3f}] {chunk.source.uri}")
            print(chunk.content[:200])

asyncio.run(main())

Requires ocp-server running — install with pip install ocp-server or run zero-install with uvx ocp-server.

Features

Workspaces & retrieval

# Register (idempotent — same URI always returns the same workspace_id)
ws = await client.workspace_register("file:///path/to/repo", name="my-repo")

# Index all supported files (.py, .ts, .go, .md, .yaml, ...)
result = await client.workspace_index(ws.workspace_id)
print(f"Indexed {result.indexed} chunks in {result.duration_ms} ms")

# Semantic k-NN search (k capped at 20)
results = await client.context_search(ws.workspace_id, "JWT token validation", k=10)

# Token-budget-aware context packing — ideal for LLM prompt assembly
pack = await client.context_pack(
    ws.workspace_id,
    intent="explain how authentication works",
    budget_tokens=4096,
)
print(pack.context)   # assembled context string, ready to inject into a prompt
print(pack.tokens)    # actual token count used

Scoped state

# Three scopes: "global", "session", "agent"
await client.state_set("config.model", "claude-3-5-sonnet", scope="global", workspace_id=ws.workspace_id)
entry = await client.state_get("config.model", scope="global", workspace_id=ws.workspace_id)
print(entry.value)    # "claude-3-5-sonnet"
print(entry.version)  # 1

# Optimistic concurrency — fails with CONFLICT if version is stale
result = await client.state_set("counter", 2, scope="global",
                                 workspace_id=ws.workspace_id, if_version=result.version)

# TTL — auto-expires after N seconds
await client.state_set("temp.flag", True, scope="session",
                        workspace_id=ws.workspace_id, session_id=sess.session_id,
                        ttl_seconds=300)

Session coordination

import uuid

# Open a session
sess = await client.session_open(ws.workspace_id, session_id=str(uuid.uuid4()))

# Hand off between agents
handoff = await client.session_handoff(
    session_id=sess.session_id,
    from_agent="planner",
    to_agent="executor",
    message={"task": "deploy to staging"},
)

# Checkpoint before a risky operation
ckpt = await client.session_checkpoint(sess.session_id, label="before-deploy", include_state=True)

# Restore from checkpoint (creates a new session with copied state)
restored = await client.session_restore(ckpt.checkpoint_id)

await client.session_close(sess.session_id)

Events

# Subscribe to workspace events
sub = await client.events_subscribe(
    ws.workspace_id,
    types=["chunk.invalidated", "state.changed"],
)

# Replay events since a timestamp
sub = await client.events_subscribe(ws.workspace_id, since="2026-01-01T00:00:00Z")

await client.events_unsubscribe(sub.subscription_id)

Error handling

from ocp_client.types import OCPError

try:
    chunk = await client.context_get_chunk(chunk_id)
except OCPError as e:
    print(e.code)     # STALE | CHUNK_NOT_FOUND | CONFLICT | PERMISSION_DENIED | ...
    print(e.message)

Connecting to a remote HTTP server

from mcp import ClientSession
from mcp.client.sse import sse_client

async with sse_client("http://localhost:8080/sse",
                      headers={"Authorization": "Bearer my-key"}) as (read, write):
    async with ClientSession(read, write) as session:
        await session.initialize()
        client = OCPClient(session)
        # ... use client ...

Links

License

Apache-2.0 — see LICENSE

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

ocp_client-0.2.1.tar.gz (5.0 kB view details)

Uploaded Source

Built Distribution

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

ocp_client-0.2.1-py3-none-any.whl (6.0 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: ocp_client-0.2.1.tar.gz
  • Upload date:
  • Size: 5.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for ocp_client-0.2.1.tar.gz
Algorithm Hash digest
SHA256 d66d9ffd1d4c2880222791cd046845fd50f3522f51e72bd7d2ca7ceec20d3625
MD5 a01f4ef254e534ad2dde8b4c0b9b741c
BLAKE2b-256 5cc7530c70811a706afcd0c94bef5d23b2be7fc7a0dec6094ce308096d9b5694

See more details on using hashes here.

Provenance

The following attestation bundles were made for ocp_client-0.2.1.tar.gz:

Publisher: publish.yml on Rajesh1213/OCP

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

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

File metadata

  • Download URL: ocp_client-0.2.1-py3-none-any.whl
  • Upload date:
  • Size: 6.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for ocp_client-0.2.1-py3-none-any.whl
Algorithm Hash digest
SHA256 06c7061e2c02843dfb8f81eccca372b7c35f92f1f08f40d0fa44dae3850b3fac
MD5 1af2b7a60df5b36ed1382c4f819c3888
BLAKE2b-256 9a29967655a10c2d109a02b6a380248e332261c7ba54f1b7ca485a8010102fca

See more details on using hashes here.

Provenance

The following attestation bundles were made for ocp_client-0.2.1-py3-none-any.whl:

Publisher: publish.yml on Rajesh1213/OCP

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

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