Skip to main content

Installation

With optional FastAPI support:

Requirements

  • Python 3.10+
  • httpx (async HTTP)
  • pydantic (type validation)
  • pyjwt[crypto] (JWT verification)

Prerequisites

Before using the API, complete setup at ctxprotocol.com:
1

Sign in

Creates your embedded wallet
2

Set spending cap

Approve USDC spending on the ContextRouter (one-time setup)
3

Fund wallet

Add USDC for tool execution fees
4

Generate API key

In Settings page

Quick Start

Want per-call pricing and spending limits? The SDK also supports Execute mode for direct method calls inside session budgets. See Two SDK Modes below.

Two SDK Modes

The SDK offers two payment models:
You have access to both modes. Pick the one that fits your use case.
  • Use Query (client.query.run()) when you want a managed librarian contract where Context handles discovery/orchestration (up to 100 MCP calls per response turn) and returns answer_with_evidence or evidence_only. Pay-per-response (~$0.10).
  • Use Execute (client.tools.execute()) when your app/agent is the librarian and you want per-call pricing with spending limits (~$0.001/call).
Most developers start with Query and add Execute later for specific pipelines that need raw data or explicit cost control. You can use both in the same application.

Execute Quick Start

Full working example: See examples/client/execute_client.py for a complete Execute-mode client with multi-call session management and spend tracking.
Mixed listings are first-class: one listing can expose methods to both modes. Methods without explicit execute pricing remain Query-only until pricing metadata is added.
Compatibility: payload fields like price and price_per_query are kept for backward compatibility. In Query mode, they represent listing-level price per response turn. A future major release can add response-named aliases (for example, price_per_response) before deprecating legacy names.

Configuration

Client Options

Always use async with context manager or call await client.close() when done to properly release resources.
The Python SDK automatically retries transient failures (HTTP 5xx, transport errors, and timeouts) with exponential backoff.

API Reference

Discovery

client.discovery.search(query, limit?)

Search for tools matching a query string, with optional mode-aware filters. Parameters: Returns: list[Tool]
If you enable Favorites-Only Auto Mode in Settings, SDK discovery and query requests made with the same API key inherit that account default automatically. Set favorites_only=True or favorites_only=False per request to override it. On Query requests with explicit tools, manual tool selection wins and favorites_only is ignored.

Get featured/popular tools. Parameters: Returns: list[Tool]

client.discovery.get(tool_id)

Fetch one tool listing by UUID. Parameters: Returns: Tool

Tools (Execute Mode)

client.tools.execute(tool_id, tool_name, args?)

Execute a single tool method. Execute calls can run inside a session budget (max_spend_usd) with automatic payment after delivery. Parameters: Returns: ExecutionResult

client.tools.start_session(max_spend_usd)

Start an execute session budget envelope.

client.tools.get_session(session_id)

Fetch current execute session status/spend.

client.tools.close_session(session_id)

Close an execute session and trigger final flush behavior.

Developer

client.developer.update_tool(tool_id, ...)

Update contributor-owned tool metadata programmatically. This is for developers managing their own listings, not for buyer query execution. Parameters: Returns: dict[str, Any]

Query (Pay-Per-Response)

The Query API is Context’s response marketplace. Instead of buying raw API calls, you’re buying curated intelligence. Ask a question, pay once, and get a grounded, managed answer.

client.query.run(query, tools?, favorites_only?, agent_model_id?, response_shape?, include_data?, include_data_url?, include_developer_trace?, idempotency_key?)

