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.3.0.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.3.0-py3-none-any.whl (6.0 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: ocp_client-0.3.0.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.3.0.tar.gz
Algorithm Hash digest
SHA256 2eab2b5d3361c3d738c06c10f8ea1e5187deb83f7a668b7a6e3434fbcca9ddc4
MD5 41568ae50c253091626db9c733b9ea1a
BLAKE2b-256 7c1ae122b56804284c9a9401ed1534b9f247232cb9b53bab8b14261ea9a54cb2

See more details on using hashes here.

Provenance

The following attestation bundles were made for ocp_client-0.3.0.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.3.0-py3-none-any.whl.

File metadata

  • Download URL: ocp_client-0.3.0-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.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 24271240a708e80acb1784920dc93c518560ad78918dcfe5a82699be51144a84
MD5 ece41dc805224648a27ec4c6d5c587c0
BLAKE2b-256 56503913c411311eec92494e023ec86aadd1ebcc15d9d3089375901ccf024ffa

See more details on using hashes here.

Provenance

The following attestation bundles were made for ocp_client-0.3.0-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