Run an agentic query. The managed runtime handles tool discovery, ambiguity resolution, multi-tool execution (up to 100 MCP calls per response turn as a safety cap), and grounding — and returns the selected Query response contract (answer_with_evidence or evidence_only, default answer_with_evidence). Query billing is pay-per-response with automatic payment after delivery. Since SDK 0.21.0, run() is backed by the durable job path (start() + poll()), so a single call reliably covers the full 1800-second hosted compute ceiling and survives transient connection drops. Pass optional interval_ms / timeout_ms keyword arguments to shorten the client-side wait. Parameters: Returns: QueryResult
agent_model_id lets headless users choose the main librarian agent model explicitly. If omitted, the API uses its managed default agent model. Internal tool selection remains managed by the server. If response_shape is evidence_only, Context skips the extra prose synthesis layer, but the librarian agent still runs to fetch, compute, and ground the result.Import AGENT_MODEL_IDS and DEFAULT_AGENT_MODEL_ID from ctxprotocol to see the current supported slugs. Omit agent_model_id to use the managed default (DEFAULT_AGENT_MODEL_ID).
The query runtime now exposes a single managed executor surface. The server decides internal budgets, ambiguity handling, and exploration policy from the query itself instead of asking SDK callers to choose a lane.include_developer_trace and orchestration_metrics are optional diagnostic surfaces that are both gated on include_developer_trace=True — they are None on the response envelope when the flag is omitted. Their inner fields are typed but may evolve across rollouts as the managed runtime changes, so treat them as debugging signals rather than a stable execution contract.The developer_trace object mirrors the chat app’s Developer Logs card (same iterative-runtime signals): orchestration_mode="query", summary (tool calls, retries, loop steps), timeline, tool_call_history (with is_code_interpreter flags on Python sandbox calls), execution_trace, verification (with bounded_answer_reason / bounded_answer_data_gap when a safety guardrail stopped retries), and diagnostics (selection, execution contract, cost, contributor searches, tool-registry stats, retry budget, stage timing). The initial_code / final_code fields are the // iterative execution: no generated code sentinel kept for trace compatibility with the previous VM-based runtime — no JavaScript is generated or executed.

Structured Response Shapes

Query is Context’s managed librarian contract. You can choose how much structure you want back: The first-party chat app defaults to answer_with_evidence, but it is using the same Query contract you get in the SDK.

Query Envelope Fields

When response_shape is answer_with_evidence or evidence_only, the result may include:

High-Fidelity Rehydration (Retrieval-First Synthesis)

When retrieval-first rollout is enabled in the deployment, the query runtime can switch synthesis context assembly from baseline truncation to retrieval-first slices for full-data or truncation-sensitive requests.
  • Stage artifacts are emitted in request-scoped internal storage (selection, execution, synthesis). The scout stage is a legacy artifact slot — scout probe execution is disabled in the current iterative runtime, so no scout stage artifacts are produced.
  • Retrieval primitives (path lookup, array windows/sampling, keyword slices, top-K relevance) are used to build a bounded context pack from canonical execution data.
  • Final synthesis still passes through the existing synthesis safety contract.
  • include_data returns a bounded inline preview when needed, and include_data_url/artifacts.canonical_data_ref reference the same canonical execution dataset used by retrieval-first assembly.

Resume and Fork

Every Query response can include query_session handles. Use resume_from to continue from a previous attempt, or fork_from to branch from an attempt while preserving lineage.

client.query.stream(query, tools?, favorites_only?, agent_model_id?, response_shape?, include_data?, include_data_url?, include_developer_trace?, idempotency_key?)

Runs the same query pipeline as run() but over a live SSE connection, yielding events in real-time. Returns: AsyncGenerator of stream events
Use the same idempotency_key when retrying the same logical request after network or timeout errors.
If you stream with response_shape="evidence_only", expect the structured result on the final done event and few or no text-delta events.
query.stream() has a default client stream timeout of 600 seconds (configurable via stream_timeout_seconds). query.run() is job-backed since 0.21.0 and is not bound by the stream timeout — it waits up to 31 minutes by default. The hosted compute ceiling is 1800 seconds on every query path — sync, async jobs, and MCP.

client.query.run_or_poll(query, ..., interval_ms?, timeout_ms?)

Start a durable query job and wait internally until it completes. This is the recommended one-call helper for LLM agents and scheduled agent frameworks because the entire wait happens inside one SDK call (one model turn) instead of asking the host LLM to call get_status() 20-40 times.
The defaults are agent-friendly: status is checked every 5 seconds over plain HTTP (HTTP polls cost no model tokens — model turns do), and the client waits up to 31 minutes, slightly beyond the 1800-second hosted compute ceiling. Only pass interval_ms / timeout_ms if you need a shorter client-side wait. Since 0.21.0, run() and run_or_poll() share the same durable job-backed path, so either works for uncertain query times. run_or_poll() remains the explicit name for readers of agent code.

Async Query Jobs

Use async jobs when a query may exceed a single blocking SDK request.
For LLM agents, prefer run_or_poll() or start() + poll(). Reserve get_status() loops for normal programs where each check is just an HTTP request, never for LLM agents where each check is a full model turn.

Types

Import Types


Tool


McpTool

For argument guidance, use standard JSON Schema fields directly inside inputSchema properties. Put fallback values in default and sample invocations in examples. Do not rely on custom _meta.inputExamples.

ExecutionResult (Execute Mode)

ExecuteSessionSpend


QueryResult (Pay-Per-Response)


Context Requirement Types

For MCP server contributors building tools that need user context:
Why Context Injection Matters:
  • No Auth Required: Public blockchain/user data is fetched by the platform
  • Security: Your MCP server never handles private keys
  • Simplicity: You receive structured, type-safe data
Python reference implementation: Hummingbot contributor server.
For practical guidance on these pacing hints, see Tool Metadata.

Injected Context Types

HyperliquidContext

PolymarketContext

WalletContext


Contributor Search Helpers

If you are building a contributor for a search-hard venue, the Python SDK ships an optional helper surface at ctxprotocol.contrib.search. Use it only when the venue’s upstream search is weak enough that deterministic retrieval plus a bounded model judge materially improves candidate resolution. Do not use it for venues that already expose reliable direct search.
What this module is for:
  • contributor-side intent shaping, candidate normalization, shortlist construction, and validated resolution
  • provider-agnostic judge injection with stable override knobs for provider, model, timeout, budget, and disabled
  • machine-readable artifact generation via build_contributor_search_validation_artifact(...)
  • runtime trace inspection via extract_contributor_searches_from_developer_trace(trace) or result.developer_trace.diagnostics.contributor_searches
Operational rules:
  • extra judge spend is contributor-owned in this rollout, so recover it through your own listing response price and/or execute pricing
  • keep deterministic validation around every judge result; malformed, timed-out, over-budget, or contradictory judgments must degrade honestly
  • save replayable validation artifacts alongside your contributor examples. Current reference fixtures live under examples/client/validation/

Error Handling

The SDK raises ContextError with specific error codes:

Error Codes


Securing Your Tool (MCP Contributors)

If you’re building an MCP server, verify incoming requests using ctxprotocol.
If you wrap a search-hard venue whose upstream API cannot reliably resolve the right market or entity, follow Optional Contributor Search Helpers. That pattern stays contributor-side, keeps provider credentials contributor-owned, and does not change client.query.run() or _meta.
Free vs Paid Security Requirements:
FastMCP is the fastest way to build MCP servers. Use ctxprotocol middleware:
FastMCP auto-generates outputSchema from Pydantic return types and includes structuredContent in responses - both required by Context Protocol.

Option 2: Raw FastAPI

For more control, use FastAPI with our middleware:

Manual Verification

For more control, use the lower-level utilities:

Verification Options

MCP Security Model

Critical for tool contributors: Not all MCP methods require authentication. The middleware selectively protects only execution methods.
What this means in practice:
  • https://your-mcp.com/mcp + initialize → Works without auth
  • https://your-mcp.com/mcp + tools/list → Works without auth
  • https://your-mcp.com/mcp + tools/callRequires Context Protocol JWT
This matches standard API patterns (OpenAPI schemas are public, GraphQL introspection is open).

Payment Flow

Context supports two settlement timings:
  1. Query mode (client.query.*) uses deferred settlement after the response is delivered
  2. Execute mode (client.tools.execute) accrues per-call method spend into execute sessions with automatic batch payment
  3. In both modes, spending caps are enforced via ContextRouter allowance checks
  4. 90% goes to the tool developer, 10% goes to the protocol